magpie-multi-usage 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -0
- package/README.md +153 -2
- package/README.zh-CN.md +154 -0
- package/hooks.mjs +31 -0
- package/index.mjs +103 -0
- package/package.json +68 -4
- package/page/boot.js +161 -0
- package/page/icon.svg +6 -0
- package/page/index.html +46 -0
- package/src/aggregator.mjs +643 -0
- package/src/atomic-fs.mjs +207 -0
- package/src/config.mjs +435 -0
- package/src/github-store.mjs +722 -0
- package/src/http-server.mjs +526 -0
- package/src/magpie-client.mjs +670 -0
- package/src/sync-engine.mjs +958 -0
- package/src/ui/app.css +877 -0
- package/src/ui/app.js +869 -0
- package/src/ui/index.html +135 -0
- package/src/ui/view-model.mjs +410 -0
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
aggregateDevices,
|
|
7
|
+
buildDeviceManifest,
|
|
8
|
+
buildMonthlySnapshot,
|
|
9
|
+
computeMonthContentHash,
|
|
10
|
+
formatLocalDateParts,
|
|
11
|
+
isValidCalendarMonth,
|
|
12
|
+
} from "./aggregator.mjs";
|
|
13
|
+
import {
|
|
14
|
+
assertContainedPath,
|
|
15
|
+
ensureDir,
|
|
16
|
+
readJsonStrict,
|
|
17
|
+
sha256Hex,
|
|
18
|
+
withFileLock,
|
|
19
|
+
writeJsonAtomic,
|
|
20
|
+
} from "./atomic-fs.mjs";
|
|
21
|
+
import {
|
|
22
|
+
getConfigPaths,
|
|
23
|
+
loadConfig,
|
|
24
|
+
loadGitHubToken,
|
|
25
|
+
resolveDataDir,
|
|
26
|
+
} from "./config.mjs";
|
|
27
|
+
import { createGitHubRelayStore } from "./github-store.mjs";
|
|
28
|
+
import {
|
|
29
|
+
DEVICE_ID_PATTERN,
|
|
30
|
+
listLocalMonths,
|
|
31
|
+
loadLocalMonthRows,
|
|
32
|
+
resolveDeviceIdentity,
|
|
33
|
+
resolveGatewayBaseUrl,
|
|
34
|
+
syncLocalLedger,
|
|
35
|
+
} from "./magpie-client.mjs";
|
|
36
|
+
|
|
37
|
+
const REMOTE_PULL_CONCURRENCY = 3;
|
|
38
|
+
const GEN_ID_PATTERN = /^[a-zA-Z0-9_-]{4,64}$/;
|
|
39
|
+
|
|
40
|
+
const sharedEngines = new Map();
|
|
41
|
+
|
|
42
|
+
function sanitizeErrorForUi(error, secretToken = "") {
|
|
43
|
+
let msg = error?.message ? String(error.message) : String(error || "Unknown error");
|
|
44
|
+
if (secretToken) {
|
|
45
|
+
msg = msg.split(secretToken).join("[REDACTED]");
|
|
46
|
+
}
|
|
47
|
+
return msg.slice(0, 300);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function buildTargetKey({ repoId, repo, branch, prefix }) {
|
|
51
|
+
const idPart = repoId || repo || "";
|
|
52
|
+
return sha256Hex(`${idPart}|${branch || ""}|${prefix || "devices"}`).slice(0, 24);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function buildConfigScopeKey(config) {
|
|
56
|
+
return sha256Hex(`${config.repo || ""}|${config.branch || ""}|${config.prefix || "devices"}`).slice(0, 24);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function readStateStrict(stateFile) {
|
|
60
|
+
const result = await readJsonStrict(stateFile);
|
|
61
|
+
if (result.status === "missing") {
|
|
62
|
+
return {};
|
|
63
|
+
}
|
|
64
|
+
if (result.status === "error") {
|
|
65
|
+
throw new Error(`Failed to read plugin state at ${stateFile}: ${result.code}`);
|
|
66
|
+
}
|
|
67
|
+
if (result.value === null || typeof result.value !== "object" || Array.isArray(result.value)) {
|
|
68
|
+
throw new Error(`Plugin state at ${stateFile} must be a JSON object.`);
|
|
69
|
+
}
|
|
70
|
+
return result.value;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function runWithConcurrency(items, concurrency, worker) {
|
|
74
|
+
const results = new Array(items.length);
|
|
75
|
+
let cursor = 0;
|
|
76
|
+
|
|
77
|
+
async function next() {
|
|
78
|
+
while (cursor < items.length) {
|
|
79
|
+
const index = cursor;
|
|
80
|
+
cursor += 1;
|
|
81
|
+
try {
|
|
82
|
+
results[index] = { status: "fulfilled", value: await worker(items[index], index) };
|
|
83
|
+
} catch (reason) {
|
|
84
|
+
results[index] = { status: "rejected", reason };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const runners = Array.from({ length: Math.min(concurrency, items.length) }, () => next());
|
|
90
|
+
await Promise.all(runners);
|
|
91
|
+
return results;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Read and verify a committed remote device generation via current.json.
|
|
96
|
+
* Returns { valid: true, generationId, manifest, snapshots } only when the
|
|
97
|
+
* manifest and EVERY referenced month exist and match their sha256 hashes.
|
|
98
|
+
*/
|
|
99
|
+
async function readCommittedDeviceGeneration(deviceCacheDir) {
|
|
100
|
+
const pointerRead = await readJsonStrict(path.join(deviceCacheDir, "current.json"));
|
|
101
|
+
if (pointerRead.status === "missing") {
|
|
102
|
+
return { status: "missing" };
|
|
103
|
+
}
|
|
104
|
+
if (pointerRead.status === "error" || !GEN_ID_PATTERN.test(String(pointerRead.value?.generation || ""))) {
|
|
105
|
+
return { status: "corrupt", error: "Cached generation pointer is unreadable." };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const generationId = pointerRead.value.generation;
|
|
109
|
+
const genDir = assertContainedPath(deviceCacheDir, path.join(deviceCacheDir, "generations", generationId));
|
|
110
|
+
const manifestRead = await readJsonStrict(path.join(genDir, "manifest.json"));
|
|
111
|
+
if (manifestRead.status !== "ok") {
|
|
112
|
+
return { status: "corrupt", error: "Cached manifest is missing or unreadable." };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const manifest = manifestRead.value;
|
|
116
|
+
if (!manifest || typeof manifest !== "object" || !manifest.months || typeof manifest.months !== "object") {
|
|
117
|
+
return { status: "corrupt", error: "Cached manifest has an invalid structure." };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const snapshots = [];
|
|
121
|
+
const snapshotsByMonth = new Map();
|
|
122
|
+
|
|
123
|
+
for (const monthKey of Object.keys(manifest.months).sort()) {
|
|
124
|
+
if (!isValidCalendarMonth(monthKey)) {
|
|
125
|
+
return { status: "corrupt", error: `Cached manifest contains invalid month ${monthKey}.` };
|
|
126
|
+
}
|
|
127
|
+
const expectedHash = manifest.months[monthKey]?.sha256;
|
|
128
|
+
const monthPath = assertContainedPath(genDir, path.join(genDir, `${monthKey}.json`));
|
|
129
|
+
const monthRead = await readJsonStrict(monthPath);
|
|
130
|
+
if (monthRead.status !== "ok") {
|
|
131
|
+
return { status: "corrupt", error: `Cached month ${monthKey} is missing or unreadable.` };
|
|
132
|
+
}
|
|
133
|
+
if (expectedHash && computeMonthContentHash(monthRead.value) !== expectedHash) {
|
|
134
|
+
return { status: "corrupt", error: `Cached month ${monthKey} failed integrity verification.` };
|
|
135
|
+
}
|
|
136
|
+
snapshots.push(monthRead.value);
|
|
137
|
+
snapshotsByMonth.set(monthKey, monthRead.value);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
status: "ok",
|
|
142
|
+
generationId,
|
|
143
|
+
manifest,
|
|
144
|
+
snapshots,
|
|
145
|
+
snapshotsByMonth,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Create a single-flight, fault-isolated multi-device sync engine backed by
|
|
151
|
+
* local Magpie ingestion and a pluggable remote relay store (GitHub by default).
|
|
152
|
+
*/
|
|
153
|
+
export function createSyncEngine({
|
|
154
|
+
dataDir,
|
|
155
|
+
magpieConfigDir,
|
|
156
|
+
defaults = {},
|
|
157
|
+
env = process.env,
|
|
158
|
+
homeDir = os.homedir(),
|
|
159
|
+
hostname = os.hostname(),
|
|
160
|
+
fetchImpl = globalThis.fetch,
|
|
161
|
+
apiBaseUrl,
|
|
162
|
+
gatewayBaseUrl,
|
|
163
|
+
pluginVersion = "0.1.0",
|
|
164
|
+
timeZone,
|
|
165
|
+
now = () => Date.now(),
|
|
166
|
+
storeFactory = createGitHubRelayStore,
|
|
167
|
+
} = {}) {
|
|
168
|
+
const resolvedDataDir = path.resolve(dataDir);
|
|
169
|
+
const paths = getConfigPaths(resolvedDataDir);
|
|
170
|
+
|
|
171
|
+
let ingestInFlight = null;
|
|
172
|
+
let pushInFlight = null;
|
|
173
|
+
let pullInFlight = null;
|
|
174
|
+
let lastDebouncedPushMs = 0;
|
|
175
|
+
let localSyncStatus = {
|
|
176
|
+
status: "ok",
|
|
177
|
+
lastSyncedAt: null,
|
|
178
|
+
lastError: null,
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
async function updateState(mutator) {
|
|
182
|
+
return withFileLock(paths.syncLockFile, async () => {
|
|
183
|
+
await ensureDir(paths.root, 0o700);
|
|
184
|
+
const current = await readStateStrict(paths.stateFile);
|
|
185
|
+
const next = mutator(current);
|
|
186
|
+
await writeJsonAtomic(paths.stateFile, next, { mode: 0o600 });
|
|
187
|
+
return next;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function buildLocalSnapshots({ config, identity, revision }) {
|
|
192
|
+
const months = await listLocalMonths(resolvedDataDir);
|
|
193
|
+
const snapshots = [];
|
|
194
|
+
const monthHashes = {};
|
|
195
|
+
|
|
196
|
+
for (const month of months) {
|
|
197
|
+
const rows = await loadLocalMonthRows(resolvedDataDir, month);
|
|
198
|
+
const { snapshot, sha256 } = buildMonthlySnapshot({
|
|
199
|
+
deviceId: identity.deviceId,
|
|
200
|
+
month,
|
|
201
|
+
rows,
|
|
202
|
+
revision,
|
|
203
|
+
updatedAt: new Date(now()).toISOString(),
|
|
204
|
+
filterForwarded: config.filterForwarded,
|
|
205
|
+
});
|
|
206
|
+
if (Object.keys(snapshot.days).length > 0) {
|
|
207
|
+
snapshots.push(snapshot);
|
|
208
|
+
monthHashes[month] = sha256;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const manifest = buildDeviceManifest({
|
|
213
|
+
deviceId: identity.deviceId,
|
|
214
|
+
displayName: identity.displayName,
|
|
215
|
+
platform: process.platform,
|
|
216
|
+
pluginVersion,
|
|
217
|
+
revision,
|
|
218
|
+
updatedAt: new Date(now()).toISOString(),
|
|
219
|
+
snapshots,
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
return { snapshots, monthHashes, manifest };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function runIngestLocal() {
|
|
226
|
+
const config = await loadConfig(resolvedDataDir, { defaults });
|
|
227
|
+
const identity = await resolveDeviceIdentity({
|
|
228
|
+
dataDir: resolvedDataDir,
|
|
229
|
+
magpieConfigDir,
|
|
230
|
+
deviceNameOverride: config.deviceName,
|
|
231
|
+
hostname,
|
|
232
|
+
env,
|
|
233
|
+
homeDir,
|
|
234
|
+
});
|
|
235
|
+
const baseUrl = gatewayBaseUrl || await resolveGatewayBaseUrl({ env, magpieConfigDir, homeDir });
|
|
236
|
+
|
|
237
|
+
try {
|
|
238
|
+
const result = await syncLocalLedger({
|
|
239
|
+
dataDir: resolvedDataDir,
|
|
240
|
+
baseUrl,
|
|
241
|
+
fetchImpl,
|
|
242
|
+
timeZone,
|
|
243
|
+
});
|
|
244
|
+
localSyncStatus = {
|
|
245
|
+
status: "ok",
|
|
246
|
+
lastSyncedAt: new Date(now()).toISOString(),
|
|
247
|
+
lastError: null,
|
|
248
|
+
};
|
|
249
|
+
return { ok: true, identity, config, result };
|
|
250
|
+
} catch (error) {
|
|
251
|
+
const hasLocalData = (await listLocalMonths(resolvedDataDir)).length > 0;
|
|
252
|
+
localSyncStatus = {
|
|
253
|
+
status: hasLocalData ? "stale" : "error",
|
|
254
|
+
lastSyncedAt: localSyncStatus.lastSyncedAt,
|
|
255
|
+
lastError: sanitizeErrorForUi(error),
|
|
256
|
+
};
|
|
257
|
+
return {
|
|
258
|
+
ok: false,
|
|
259
|
+
identity,
|
|
260
|
+
config,
|
|
261
|
+
error: localSyncStatus.lastError,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function ingestLocal() {
|
|
267
|
+
if (!ingestInFlight) {
|
|
268
|
+
ingestInFlight = runIngestLocal().finally(() => {
|
|
269
|
+
ingestInFlight = null;
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
return ingestInFlight;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async function resolveStore(config) {
|
|
276
|
+
const { token } = await loadGitHubToken(resolvedDataDir, { env });
|
|
277
|
+
if (!config.repo || !token) {
|
|
278
|
+
return { store: null, token: "" };
|
|
279
|
+
}
|
|
280
|
+
const store = storeFactory({
|
|
281
|
+
repo: config.repo,
|
|
282
|
+
branch: config.branch,
|
|
283
|
+
prefix: config.prefix,
|
|
284
|
+
token,
|
|
285
|
+
apiBaseUrl,
|
|
286
|
+
fetchImpl,
|
|
287
|
+
pluginVersion,
|
|
288
|
+
});
|
|
289
|
+
return { store, token };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function runPushLocal({ force = false, skipIngest = false } = {}) {
|
|
293
|
+
const config = await loadConfig(resolvedDataDir, { defaults });
|
|
294
|
+
if (!config.pushEnabled) {
|
|
295
|
+
return { ok: true, skipped: true, reason: "push_disabled", writtenMonths: [] };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const { store, token } = await resolveStore(config);
|
|
299
|
+
if (!store) {
|
|
300
|
+
return { ok: true, skipped: true, reason: "not_configured", writtenMonths: [] };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const currentMs = now();
|
|
304
|
+
if (!force && lastDebouncedPushMs > 0 && currentMs - lastDebouncedPushMs < config.pushIntervalSec * 1000) {
|
|
305
|
+
return { ok: true, skipped: true, reason: "debounced", writtenMonths: [] };
|
|
306
|
+
}
|
|
307
|
+
lastDebouncedPushMs = currentMs;
|
|
308
|
+
|
|
309
|
+
let identity;
|
|
310
|
+
if (skipIngest) {
|
|
311
|
+
identity = await resolveDeviceIdentity({
|
|
312
|
+
dataDir: resolvedDataDir,
|
|
313
|
+
magpieConfigDir,
|
|
314
|
+
deviceNameOverride: config.deviceName,
|
|
315
|
+
hostname,
|
|
316
|
+
env,
|
|
317
|
+
homeDir,
|
|
318
|
+
});
|
|
319
|
+
} else {
|
|
320
|
+
const ingested = await ingestLocal();
|
|
321
|
+
if (!ingested.ok) {
|
|
322
|
+
return {
|
|
323
|
+
ok: false,
|
|
324
|
+
skipped: false,
|
|
325
|
+
reason: "local_ingest_failed",
|
|
326
|
+
error: ingested.error,
|
|
327
|
+
writtenMonths: [],
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
identity = ingested.identity;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
let verified;
|
|
334
|
+
try {
|
|
335
|
+
verified = await store.verifyPrivateRepo({ requirePush: true });
|
|
336
|
+
} catch (error) {
|
|
337
|
+
const safeMessage = sanitizeErrorForUi(error, token);
|
|
338
|
+
await updateState((prev) => ({
|
|
339
|
+
...prev,
|
|
340
|
+
lastPushAttemptAt: new Date(now()).toISOString(),
|
|
341
|
+
lastPushError: safeMessage,
|
|
342
|
+
}));
|
|
343
|
+
return {
|
|
344
|
+
ok: false,
|
|
345
|
+
skipped: false,
|
|
346
|
+
pushed: false,
|
|
347
|
+
code: error?.code || "PUSH_FAILED",
|
|
348
|
+
error: safeMessage,
|
|
349
|
+
writtenMonths: [],
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const targetKey = buildTargetKey(verified);
|
|
354
|
+
const scopeKey = buildConfigScopeKey(config);
|
|
355
|
+
const state = await readStateStrict(paths.stateFile);
|
|
356
|
+
const pushedRecord = state.pushedTargets?.[targetKey] || null;
|
|
357
|
+
|
|
358
|
+
const previousHashes = pushedRecord?.deviceId === identity.deviceId && pushedRecord.months
|
|
359
|
+
? pushedRecord.months
|
|
360
|
+
: {};
|
|
361
|
+
const previousRevision = pushedRecord?.deviceId === identity.deviceId && Number.isInteger(pushedRecord.revision)
|
|
362
|
+
? pushedRecord.revision
|
|
363
|
+
: 0;
|
|
364
|
+
const nextRevision = previousRevision + 1;
|
|
365
|
+
|
|
366
|
+
const { snapshots, monthHashes, manifest } = await buildLocalSnapshots({
|
|
367
|
+
config,
|
|
368
|
+
identity,
|
|
369
|
+
revision: nextRevision,
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
const changedMonths = snapshots
|
|
373
|
+
.filter((snap) => previousHashes[snap.month] !== monthHashes[snap.month])
|
|
374
|
+
.map((snap) => ({ month: snap.month, snapshot: snap }));
|
|
375
|
+
|
|
376
|
+
const removedMonths = Object.keys(previousHashes).filter((m) => !Object.prototype.hasOwnProperty.call(monthHashes, m));
|
|
377
|
+
const displayNameChanged = pushedRecord ? pushedRecord.displayName !== identity.displayName : false;
|
|
378
|
+
const firstPublish = !pushedRecord || previousRevision === 0;
|
|
379
|
+
|
|
380
|
+
if (!firstPublish && changedMonths.length === 0 && removedMonths.length === 0 && !displayNameChanged) {
|
|
381
|
+
return {
|
|
382
|
+
ok: true,
|
|
383
|
+
skipped: false,
|
|
384
|
+
pushed: false,
|
|
385
|
+
reason: "up_to_date",
|
|
386
|
+
writtenMonths: [],
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
try {
|
|
391
|
+
const published = await store.publishDevice({
|
|
392
|
+
deviceId: identity.deviceId,
|
|
393
|
+
manifest,
|
|
394
|
+
changedMonths,
|
|
395
|
+
removedMonths,
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
await updateState((prev) => ({
|
|
399
|
+
...prev,
|
|
400
|
+
scopeTargetMap: {
|
|
401
|
+
...(prev.scopeTargetMap || {}),
|
|
402
|
+
[scopeKey]: targetKey,
|
|
403
|
+
},
|
|
404
|
+
pushedTargets: {
|
|
405
|
+
...(prev.pushedTargets || {}),
|
|
406
|
+
[targetKey]: {
|
|
407
|
+
repo: verified.repo,
|
|
408
|
+
repoId: verified.repoId,
|
|
409
|
+
branch: verified.branch,
|
|
410
|
+
prefix: verified.prefix,
|
|
411
|
+
deviceId: identity.deviceId,
|
|
412
|
+
displayName: identity.displayName,
|
|
413
|
+
revision: nextRevision,
|
|
414
|
+
months: monthHashes,
|
|
415
|
+
lastCommitSha: published.commitSha,
|
|
416
|
+
},
|
|
417
|
+
},
|
|
418
|
+
lastPushAt: new Date(now()).toISOString(),
|
|
419
|
+
lastPushError: null,
|
|
420
|
+
}));
|
|
421
|
+
|
|
422
|
+
return {
|
|
423
|
+
ok: true,
|
|
424
|
+
skipped: false,
|
|
425
|
+
pushed: true,
|
|
426
|
+
revision: nextRevision,
|
|
427
|
+
writtenMonths: published.publishedMonths,
|
|
428
|
+
};
|
|
429
|
+
} catch (error) {
|
|
430
|
+
const safeMessage = sanitizeErrorForUi(error, token);
|
|
431
|
+
await updateState((prev) => ({
|
|
432
|
+
...prev,
|
|
433
|
+
lastPushAttemptAt: new Date(now()).toISOString(),
|
|
434
|
+
lastPushError: safeMessage,
|
|
435
|
+
}));
|
|
436
|
+
return {
|
|
437
|
+
ok: false,
|
|
438
|
+
skipped: false,
|
|
439
|
+
pushed: false,
|
|
440
|
+
code: error?.code || "PUSH_FAILED",
|
|
441
|
+
error: safeMessage,
|
|
442
|
+
writtenMonths: [],
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async function pullSingleRemoteDevice({ store, verifiedTarget, targetCacheDir, deviceId, previousMeta, token }) {
|
|
448
|
+
if (!DEVICE_ID_PATTERN.test(deviceId)) {
|
|
449
|
+
return {
|
|
450
|
+
deviceId,
|
|
451
|
+
ok: false,
|
|
452
|
+
error: "Invalid remote device ID.",
|
|
453
|
+
meta: { ...previousMeta, status: "error", lastError: "Invalid remote device ID." },
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
const deviceCacheDir = assertContainedPath(targetCacheDir, path.join(targetCacheDir, deviceId));
|
|
458
|
+
const committed = await readCommittedDeviceGeneration(deviceCacheDir);
|
|
459
|
+
const hasValidCommittedCache = committed.status === "ok";
|
|
460
|
+
const attemptIso = new Date(now()).toISOString();
|
|
461
|
+
|
|
462
|
+
let stagingDir = null;
|
|
463
|
+
try {
|
|
464
|
+
// Only send ETag when our committed local generation is completely intact.
|
|
465
|
+
const manifestRes = await store.fetchDeviceManifest(deviceId, {
|
|
466
|
+
etag: hasValidCommittedCache ? previousMeta?.etag || null : null,
|
|
467
|
+
verified: verifiedTarget,
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
if (manifestRes.status === "not_modified" && hasValidCommittedCache) {
|
|
471
|
+
return {
|
|
472
|
+
deviceId,
|
|
473
|
+
ok: true,
|
|
474
|
+
notModified: true,
|
|
475
|
+
meta: {
|
|
476
|
+
...previousMeta,
|
|
477
|
+
displayName: committed.manifest.displayName || previousMeta?.displayName || deviceId,
|
|
478
|
+
status: "ok",
|
|
479
|
+
lastSyncedAt: attemptIso,
|
|
480
|
+
lastAttemptAt: attemptIso,
|
|
481
|
+
lastError: null,
|
|
482
|
+
},
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
if (manifestRes.status === "missing") {
|
|
487
|
+
return {
|
|
488
|
+
deviceId,
|
|
489
|
+
ok: true,
|
|
490
|
+
missing: true,
|
|
491
|
+
meta: {
|
|
492
|
+
...previousMeta,
|
|
493
|
+
status: hasValidCommittedCache ? "stale" : "empty",
|
|
494
|
+
lastAttemptAt: attemptIso,
|
|
495
|
+
lastError: hasValidCommittedCache ? "Remote manifest not found; preserving cached snapshot." : null,
|
|
496
|
+
},
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const manifest = manifestRes.manifest;
|
|
501
|
+
const genId = `g_${Date.now()}_${crypto.randomBytes(4).toString("hex")}`;
|
|
502
|
+
const generationsDir = assertContainedPath(deviceCacheDir, path.join(deviceCacheDir, "generations"));
|
|
503
|
+
stagingDir = assertContainedPath(generationsDir, path.join(generationsDir, genId));
|
|
504
|
+
await ensureDir(stagingDir, 0o700);
|
|
505
|
+
|
|
506
|
+
const downloadedMonths = [];
|
|
507
|
+
const nextMonthHashes = {};
|
|
508
|
+
|
|
509
|
+
for (const monthKey of Object.keys(manifest.months || {}).sort()) {
|
|
510
|
+
const expectedHash = manifest.months[monthKey].sha256;
|
|
511
|
+
let snapshot = null;
|
|
512
|
+
|
|
513
|
+
if (hasValidCommittedCache && committed.snapshotsByMonth.has(monthKey)) {
|
|
514
|
+
const prevSnap = committed.snapshotsByMonth.get(monthKey);
|
|
515
|
+
if (computeMonthContentHash(prevSnap) === expectedHash) {
|
|
516
|
+
snapshot = prevSnap;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
if (!snapshot) {
|
|
521
|
+
const fetched = await store.fetchDeviceMonth(deviceId, monthKey, {
|
|
522
|
+
expectedSha256: expectedHash,
|
|
523
|
+
verified: verifiedTarget,
|
|
524
|
+
});
|
|
525
|
+
if (fetched.status !== "ok") {
|
|
526
|
+
throw new Error(`Unexpected response fetching ${deviceId}/${monthKey}.json.`);
|
|
527
|
+
}
|
|
528
|
+
snapshot = fetched.snapshot;
|
|
529
|
+
downloadedMonths.push(monthKey);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const monthFile = assertContainedPath(stagingDir, path.join(stagingDir, `${monthKey}.json`));
|
|
533
|
+
await writeJsonAtomic(monthFile, snapshot, { mode: 0o600 });
|
|
534
|
+
nextMonthHashes[monthKey] = expectedHash;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
await writeJsonAtomic(path.join(stagingDir, "manifest.json"), manifest, { mode: 0o600 });
|
|
538
|
+
|
|
539
|
+
// Atomically flip current.json only after every required month is staged and verified.
|
|
540
|
+
await writeJsonAtomic(
|
|
541
|
+
path.join(deviceCacheDir, "current.json"),
|
|
542
|
+
{ generation: genId, updatedAt: attemptIso },
|
|
543
|
+
{ mode: 0o600 },
|
|
544
|
+
);
|
|
545
|
+
|
|
546
|
+
// Best-effort pruning of previous generations after the new pointer is committed.
|
|
547
|
+
try {
|
|
548
|
+
const entries = await fs.readdir(generationsDir);
|
|
549
|
+
for (const oldGen of entries) {
|
|
550
|
+
if (oldGen !== genId) {
|
|
551
|
+
await fs.rm(assertContainedPath(generationsDir, path.join(generationsDir, oldGen)), {
|
|
552
|
+
recursive: true,
|
|
553
|
+
force: true,
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
} catch {
|
|
558
|
+
// Non-fatal cleanup error.
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
return {
|
|
562
|
+
deviceId,
|
|
563
|
+
ok: true,
|
|
564
|
+
downloadedMonths,
|
|
565
|
+
meta: {
|
|
566
|
+
displayName: manifest.displayName || deviceId,
|
|
567
|
+
etag: manifestRes.etag,
|
|
568
|
+
revision: manifest.revision,
|
|
569
|
+
monthHashes: nextMonthHashes,
|
|
570
|
+
status: "ok",
|
|
571
|
+
lastSyncedAt: attemptIso,
|
|
572
|
+
lastAttemptAt: attemptIso,
|
|
573
|
+
lastError: null,
|
|
574
|
+
},
|
|
575
|
+
};
|
|
576
|
+
} catch (error) {
|
|
577
|
+
if (stagingDir) {
|
|
578
|
+
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
|
|
579
|
+
}
|
|
580
|
+
const safeMessage = sanitizeErrorForUi(error, token);
|
|
581
|
+
return {
|
|
582
|
+
deviceId,
|
|
583
|
+
ok: false,
|
|
584
|
+
error: safeMessage,
|
|
585
|
+
code: error?.code || "REMOTE_PULL_FAILED",
|
|
586
|
+
meta: {
|
|
587
|
+
...previousMeta,
|
|
588
|
+
status: hasValidCommittedCache ? "stale" : "error",
|
|
589
|
+
lastAttemptAt: attemptIso,
|
|
590
|
+
lastError: safeMessage,
|
|
591
|
+
},
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
async function runPullRemote() {
|
|
597
|
+
const config = await loadConfig(resolvedDataDir, { defaults });
|
|
598
|
+
const identity = await resolveDeviceIdentity({
|
|
599
|
+
dataDir: resolvedDataDir,
|
|
600
|
+
magpieConfigDir,
|
|
601
|
+
deviceNameOverride: config.deviceName,
|
|
602
|
+
hostname,
|
|
603
|
+
env,
|
|
604
|
+
homeDir,
|
|
605
|
+
});
|
|
606
|
+
const { store, token } = await resolveStore(config);
|
|
607
|
+
if (!store) {
|
|
608
|
+
return { ok: true, skipped: true, reason: "not_configured", devices: {} };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const scopeKey = buildConfigScopeKey(config);
|
|
612
|
+
const state = await readStateStrict(paths.stateFile);
|
|
613
|
+
|
|
614
|
+
let verifiedTarget;
|
|
615
|
+
let deviceIds;
|
|
616
|
+
try {
|
|
617
|
+
const listed = await store.listDeviceIds();
|
|
618
|
+
verifiedTarget = listed.target;
|
|
619
|
+
deviceIds = listed.deviceIds.filter((id) => id !== identity.deviceId);
|
|
620
|
+
} catch (error) {
|
|
621
|
+
const safeMessage = sanitizeErrorForUi(error, token);
|
|
622
|
+
const attemptIso = new Date(now()).toISOString();
|
|
623
|
+
const knownTargetKey = state.scopeTargetMap?.[scopeKey] || null;
|
|
624
|
+
const previousRemote = knownTargetKey ? (state.remoteTargets?.[knownTargetKey]?.devices || {}) : {};
|
|
625
|
+
const updated = {};
|
|
626
|
+
for (const [id, meta] of Object.entries(previousRemote)) {
|
|
627
|
+
updated[id] = {
|
|
628
|
+
...meta,
|
|
629
|
+
status: meta?.lastSyncedAt ? "stale" : "error",
|
|
630
|
+
lastAttemptAt: attemptIso,
|
|
631
|
+
lastError: safeMessage,
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
await updateState((prev) => ({
|
|
635
|
+
...prev,
|
|
636
|
+
...(knownTargetKey
|
|
637
|
+
? {
|
|
638
|
+
remoteTargets: {
|
|
639
|
+
...(prev.remoteTargets || {}),
|
|
640
|
+
[knownTargetKey]: {
|
|
641
|
+
...(prev.remoteTargets?.[knownTargetKey] || {}),
|
|
642
|
+
devices: updated,
|
|
643
|
+
},
|
|
644
|
+
},
|
|
645
|
+
}
|
|
646
|
+
: {}),
|
|
647
|
+
lastPullAttemptAt: attemptIso,
|
|
648
|
+
lastPullError: safeMessage,
|
|
649
|
+
}));
|
|
650
|
+
return {
|
|
651
|
+
ok: false,
|
|
652
|
+
skipped: false,
|
|
653
|
+
code: error?.code || "REMOTE_LIST_FAILED",
|
|
654
|
+
error: safeMessage,
|
|
655
|
+
devices: updated,
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
const targetKey = buildTargetKey(verifiedTarget);
|
|
660
|
+
const targetCacheDir = assertContainedPath(paths.remoteCacheDir, path.join(paths.remoteCacheDir, targetKey));
|
|
661
|
+
const previousRemote = state.remoteTargets?.[targetKey]?.devices || {};
|
|
662
|
+
|
|
663
|
+
const settled = await runWithConcurrency(deviceIds, REMOTE_PULL_CONCURRENCY, (deviceId) =>
|
|
664
|
+
pullSingleRemoteDevice({
|
|
665
|
+
store,
|
|
666
|
+
verifiedTarget,
|
|
667
|
+
targetCacheDir,
|
|
668
|
+
deviceId,
|
|
669
|
+
previousMeta: previousRemote[deviceId] || {},
|
|
670
|
+
token,
|
|
671
|
+
}),
|
|
672
|
+
);
|
|
673
|
+
|
|
674
|
+
const nextRemoteDevices = { ...previousRemote };
|
|
675
|
+
const perDeviceOutcome = {};
|
|
676
|
+
let hadFailure = false;
|
|
677
|
+
|
|
678
|
+
for (const entry of settled) {
|
|
679
|
+
if (entry.status === "fulfilled") {
|
|
680
|
+
const result = entry.value;
|
|
681
|
+
nextRemoteDevices[result.deviceId] = result.meta;
|
|
682
|
+
perDeviceOutcome[result.deviceId] = {
|
|
683
|
+
ok: result.ok,
|
|
684
|
+
status: result.meta.status,
|
|
685
|
+
error: result.error || null,
|
|
686
|
+
downloadedMonths: result.downloadedMonths || [],
|
|
687
|
+
notModified: Boolean(result.notModified),
|
|
688
|
+
};
|
|
689
|
+
if (!result.ok) {
|
|
690
|
+
hadFailure = true;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const attemptIso = new Date(now()).toISOString();
|
|
696
|
+
await updateState((prev) => ({
|
|
697
|
+
...prev,
|
|
698
|
+
scopeTargetMap: {
|
|
699
|
+
...(prev.scopeTargetMap || {}),
|
|
700
|
+
[scopeKey]: targetKey,
|
|
701
|
+
},
|
|
702
|
+
remoteTargets: {
|
|
703
|
+
...(prev.remoteTargets || {}),
|
|
704
|
+
[targetKey]: {
|
|
705
|
+
repo: verifiedTarget.repo,
|
|
706
|
+
repoId: verifiedTarget.repoId,
|
|
707
|
+
branch: verifiedTarget.branch,
|
|
708
|
+
prefix: verifiedTarget.prefix,
|
|
709
|
+
devices: nextRemoteDevices,
|
|
710
|
+
},
|
|
711
|
+
},
|
|
712
|
+
lastPullAt: attemptIso,
|
|
713
|
+
lastPullError: hadFailure ? "One or more remote devices failed to refresh." : null,
|
|
714
|
+
}));
|
|
715
|
+
|
|
716
|
+
return {
|
|
717
|
+
ok: !hadFailure,
|
|
718
|
+
skipped: false,
|
|
719
|
+
devices: perDeviceOutcome,
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async function loadCachedRemoteDevices(selfDeviceId, config, state) {
|
|
724
|
+
if (!config.repo) {
|
|
725
|
+
return [];
|
|
726
|
+
}
|
|
727
|
+
const scopeKey = buildConfigScopeKey(config);
|
|
728
|
+
const targetKey = state.scopeTargetMap?.[scopeKey] || null;
|
|
729
|
+
if (!targetKey) {
|
|
730
|
+
return [];
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const targetCacheDir = assertContainedPath(paths.remoteCacheDir, path.join(paths.remoteCacheDir, targetKey));
|
|
734
|
+
const remoteMetaMap = state.remoteTargets?.[targetKey]?.devices || {};
|
|
735
|
+
|
|
736
|
+
let dirNames = [];
|
|
737
|
+
try {
|
|
738
|
+
dirNames = await fs.readdir(targetCacheDir);
|
|
739
|
+
} catch (error) {
|
|
740
|
+
if (!error || error.code !== "ENOENT") {
|
|
741
|
+
throw error;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
const candidateIds = new Set([
|
|
746
|
+
...Object.keys(remoteMetaMap).filter((id) => DEVICE_ID_PATTERN.test(id)),
|
|
747
|
+
...dirNames.filter((name) => DEVICE_ID_PATTERN.test(name)),
|
|
748
|
+
]);
|
|
749
|
+
candidateIds.delete(selfDeviceId);
|
|
750
|
+
|
|
751
|
+
const remoteDevices = [];
|
|
752
|
+
for (const deviceId of Array.from(candidateIds).sort()) {
|
|
753
|
+
const meta = remoteMetaMap[deviceId] || {};
|
|
754
|
+
const deviceDir = assertContainedPath(targetCacheDir, path.join(targetCacheDir, deviceId));
|
|
755
|
+
const committed = await readCommittedDeviceGeneration(deviceDir);
|
|
756
|
+
|
|
757
|
+
if (committed.status !== "ok") {
|
|
758
|
+
remoteDevices.push({
|
|
759
|
+
deviceId,
|
|
760
|
+
displayName: typeof meta.displayName === "string" && meta.displayName ? meta.displayName : deviceId,
|
|
761
|
+
isLocal: false,
|
|
762
|
+
status: meta.status || (committed.status === "corrupt" ? "error" : "empty"),
|
|
763
|
+
lastSyncedAt: meta.lastSyncedAt || null,
|
|
764
|
+
lastError: meta.lastError || (committed.status === "corrupt" ? committed.error : null),
|
|
765
|
+
months: [],
|
|
766
|
+
});
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const manifest = committed.manifest;
|
|
771
|
+
remoteDevices.push({
|
|
772
|
+
deviceId,
|
|
773
|
+
displayName: typeof manifest.displayName === "string" && manifest.displayName
|
|
774
|
+
? manifest.displayName
|
|
775
|
+
: (typeof meta.displayName === "string" && meta.displayName ? meta.displayName : deviceId),
|
|
776
|
+
isLocal: false,
|
|
777
|
+
status: meta.status || (committed.snapshots.length > 0 ? "ok" : "empty"),
|
|
778
|
+
lastSyncedAt: meta.lastSyncedAt || manifest.updatedAt || null,
|
|
779
|
+
lastError: meta.lastError || null,
|
|
780
|
+
months: committed.snapshots,
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
return remoteDevices;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
return {
|
|
788
|
+
dataDir: resolvedDataDir,
|
|
789
|
+
|
|
790
|
+
ingestLocal,
|
|
791
|
+
|
|
792
|
+
pushLocal(options = {}) {
|
|
793
|
+
if (!pushInFlight) {
|
|
794
|
+
pushInFlight = runPushLocal(options).finally(() => {
|
|
795
|
+
pushInFlight = null;
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
return pushInFlight;
|
|
799
|
+
},
|
|
800
|
+
|
|
801
|
+
pullRemote() {
|
|
802
|
+
if (!pullInFlight) {
|
|
803
|
+
pullInFlight = runPullRemote().finally(() => {
|
|
804
|
+
pullInFlight = null;
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
return pullInFlight;
|
|
808
|
+
},
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Trigger a debounced background push without throwing or blocking callers.
|
|
812
|
+
*/
|
|
813
|
+
scheduleDebouncedPush() {
|
|
814
|
+
if (pushInFlight) {
|
|
815
|
+
return null;
|
|
816
|
+
}
|
|
817
|
+
return this.pushLocal({ force: false }).catch(() => ({
|
|
818
|
+
ok: false,
|
|
819
|
+
skipped: false,
|
|
820
|
+
reason: "unexpected_error",
|
|
821
|
+
}));
|
|
822
|
+
},
|
|
823
|
+
|
|
824
|
+
async testConnection({ repo, branch, prefix, token } = {}) {
|
|
825
|
+
const config = await loadConfig(resolvedDataDir, { defaults });
|
|
826
|
+
const storedToken = await loadGitHubToken(resolvedDataDir, { env });
|
|
827
|
+
const effectiveToken = typeof token === "string" && token.trim() ? token.trim() : storedToken.token;
|
|
828
|
+
const effectiveRepo = repo !== undefined ? repo : config.repo;
|
|
829
|
+
const effectiveBranch = branch !== undefined ? branch : config.branch;
|
|
830
|
+
const effectivePrefix = prefix !== undefined ? prefix : config.prefix;
|
|
831
|
+
|
|
832
|
+
try {
|
|
833
|
+
const store = storeFactory({
|
|
834
|
+
repo: effectiveRepo,
|
|
835
|
+
branch: effectiveBranch,
|
|
836
|
+
prefix: effectivePrefix,
|
|
837
|
+
token: effectiveToken,
|
|
838
|
+
apiBaseUrl,
|
|
839
|
+
fetchImpl,
|
|
840
|
+
pluginVersion,
|
|
841
|
+
});
|
|
842
|
+
return await store.testConnection();
|
|
843
|
+
} catch (error) {
|
|
844
|
+
return {
|
|
845
|
+
ok: false,
|
|
846
|
+
code: error?.code || "CONNECTION_FAILED",
|
|
847
|
+
error: sanitizeErrorForUi(error, effectiveToken),
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
},
|
|
851
|
+
|
|
852
|
+
async getSummary({ range = "7d", deviceFilter = "all", todayDay } = {}) {
|
|
853
|
+
const config = await loadConfig(resolvedDataDir, { defaults });
|
|
854
|
+
const identity = await resolveDeviceIdentity({
|
|
855
|
+
dataDir: resolvedDataDir,
|
|
856
|
+
magpieConfigDir,
|
|
857
|
+
deviceNameOverride: config.deviceName,
|
|
858
|
+
hostname,
|
|
859
|
+
env,
|
|
860
|
+
homeDir,
|
|
861
|
+
});
|
|
862
|
+
const state = await readStateStrict(paths.stateFile);
|
|
863
|
+
const scopeKey = buildConfigScopeKey(config);
|
|
864
|
+
const activeTargetKey = state.scopeTargetMap?.[scopeKey] || null;
|
|
865
|
+
const pushRev = activeTargetKey && Number.isInteger(state.pushedTargets?.[activeTargetKey]?.revision)
|
|
866
|
+
? state.pushedTargets[activeTargetKey].revision
|
|
867
|
+
: 0;
|
|
868
|
+
|
|
869
|
+
const localBuilt = await buildLocalSnapshots({
|
|
870
|
+
config,
|
|
871
|
+
identity,
|
|
872
|
+
revision: pushRev,
|
|
873
|
+
});
|
|
874
|
+
|
|
875
|
+
const localDevice = {
|
|
876
|
+
deviceId: identity.deviceId,
|
|
877
|
+
displayName: identity.displayName,
|
|
878
|
+
isLocal: true,
|
|
879
|
+
status: localSyncStatus.status === "ok"
|
|
880
|
+
? (localBuilt.snapshots.length > 0 ? "ok" : "empty")
|
|
881
|
+
: localSyncStatus.status,
|
|
882
|
+
lastSyncedAt: localSyncStatus.lastSyncedAt || state.lastLocalSyncAt || null,
|
|
883
|
+
lastError: localSyncStatus.lastError,
|
|
884
|
+
months: localBuilt.snapshots,
|
|
885
|
+
};
|
|
886
|
+
|
|
887
|
+
const remoteDevices = await loadCachedRemoteDevices(identity.deviceId, config, state);
|
|
888
|
+
|
|
889
|
+
const effectiveToday = todayDay || formatLocalDateParts(new Date(now()), timeZone).day;
|
|
890
|
+
const aggregated = aggregateDevices({
|
|
891
|
+
devices: [localDevice, ...remoteDevices],
|
|
892
|
+
range,
|
|
893
|
+
deviceFilter,
|
|
894
|
+
todayDay: effectiveToday,
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
return {
|
|
898
|
+
...aggregated,
|
|
899
|
+
sync: {
|
|
900
|
+
pushEnabled: config.pushEnabled,
|
|
901
|
+
repoConfigured: Boolean(config.repo),
|
|
902
|
+
lastLocalSyncAt: state.lastLocalSyncAt || null,
|
|
903
|
+
lastPushAt: state.lastPushAt || null,
|
|
904
|
+
lastPushError: state.lastPushError || null,
|
|
905
|
+
lastPullAt: state.lastPullAt || null,
|
|
906
|
+
lastPullError: state.lastPullError || null,
|
|
907
|
+
},
|
|
908
|
+
};
|
|
909
|
+
},
|
|
910
|
+
|
|
911
|
+
async refresh({ push = true, pull = true, forcePush = true, range = "7d", deviceFilter = "all", todayDay } = {}) {
|
|
912
|
+
const localResult = await ingestLocal();
|
|
913
|
+
const pushResult = push && localResult.ok
|
|
914
|
+
? await this.pushLocal({ force: forcePush, skipIngest: true })
|
|
915
|
+
: push && !localResult.ok
|
|
916
|
+
? { ok: false, skipped: false, reason: "local_ingest_failed", error: localResult.error, writtenMonths: [] }
|
|
917
|
+
: { ok: true, skipped: true };
|
|
918
|
+
const pullResult = pull ? await this.pullRemote() : { ok: true, skipped: true };
|
|
919
|
+
const summary = await this.getSummary({ range, deviceFilter, todayDay });
|
|
920
|
+
|
|
921
|
+
return {
|
|
922
|
+
local: {
|
|
923
|
+
ok: localResult.ok,
|
|
924
|
+
error: localResult.error || null,
|
|
925
|
+
},
|
|
926
|
+
push: pushResult,
|
|
927
|
+
pull: pullResult,
|
|
928
|
+
summary,
|
|
929
|
+
};
|
|
930
|
+
},
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* Return a process-wide shared SyncEngine keyed by resolved dataDir so
|
|
936
|
+
* index.mjs and hooks.mjs share single-flight and debounce state cleanly.
|
|
937
|
+
*/
|
|
938
|
+
export function getSharedSyncEngine(options = {}) {
|
|
939
|
+
const dataDir = options.dataDir
|
|
940
|
+
? path.resolve(options.dataDir)
|
|
941
|
+
: resolveDataDir({
|
|
942
|
+
optionDataDir: options.optionDataDir || "",
|
|
943
|
+
env: options.env || process.env,
|
|
944
|
+
homeDir: options.homeDir || os.homedir(),
|
|
945
|
+
});
|
|
946
|
+
|
|
947
|
+
if (!sharedEngines.has(dataDir)) {
|
|
948
|
+
sharedEngines.set(dataDir, createSyncEngine({ ...options, dataDir }));
|
|
949
|
+
}
|
|
950
|
+
return sharedEngines.get(dataDir);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* Reset process-wide cached engines (for test isolation).
|
|
955
|
+
*/
|
|
956
|
+
export function resetSharedSyncEngines() {
|
|
957
|
+
sharedEngines.clear();
|
|
958
|
+
}
|