@narumitw/pi-sync 0.63.1 → 0.65.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/CHANGELOG.md +21 -0
- package/README.md +86 -10
- package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
- package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
- package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
- package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
- package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
- package/dist/chunks/{chunk-V76KCWHO.ts → chunk-IOM6E5FW.ts} +4 -4
- package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-JQ5BAWW2.ts} +482 -78
- package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
- package/dist/chunks/{chunk-LBNC5AOM.ts → chunk-OBVJTKVY.ts} +12 -12
- package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-OWEOZZZE.ts} +6 -6
- package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-SZJOUVCL.ts} +3 -3
- package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
- package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-WJQ4TGN5.ts} +58 -31
- package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
- package/dist/chunks/{chunk-HLCML3OW.ts → chunk-XUZV4OGI.ts} +5 -3
- package/dist/chunks/chunk-XUZV4OGI.ts.map +7 -0
- package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-YZ4DXQ7N.ts} +81 -30
- package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
- package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-J7L7S4AR.ts} +2 -2
- package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
- package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-XB75YLEG.ts} +5 -5
- package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-RGA26Z6G.ts} +103 -83
- package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
- package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-AAC674C6.ts} +3 -2
- package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
- package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
- package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-WVMET5RI.ts} +4 -4
- package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-644T6KHG.ts} +4 -4
- package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-YP2KF2WQ.ts} +9 -9
- package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-NBBTSMKR.ts} +5 -5
- package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-AIEM2KL2.ts} +2 -2
- package/dist/daemon/dist/cli.js +2 -0
- package/dist/daemon/dist/client-transport.js +66 -0
- package/dist/daemon/dist/client.js +222 -354
- package/dist/daemon/dist/consent.js +33 -11
- package/dist/daemon/dist/daemon-debug.js +33 -0
- package/dist/daemon/dist/daemon-recovery.js +158 -0
- package/dist/daemon/dist/daemon-startup.js +257 -0
- package/dist/daemon/dist/engine/backends/git/git-backend.js +49 -13
- package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
- package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
- package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
- package/dist/daemon/dist/engine/backends/s3/s3-backend.js +30 -21
- package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
- package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +34 -32
- package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
- package/dist/daemon/dist/engine/debug-log.js +134 -0
- package/dist/daemon/dist/engine/paths.js +7 -1
- package/dist/daemon/dist/engine/settings/config-file.js +62 -17
- package/dist/daemon/dist/engine/settings/config.js +49 -14
- package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
- package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
- package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
- package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
- package/dist/daemon/dist/engine/state/lock.js +157 -17
- package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
- package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
- package/dist/daemon/dist/engine/sync/initialization.js +2 -2
- package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
- package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
- package/dist/daemon/dist/engine/sync/remote-snapshot.js +21 -4
- package/dist/daemon/dist/engine/sync/session-push.js +13 -4
- package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
- package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
- package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
- package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
- package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
- package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
- package/dist/daemon/dist/engine/sync/sync-local.js +59 -4
- package/dist/daemon/dist/engine/sync/sync-mutations.js +309 -337
- package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
- package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
- package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
- package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
- package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
- package/dist/daemon/dist/engine-service.js +122 -10
- package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
- package/dist/daemon/dist/identity.js +36 -6
- package/dist/daemon/dist/index.js +2 -1
- package/dist/daemon/dist/monitor.js +21 -1
- package/dist/daemon/dist/paged-review.js +177 -0
- package/dist/daemon/dist/participant-ledger.js +149 -0
- package/dist/daemon/dist/protocol.js +4 -0
- package/dist/daemon/dist/server.js +340 -127
- package/dist/daemon/dist/service-host.js +83 -15
- package/dist/daemon/dist/state-wait-jobs.js +23 -0
- package/dist/daemon/dist/state-wait.js +34 -0
- package/dist/daemon/package.json +1 -1
- package/dist/index.ts +128 -48
- package/dist/index.ts.map +2 -2
- package/docs/continuous-sync-verification.md +2 -0
- package/docs/daemon-migration.md +31 -6
- package/docs/tui-contract.md +7 -1
- package/package.json +2 -2
- package/skills/configure-pi-sync/references/configuration.md +23 -13
- package/src/commands/command-execution.ts +67 -5
- package/src/commands/command-handler.ts +12 -3
- package/src/commands/command.ts +4 -2
- package/src/daemon/client-debug.ts +45 -0
- package/src/daemon/directional-recovery.ts +103 -0
- package/src/daemon/ownership-recovery.ts +50 -0
- package/src/daemon/pi-client.ts +399 -71
- package/src/daemon/startup-bootstrap-client.ts +26 -0
- package/src/settings/config.ts +1 -0
- package/src/sync/automatic-sync.ts +61 -18
- package/src/sync/startup-check.ts +13 -5
- package/src/sync-extension.ts +46 -8
- package/src/ui/cancellable-operation.ts +5 -2
- package/src/ui/manager-state.ts +31 -23
- package/src/ui/manager-ui.ts +45 -25
- package/src/ui/merge-review.ts +53 -18
- package/src/ui/settings-ui.ts +2 -2
- package/src/ui/sync-confirmation.ts +14 -17
- package/src/ui/sync-setups-ui.ts +15 -12
- package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
- package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
- package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
- package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
- package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
- package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
- package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
- /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
- /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
- /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
- /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
- /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
- /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
- /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
- /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-AAC674C6.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
- /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
- /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
- /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
|
@@ -1,16 +1,23 @@
|
|
|
1
1
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { addAbortListener } from "node:events";
|
|
3
|
+
import { lstatSync } from "node:fs";
|
|
3
4
|
import fs from "node:fs/promises";
|
|
4
5
|
import { createServer } from "node:http";
|
|
5
|
-
import path from "node:path";
|
|
6
6
|
import lockfile from "proper-lockfile";
|
|
7
7
|
import { DAEMON_BUILD_VERSION } from "./build-version.js";
|
|
8
|
+
import { ConsentPublicationError, readConsent } from "./consent.js";
|
|
8
9
|
import { endpointOwner } from "./endpoint.js";
|
|
9
|
-
import {
|
|
10
|
+
import { debugOperation } from "./engine/debug-log.js";
|
|
11
|
+
import { SyncDecisionRequiredError } from "./engine/sync/sync-errors.js";
|
|
12
|
+
import { isForegroundDirection, isForegroundQueueOutcome } from "./foreground-queue-outcome.js";
|
|
13
|
+
import { canonicalRootGuard, daemonPaths, matchesPublishedIdentity, privateDirectory, processExists, publishIdentity, readIdentity, readJsonBody, readUpgradeOwner, runtimePaths, } from "./identity.js";
|
|
10
14
|
import { createIdleExit } from "./idle-exit.js";
|
|
11
15
|
import { withCleanup } from "./lifecycle.js";
|
|
16
|
+
import { createPagedReviewOffer, reviewScope } from "./paged-review.js";
|
|
12
17
|
import { ParticipantAdmission } from "./participant-admission.js";
|
|
13
|
-
import {
|
|
18
|
+
import { createParticipantLedger } from "./participant-ledger.js";
|
|
19
|
+
import { ClientContactExpiredError, DAEMON_JOB_CAPACITY, DaemonStoppingError, MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, OWNERSHIP_CLEANUP_REQUIRED, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, UNKNOWN_JOB_RESULT, validateFacts, validateHandoff, validId, } from "./protocol.js";
|
|
20
|
+
import { ParticipantStateWait } from "./state-wait.js";
|
|
14
21
|
export async function startServer(root, execute, hooks = {}) {
|
|
15
22
|
const base = await runtimePaths(root);
|
|
16
23
|
const identity = {
|
|
@@ -29,6 +36,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
29
36
|
throw new Error("A daemon owner is still alive; refusing replacement.");
|
|
30
37
|
let compromised = false;
|
|
31
38
|
let published = false;
|
|
39
|
+
let released = false;
|
|
32
40
|
const release = await lockfile.lock(paths.directory, {
|
|
33
41
|
realpath: false,
|
|
34
42
|
lockfilePath: paths.owner,
|
|
@@ -40,7 +48,28 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
40
48
|
void close().catch(() => { });
|
|
41
49
|
},
|
|
42
50
|
});
|
|
51
|
+
const diagnostic = hooks.diagnostic;
|
|
52
|
+
const ownsLog = () => {
|
|
53
|
+
if (!published || compromised || released)
|
|
54
|
+
return false;
|
|
55
|
+
assertRoot();
|
|
56
|
+
return (lstatSync(paths.owner, { throwIfNoEntry: false })?.isDirectory() === true &&
|
|
57
|
+
matchesPublishedIdentity(paths, identity));
|
|
58
|
+
};
|
|
59
|
+
const debug = diagnostic
|
|
60
|
+
? (event, current) => {
|
|
61
|
+
try {
|
|
62
|
+
diagnostic(event, () => ownsLog() && (current?.() ?? true));
|
|
63
|
+
}
|
|
64
|
+
catch { }
|
|
65
|
+
}
|
|
66
|
+
: undefined;
|
|
67
|
+
const failure = () => {
|
|
68
|
+
debug?.({ event: "lifecycle", outcome: "failed" });
|
|
69
|
+
hooks.failure?.();
|
|
70
|
+
};
|
|
43
71
|
const participants = new Map();
|
|
72
|
+
const waiters = new WeakMap();
|
|
44
73
|
const admission = new ParticipantAdmission();
|
|
45
74
|
const jobs = new Map();
|
|
46
75
|
const backgroundJobs = new Set();
|
|
@@ -49,22 +78,24 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
49
78
|
// Retain tombstones after result eviction; replay must never dispatch a second write.
|
|
50
79
|
const retired = new Set();
|
|
51
80
|
const pending = new Map();
|
|
52
|
-
const
|
|
81
|
+
const ledger = createParticipantLedger(paths, () => participants.values(), failure);
|
|
53
82
|
let sequence = 0;
|
|
54
83
|
let participantGeneration = 0;
|
|
55
84
|
let closed = false;
|
|
56
85
|
let stopRequested = false;
|
|
86
|
+
let foregroundRecoveryJob;
|
|
87
|
+
let consentPublicationFailed = false;
|
|
57
88
|
let automaticClosing = false;
|
|
58
|
-
let peerWriteFailed = false;
|
|
59
89
|
let idleExit;
|
|
60
90
|
let expiring;
|
|
61
91
|
const peerOperations = new Set();
|
|
62
92
|
let queue = Promise.resolve();
|
|
63
93
|
let closing;
|
|
64
|
-
let peerWrites = Promise.resolve();
|
|
65
94
|
let heartbeat;
|
|
66
95
|
function participantsChanged() {
|
|
67
96
|
participantGeneration++;
|
|
97
|
+
for (const peer of participants.values())
|
|
98
|
+
waiters.get(peer)?.changed();
|
|
68
99
|
for (const job of [...jobs.values(), ...backgroundJobs]) {
|
|
69
100
|
if (job.participantGeneration !== undefined &&
|
|
70
101
|
!job.committed &&
|
|
@@ -72,87 +103,26 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
72
103
|
job.controller.abort(new DOMException("Daemon participants changed before automatic work completed.", "AbortError"));
|
|
73
104
|
}
|
|
74
105
|
}
|
|
75
|
-
function savePeers(candidate) {
|
|
106
|
+
function savePeers(candidate, allowNoop = false) {
|
|
76
107
|
idleExit?.changed();
|
|
77
|
-
|
|
78
|
-
peerWrites = operation.catch(() => {
|
|
79
|
-
peerWriteFailed = true;
|
|
80
|
-
hooks.failure?.();
|
|
81
|
-
});
|
|
82
|
-
return operation;
|
|
83
|
-
}
|
|
84
|
-
async function writePeers(candidate) {
|
|
85
|
-
const temporary = path.join(paths.directory, `.${randomUUID()}.clients`);
|
|
86
|
-
const data = {
|
|
87
|
-
version: 1,
|
|
88
|
-
root: paths.root,
|
|
89
|
-
clients: [...participants.values()]
|
|
90
|
-
.filter((peer) => processExists(peer.facts.pid))
|
|
91
|
-
.map((peer) => ({ ...(candidate?.peer === peer ? candidate.facts : peer.facts), handoff: peer.handoff })),
|
|
92
|
-
};
|
|
93
|
-
const handle = await fs.open(temporary, "wx", 0o600);
|
|
94
|
-
try {
|
|
95
|
-
await handle.writeFile(JSON.stringify(data));
|
|
96
|
-
await handle.sync();
|
|
97
|
-
await handle.close();
|
|
98
|
-
await fs.rename(temporary, peersFile);
|
|
99
|
-
}
|
|
100
|
-
finally {
|
|
101
|
-
await handle.close().catch(() => { });
|
|
102
|
-
await fs.rm(temporary, { force: true });
|
|
103
|
-
}
|
|
108
|
+
return ledger.save(candidate, allowNoop);
|
|
104
109
|
}
|
|
105
110
|
try {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
data.version !== 1 ||
|
|
122
|
-
data.root !== paths.root ||
|
|
123
|
-
!Array.isArray(data.clients) ||
|
|
124
|
-
data.clients.length > 64)
|
|
125
|
-
throw new Error("Invalid daemon client record; evidence retained.");
|
|
126
|
-
for (const stored of data.clients) {
|
|
127
|
-
if (!record(stored))
|
|
128
|
-
throw new Error("Invalid stored participant.");
|
|
129
|
-
const { handoff, ...value } = stored;
|
|
130
|
-
validateFacts(value);
|
|
131
|
-
if (handoff !== undefined)
|
|
132
|
-
validateHandoff(handoff);
|
|
133
|
-
if (processExists(value.pid)) {
|
|
134
|
-
if (handoff?.kind === "exit")
|
|
135
|
-
closedClients.add(value.id);
|
|
136
|
-
participants.set(value.id, {
|
|
137
|
-
facts: value,
|
|
138
|
-
handoff,
|
|
139
|
-
callbacks: new Map(),
|
|
140
|
-
events: [],
|
|
141
|
-
connected: false,
|
|
142
|
-
closing: false,
|
|
143
|
-
suspected: handoff?.kind !== "exit",
|
|
144
|
-
seen: 0,
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
finally {
|
|
150
|
-
await handle.close();
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
catch (error) {
|
|
154
|
-
if (error.code !== "ENOENT")
|
|
155
|
-
throw error;
|
|
111
|
+
for (const { facts, handoff } of await ledger.restore()) {
|
|
112
|
+
if (!processExists(facts.pid))
|
|
113
|
+
continue;
|
|
114
|
+
if (handoff?.kind === "exit")
|
|
115
|
+
closedClients.add(facts.id);
|
|
116
|
+
participants.set(facts.id, {
|
|
117
|
+
facts,
|
|
118
|
+
handoff,
|
|
119
|
+
callbacks: new Map(),
|
|
120
|
+
events: [],
|
|
121
|
+
connected: false,
|
|
122
|
+
closing: false,
|
|
123
|
+
suspected: handoff?.kind !== "exit",
|
|
124
|
+
seen: 0,
|
|
125
|
+
});
|
|
156
126
|
}
|
|
157
127
|
}
|
|
158
128
|
catch (error) {
|
|
@@ -173,6 +143,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
173
143
|
peer.events.push(event);
|
|
174
144
|
while (peer.events.length > 128 || Buffer.byteLength(JSON.stringify(peer.events)) > MAX_MESSAGE_BYTES / 8)
|
|
175
145
|
peer.events.shift();
|
|
146
|
+
waiters.get(peer)?.changed();
|
|
176
147
|
}
|
|
177
148
|
};
|
|
178
149
|
const assertOwner = () => {
|
|
@@ -247,20 +218,28 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
247
218
|
const peer = requireParticipant(target, cleanup);
|
|
248
219
|
const callback = { id: randomUUID(), job: job.view.id, kind, payload: data };
|
|
249
220
|
let review;
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
typeof data.content === "string" &&
|
|
253
|
-
Buffer.byteLength(data.content) > REVIEW_PAGE_CHARS) {
|
|
221
|
+
let pagedReview;
|
|
222
|
+
if (kind === "merge-review" && record(data) && typeof data.content === "string") {
|
|
254
223
|
const bytes = Buffer.byteLength(data.content);
|
|
255
224
|
if (bytes > MAX_REVIEW_BYTES)
|
|
256
225
|
throw new Error("Exact review exceeds its byte limit; no truncated review was approved.");
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
226
|
+
if (bytes > REVIEW_PAGE_CHARS) {
|
|
227
|
+
if (peer.reviewDetails)
|
|
228
|
+
pagedReview = createPagedReviewOffer(reviewScope(identity, peer.facts, callback), data, data.content, bytes);
|
|
229
|
+
if (pagedReview) {
|
|
230
|
+
callback.payload = pagedReview.summary;
|
|
231
|
+
callback.review = pagedReview.reference;
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
review = data.content;
|
|
235
|
+
callback.payload = { ...data, content: undefined };
|
|
236
|
+
callback.review = {
|
|
237
|
+
pages: Math.ceil(review.length / REVIEW_PAGE_CHARS),
|
|
238
|
+
bytes,
|
|
239
|
+
sha256: createHash("sha256").update(review).digest("hex"),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
}
|
|
264
243
|
}
|
|
265
244
|
if (peer.callbacks.size >= 64 ||
|
|
266
245
|
Buffer.byteLength(JSON.stringify([...peer.callbacks.values(), callback])) > MAX_MESSAGE_BYTES / 8)
|
|
@@ -292,20 +271,33 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
292
271
|
if (cleanup && reservation && error === undefined && value === true)
|
|
293
272
|
peer.reservations?.delete(reservation);
|
|
294
273
|
sequence++;
|
|
274
|
+
waiters.get(peer)?.changed();
|
|
295
275
|
if (error)
|
|
296
276
|
reject(error);
|
|
297
277
|
else
|
|
298
278
|
resolve(value);
|
|
299
279
|
};
|
|
280
|
+
let startupReviewLock;
|
|
281
|
+
if (!job.committed && ["confirm", "select", "merge-review"].includes(kind)) {
|
|
282
|
+
try {
|
|
283
|
+
startupReviewLock = hooks.startup?.captureReviewLock();
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
startupReviewLock = undefined;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
300
289
|
pending.set(callback.id, {
|
|
301
290
|
callback,
|
|
291
|
+
startupReviewLock,
|
|
302
292
|
review,
|
|
293
|
+
pagedReview,
|
|
303
294
|
target,
|
|
304
295
|
resolve: (value) => finish(value),
|
|
305
296
|
reject: (error) => finish(undefined, error),
|
|
306
297
|
});
|
|
307
298
|
peer.callbacks.set(callback.id, callback);
|
|
308
299
|
sequence++;
|
|
300
|
+
waiters.get(peer)?.changed();
|
|
309
301
|
effectiveSignal?.addEventListener("abort", abort, { once: true });
|
|
310
302
|
if (kind.startsWith("queue-")) {
|
|
311
303
|
timer = setTimeout(() => finish(undefined, new Error("Client file-queue acknowledgement timed out; work was stopped.")), 30_000);
|
|
@@ -329,12 +321,22 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
329
321
|
validate,
|
|
330
322
|
request,
|
|
331
323
|
emit: (kind, data, target = job.client) => emit(kind, data, target),
|
|
324
|
+
debug,
|
|
325
|
+
noteDebugOutcome(outcome) {
|
|
326
|
+
job.debugOutcome = outcome;
|
|
327
|
+
},
|
|
332
328
|
committed: () => {
|
|
333
329
|
job.committed = true;
|
|
334
330
|
emit("commit", { job: job.view.id }, job.client);
|
|
335
331
|
},
|
|
336
332
|
};
|
|
337
333
|
}
|
|
334
|
+
function assertForegroundQueueReady() {
|
|
335
|
+
if (foregroundRecoveryJob)
|
|
336
|
+
throw Object.assign(new Error("File-queue cleanup is pending; no new daemon work can start."), {
|
|
337
|
+
code: OWNERSHIP_CLEANUP_REQUIRED,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
338
340
|
function enqueue(id, client, operation, payload) {
|
|
339
341
|
const peer = requireParticipant(client);
|
|
340
342
|
if (!id.startsWith(operationPrefix(identity)))
|
|
@@ -346,18 +348,22 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
346
348
|
throw new Error("Operation ID was reused with different input.");
|
|
347
349
|
return duplicate;
|
|
348
350
|
}
|
|
351
|
+
assertForegroundQueueReady();
|
|
349
352
|
if (retired.has(id))
|
|
350
353
|
throw new Error("Operation result expired; reconcile the existing journal before starting new work.");
|
|
351
354
|
if (retired.size + jobs.size >= 4096)
|
|
352
355
|
throw new Error("Daemon operation ledger is full; drain and restart explicitly.");
|
|
353
|
-
if (jobs.size >=
|
|
356
|
+
if (jobs.size >= DAEMON_JOB_CAPACITY) {
|
|
354
357
|
for (const [key, job] of jobs)
|
|
355
358
|
if (job.view.phase === "done" || job.view.phase === "failed") {
|
|
356
359
|
retired.add(key);
|
|
357
360
|
jobs.delete(key);
|
|
361
|
+
const owner = job.client ? participants.get(job.client) : undefined;
|
|
362
|
+
if (owner)
|
|
363
|
+
waiters.get(owner)?.changed();
|
|
358
364
|
break;
|
|
359
365
|
}
|
|
360
|
-
if (jobs.size >=
|
|
366
|
+
if (jobs.size >= DAEMON_JOB_CAPACITY)
|
|
361
367
|
throw new Error("Daemon job capacity reached.");
|
|
362
368
|
}
|
|
363
369
|
const job = {
|
|
@@ -381,19 +387,42 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
381
387
|
if (cancelled.has(`${client}:${id}`))
|
|
382
388
|
job.controller.abort(new DOMException("Operation cancelled before dispatch", "AbortError"));
|
|
383
389
|
const execution = makeExecution(job);
|
|
390
|
+
const kind = debug && debugOperation(operation);
|
|
391
|
+
const note = (outcome) => {
|
|
392
|
+
if (kind)
|
|
393
|
+
debug?.({ event: "job", operation: kind, outcome, operationId: id });
|
|
394
|
+
};
|
|
384
395
|
job.promise = queue
|
|
385
396
|
.then(async () => {
|
|
386
397
|
execution.validate();
|
|
398
|
+
assertForegroundQueueReady();
|
|
387
399
|
job.view.phase = "running";
|
|
400
|
+
note("started");
|
|
388
401
|
const result = await execute(operation, payload, execution);
|
|
389
402
|
if (Buffer.byteLength(JSON.stringify(result ?? null)) > MAX_MESSAGE_BYTES / 2)
|
|
390
403
|
throw new Error("Operation result exceeds its byte limit; use bounded inspection.");
|
|
404
|
+
if (isForegroundDirection(operation) && isForegroundQueueOutcome(result)) {
|
|
405
|
+
if (result.foregroundQueueCleanup === "before-mutation" && job.committed)
|
|
406
|
+
throw Object.assign(new Error("File-queue release and transfer outcome could not be verified."), {
|
|
407
|
+
code: OWNERSHIP_CLEANUP_REQUIRED,
|
|
408
|
+
});
|
|
409
|
+
foregroundRecoveryJob ??= job;
|
|
410
|
+
}
|
|
391
411
|
job.view.result = result;
|
|
392
412
|
job.view.phase = "done";
|
|
413
|
+
note(result === "cancelled" ? "cancelled" : (job.debugOutcome ?? "completed"));
|
|
393
414
|
})
|
|
394
415
|
.catch((error) => {
|
|
416
|
+
if (error instanceof ConsentPublicationError)
|
|
417
|
+
consentPublicationFailed = true;
|
|
395
418
|
job.view.phase = "failed";
|
|
396
419
|
job.view.error = remoteError(error);
|
|
420
|
+
note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
|
|
421
|
+
? "cancelled"
|
|
422
|
+
: (job.debugOutcome ??
|
|
423
|
+
(error instanceof SyncDecisionRequiredError || error instanceof DaemonStoppingError
|
|
424
|
+
? "blocked"
|
|
425
|
+
: "failed")));
|
|
397
426
|
if (job.committed)
|
|
398
427
|
for (const id of new Set([client, ...job.peers])) {
|
|
399
428
|
const affected = participants.get(id);
|
|
@@ -405,6 +434,9 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
405
434
|
for (const waiting of [...pending.values()])
|
|
406
435
|
if (waiting.callback.job === id)
|
|
407
436
|
waiting.reject(new Error("Operation finished."));
|
|
437
|
+
const owner = participants.get(client);
|
|
438
|
+
if (owner)
|
|
439
|
+
waiters.get(owner)?.changed();
|
|
408
440
|
hooks.idle?.();
|
|
409
441
|
});
|
|
410
442
|
queue = job.promise;
|
|
@@ -416,6 +448,66 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
416
448
|
peer.expiry = undefined;
|
|
417
449
|
peer.resumeFacts = undefined;
|
|
418
450
|
}
|
|
451
|
+
async function bootstrapStartup(client, generation, fingerprint, debug, signal, startup) {
|
|
452
|
+
const peer = requireParticipant(client);
|
|
453
|
+
const before = peer.facts;
|
|
454
|
+
const currentParticipant = () => {
|
|
455
|
+
assertOwner();
|
|
456
|
+
signal.throwIfAborted();
|
|
457
|
+
return !ledger.failed && requireParticipant(client) === peer && peer.facts === before;
|
|
458
|
+
};
|
|
459
|
+
if (before.generation !== generation || !before.hasUI || !["tui", "rpc"].includes(before.mode)) {
|
|
460
|
+
throw new Error("Only the attached interactive session can finish startup.");
|
|
461
|
+
}
|
|
462
|
+
const reviewState = () => {
|
|
463
|
+
if (backgroundJobs.size ||
|
|
464
|
+
[...participants.values()].some((item) => item.resumeUnsafe || item.reservations?.size))
|
|
465
|
+
return;
|
|
466
|
+
const running = [...jobs.values()].filter((job) => job.view.phase === "running" || job.view.phase === "queued");
|
|
467
|
+
if (!running.length && !pending.size)
|
|
468
|
+
return null;
|
|
469
|
+
if (running.length !== 1 || pending.size !== 1)
|
|
470
|
+
return;
|
|
471
|
+
const [job] = running;
|
|
472
|
+
const review = pending.values().next().value;
|
|
473
|
+
if (job.view.phase === "running" &&
|
|
474
|
+
!job.committed &&
|
|
475
|
+
!job.controller.signal.aborted &&
|
|
476
|
+
job.participantGeneration === undefined &&
|
|
477
|
+
review?.startupReviewLock &&
|
|
478
|
+
review.callback.job === job.view.id &&
|
|
479
|
+
review.target !== client)
|
|
480
|
+
return review;
|
|
481
|
+
};
|
|
482
|
+
if (before.ready || !currentParticipant() || reviewState() === undefined)
|
|
483
|
+
return false;
|
|
484
|
+
await hooks.factsChanged?.();
|
|
485
|
+
return admission.run(async () => {
|
|
486
|
+
const review = reviewState();
|
|
487
|
+
if (review === undefined || !currentParticipant())
|
|
488
|
+
return false;
|
|
489
|
+
const validateEvidence = await startup.probe(fingerprint, signal, review?.startupReviewLock);
|
|
490
|
+
const recheck = () => currentParticipant() && reviewState() === review;
|
|
491
|
+
if (!validateEvidence || !recheck())
|
|
492
|
+
return false;
|
|
493
|
+
const ready = { ...before, ready: true, startupDebug: debug };
|
|
494
|
+
await savePeers({ peer, facts: ready });
|
|
495
|
+
let accepted = false;
|
|
496
|
+
try {
|
|
497
|
+
if (!recheck() || !validateEvidence())
|
|
498
|
+
return false;
|
|
499
|
+
peer.facts = ready;
|
|
500
|
+
accepted = true;
|
|
501
|
+
participantsChanged();
|
|
502
|
+
hooks.idle?.();
|
|
503
|
+
return true;
|
|
504
|
+
}
|
|
505
|
+
finally {
|
|
506
|
+
if (!accepted)
|
|
507
|
+
await savePeers();
|
|
508
|
+
}
|
|
509
|
+
}, signal);
|
|
510
|
+
}
|
|
419
511
|
async function resumeContact(facts, disconnect) {
|
|
420
512
|
const peer = requireParticipant(facts.id, true);
|
|
421
513
|
const expiry = peer.expiry;
|
|
@@ -434,7 +526,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
434
526
|
const recheck = () => {
|
|
435
527
|
assertOwner();
|
|
436
528
|
signal.throwIfAborted();
|
|
437
|
-
if (
|
|
529
|
+
if (ledger.failed)
|
|
438
530
|
throw new Error("Daemon client ledger persistence is uncertain; reconcile with the existing owner before reconnecting.");
|
|
439
531
|
if (participants.get(facts.id) !== peer ||
|
|
440
532
|
peer.expiry !== expiry ||
|
|
@@ -523,10 +615,56 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
523
615
|
hooks.idle?.();
|
|
524
616
|
return result;
|
|
525
617
|
}
|
|
526
|
-
|
|
618
|
+
function stop() {
|
|
619
|
+
stopRequested = true;
|
|
620
|
+
for (const peer of participants.values())
|
|
621
|
+
waiters.get(peer)?.changed();
|
|
622
|
+
setImmediate(() => {
|
|
623
|
+
void close().catch(() => { });
|
|
624
|
+
});
|
|
625
|
+
return { stopping: true };
|
|
626
|
+
}
|
|
627
|
+
async function stopForeground(params, signal) {
|
|
628
|
+
if (params.check !== undefined && params.check !== true)
|
|
629
|
+
throw new Error("Invalid foreground stop request.");
|
|
630
|
+
const barrier = await readUpgradeOwner(paths);
|
|
631
|
+
signal?.throwIfAborted();
|
|
632
|
+
assertOwner();
|
|
633
|
+
if (params.check === true
|
|
634
|
+
? barrier !== undefined
|
|
635
|
+
: barrier?.purpose !== "cleanup" || barrier.instance !== identity.instance || barrier.pid !== identity.pid)
|
|
636
|
+
return { blocked: "A daemon upgrade or recovery is already pending." };
|
|
637
|
+
if (!published || !matchesPublishedIdentity(paths, identity))
|
|
638
|
+
return { blocked: "Daemon owner changed during queue cleanup." };
|
|
639
|
+
const job = foregroundRecoveryJob;
|
|
640
|
+
const requester = validId(params.client) ? participants.get(params.client) : undefined;
|
|
641
|
+
if (job?.view.phase !== "done" ||
|
|
642
|
+
job.view.id !== params.job ||
|
|
643
|
+
!requester ||
|
|
644
|
+
requester.facts.id !== job.client ||
|
|
645
|
+
requester.facts.generation !== params.generation ||
|
|
646
|
+
requester.facts.generation !== job.generation ||
|
|
647
|
+
contactState(requester) !== "active")
|
|
648
|
+
return { blocked: "The completed transfer is not owned by the current Pi session." };
|
|
649
|
+
if (ledger.failed ||
|
|
650
|
+
consentPublicationFailed ||
|
|
651
|
+
hooks.foregroundRecoveryAllowed?.() !== true ||
|
|
652
|
+
Object.values(readConsent(paths.root)?.setups ?? {}).some((setup) => setup.afterExit))
|
|
653
|
+
return { blocked: "Daemon authorization or ownership evidence needs repair before a restart." };
|
|
654
|
+
if (peerOperations.size ||
|
|
655
|
+
expiring ||
|
|
656
|
+
backgroundJobs.size ||
|
|
657
|
+
pending.size ||
|
|
658
|
+
[...jobs.values()].some(({ view }) => view.phase === "queued" || view.phase === "running"))
|
|
659
|
+
return { blocked: "Another daemon operation may still be running; no restart was attempted." };
|
|
660
|
+
if ([...participants.values()].some((peer) => peer !== requester && participates(peer) && processExists(peer.facts.pid)))
|
|
661
|
+
return { blocked: "Another live Pi session still uses this daemon; no restart was attempted." };
|
|
662
|
+
return params.check === true ? { eligible: true } : stop();
|
|
663
|
+
}
|
|
664
|
+
async function handle(method, params, signal, reviewDetails = false) {
|
|
527
665
|
if (automaticClosing && method !== "stop")
|
|
528
666
|
throw new DaemonStoppingError();
|
|
529
|
-
const cleanup = ["answer", "poll", "cancel", "detach", "pause", "handoff", "stop"].includes(method);
|
|
667
|
+
const cleanup = ["answer", "poll", "state-wait", "cancel", "detach", "pause", "handoff", "stop"].includes(method);
|
|
530
668
|
if (!published && !cleanup)
|
|
531
669
|
throw new Error("Daemon readiness is not published.");
|
|
532
670
|
if (!cleanup)
|
|
@@ -564,6 +702,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
564
702
|
participantsChanged();
|
|
565
703
|
participants.set(params.id, {
|
|
566
704
|
facts: structuredClone(params),
|
|
705
|
+
reviewDetails,
|
|
567
706
|
reservations: old?.reservations,
|
|
568
707
|
resumeUnsafe: old?.resumeUnsafe,
|
|
569
708
|
callbacks: old?.callbacks ?? new Map(),
|
|
@@ -611,12 +750,28 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
611
750
|
// Monitoring can await a queued reservation; never call it while admission is held.
|
|
612
751
|
await hooks.factsChanged?.();
|
|
613
752
|
assertOwner();
|
|
614
|
-
return poll(attached, 0);
|
|
753
|
+
return { ...poll(attached, 0), stateWait: 1 };
|
|
615
754
|
}
|
|
616
755
|
if (method === "resume-contact") {
|
|
617
756
|
validateFacts(params);
|
|
618
757
|
return resumeContact(params, signal);
|
|
619
758
|
}
|
|
759
|
+
if (method === "startup.bootstrap" && hooks.startup) {
|
|
760
|
+
if (foregroundRecoveryJob)
|
|
761
|
+
throw new Error("File-queue cleanup is pending; startup work did not begin.");
|
|
762
|
+
if (!record(params) ||
|
|
763
|
+
Object.keys(params).length !== 4 ||
|
|
764
|
+
!validId(params.client) ||
|
|
765
|
+
!validId(params.generation) ||
|
|
766
|
+
typeof params.fingerprint !== "string" ||
|
|
767
|
+
!/^[a-f0-9]{64}$/u.test(params.fingerprint) ||
|
|
768
|
+
typeof params.debug !== "boolean" ||
|
|
769
|
+
!signal)
|
|
770
|
+
throw new Error("Invalid startup bootstrap request.");
|
|
771
|
+
const peer = requireParticipant(params.client);
|
|
772
|
+
peer.seen = Date.now();
|
|
773
|
+
return bootstrapStartup(params.client, params.generation, params.fingerprint, params.debug, signal, hooks.startup);
|
|
774
|
+
}
|
|
620
775
|
if (!record(params))
|
|
621
776
|
throw new Error("Invalid request parameters.");
|
|
622
777
|
const contact = typeof params.client === "string" ? participants.get(params.client) : undefined;
|
|
@@ -638,10 +793,11 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
638
793
|
requireParticipant(params.facts.id);
|
|
639
794
|
peer.facts = structuredClone(params.facts);
|
|
640
795
|
const published = peer.facts;
|
|
641
|
-
|
|
796
|
+
const unchanged = JSON.stringify(old) === JSON.stringify(published);
|
|
797
|
+
if (!unchanged)
|
|
642
798
|
participantsChanged();
|
|
643
799
|
try {
|
|
644
|
-
await savePeers();
|
|
800
|
+
await savePeers(undefined, unchanged);
|
|
645
801
|
}
|
|
646
802
|
catch (error) {
|
|
647
803
|
if (peer.facts === published)
|
|
@@ -679,18 +835,52 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
679
835
|
throw new Error("Invalid operation envelope.");
|
|
680
836
|
return enqueue(params.id, params.client, params.operation, params.payload).view;
|
|
681
837
|
}
|
|
838
|
+
if (method === "state-wait") {
|
|
839
|
+
const peer = requireParticipant(params.client, true);
|
|
840
|
+
const client = peer.facts.id;
|
|
841
|
+
const generation = peer.facts.generation;
|
|
842
|
+
const requested = params.jobs;
|
|
843
|
+
if (params.generation !== generation ||
|
|
844
|
+
!Array.isArray(requested) ||
|
|
845
|
+
requested.length > DAEMON_JOB_CAPACITY ||
|
|
846
|
+
!requested.every(validId))
|
|
847
|
+
throw new Error("Invalid state wait.");
|
|
848
|
+
let mailbox = waiters.get(peer);
|
|
849
|
+
if (!mailbox) {
|
|
850
|
+
mailbox = new ParticipantStateWait();
|
|
851
|
+
waiters.set(peer, mailbox);
|
|
852
|
+
}
|
|
853
|
+
await mailbox.wait(params.revision, signal);
|
|
854
|
+
signal?.throwIfAborted();
|
|
855
|
+
if (participants.get(client) !== peer || peer.facts.generation !== generation)
|
|
856
|
+
throw new Error("Client changed during state wait.");
|
|
857
|
+
const finished = [...jobs.values()]
|
|
858
|
+
.filter((job) => job.client === client && (job.view.phase === "done" || job.view.phase === "failed"))
|
|
859
|
+
.map((job) => job.view.id);
|
|
860
|
+
return {
|
|
861
|
+
...poll(peer, params.cursor),
|
|
862
|
+
stateRevision: mailbox.version,
|
|
863
|
+
finished,
|
|
864
|
+
missing: requested.filter((id) => jobs.get(id)?.client !== client),
|
|
865
|
+
};
|
|
866
|
+
}
|
|
682
867
|
if (method === "poll") {
|
|
683
868
|
const peer = requireParticipant(params.client, true);
|
|
684
869
|
const job = typeof params.job === "string" ? jobs.get(params.job) : undefined;
|
|
685
870
|
if (params.job !== undefined && !job)
|
|
686
|
-
throw new Error(
|
|
871
|
+
throw new Error(UNKNOWN_JOB_RESULT);
|
|
687
872
|
if (job && job.client !== params.client)
|
|
688
873
|
throw new Error("Operation belongs to another client.");
|
|
689
874
|
return poll(peer, params.cursor, job);
|
|
690
875
|
}
|
|
691
876
|
if (method === "review-page") {
|
|
692
|
-
requireParticipant(params.client);
|
|
877
|
+
const peer = requireParticipant(params.client);
|
|
693
878
|
const waiting = typeof params.id === "string" ? pending.get(params.id) : undefined;
|
|
879
|
+
if (waiting?.pagedReview) {
|
|
880
|
+
if (waiting.pagedReview.generation !== peer.facts.generation)
|
|
881
|
+
throw new Error("Stale, foreign, or invalid review page.");
|
|
882
|
+
return waiting.pagedReview.page(params);
|
|
883
|
+
}
|
|
694
884
|
if (!waiting?.review ||
|
|
695
885
|
waiting.target !== params.client ||
|
|
696
886
|
!Number.isSafeInteger(params.index) ||
|
|
@@ -701,12 +891,20 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
701
891
|
return { id: params.id, index: params.index, content: waiting.review.slice(start, start + REVIEW_PAGE_CHARS) };
|
|
702
892
|
}
|
|
703
893
|
if (method === "answer") {
|
|
704
|
-
requireParticipant(params.client, true);
|
|
894
|
+
const peer = requireParticipant(params.client, true);
|
|
705
895
|
const waiting = typeof params.id === "string" ? pending.get(params.id) : undefined;
|
|
706
|
-
|
|
896
|
+
const offer = waiting?.pagedReview;
|
|
897
|
+
if (!waiting ||
|
|
898
|
+
waiting.target !== params.client ||
|
|
899
|
+
(offer && (offer.generation !== peer.facts.generation || params.generation !== offer.generation)))
|
|
707
900
|
throw new Error("Stale or foreign callback response.");
|
|
708
901
|
if (typeof params.error === "string")
|
|
709
902
|
waiting.reject(new Error(params.error.slice(0, 1024)));
|
|
903
|
+
else if (offer && params.value !== false) {
|
|
904
|
+
assertOwner();
|
|
905
|
+
requireParticipant(params.client);
|
|
906
|
+
waiting.resolve(offer.approved(params.value));
|
|
907
|
+
}
|
|
710
908
|
else
|
|
711
909
|
waiting.resolve(params.value);
|
|
712
910
|
return {};
|
|
@@ -729,13 +927,10 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
729
927
|
await job.promise;
|
|
730
928
|
return job.view;
|
|
731
929
|
}
|
|
732
|
-
if (method === "stop")
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
});
|
|
737
|
-
return { stopping: true };
|
|
738
|
-
}
|
|
930
|
+
if (method === "foreground-stop")
|
|
931
|
+
return stopForeground(params, signal);
|
|
932
|
+
if (method === "stop")
|
|
933
|
+
return stop();
|
|
739
934
|
throw new Error("Unknown daemon method.");
|
|
740
935
|
}
|
|
741
936
|
const respond = (response, status, value) => {
|
|
@@ -767,14 +962,14 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
767
962
|
respond(response, 403, { error: { name: "Error", message: "Invalid daemon identity or protocol." } });
|
|
768
963
|
return;
|
|
769
964
|
}
|
|
770
|
-
if (
|
|
965
|
+
if (["attach", "resume-contact", "startup.bootstrap", "state-wait", "foreground-stop"].includes(body.method)) {
|
|
771
966
|
admissionController = new AbortController();
|
|
772
967
|
response.once("close", disconnect);
|
|
773
968
|
if (response.destroyed)
|
|
774
969
|
disconnect();
|
|
775
970
|
}
|
|
776
|
-
const operation = handle(body.method, body.params, admissionController?.signal);
|
|
777
|
-
if (["attach", "resume-contact", "update", "detach", "pause", "handoff"].includes(body.method)) {
|
|
971
|
+
const operation = handle(body.method, body.params, admissionController?.signal, body.reviewDetails === 1);
|
|
972
|
+
if (["attach", "resume-contact", "startup.bootstrap", "update", "detach", "pause", "handoff"].includes(body.method)) {
|
|
778
973
|
peerOperations.add(operation);
|
|
779
974
|
void operation.finally(() => peerOperations.delete(operation)).catch(() => { });
|
|
780
975
|
}
|
|
@@ -801,6 +996,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
801
996
|
await publishIdentity(paths, identity);
|
|
802
997
|
assertOwner();
|
|
803
998
|
published = true;
|
|
999
|
+
debug?.({ event: "lifecycle", outcome: "starting" });
|
|
804
1000
|
}
|
|
805
1001
|
catch (error) {
|
|
806
1002
|
closed = true;
|
|
@@ -830,6 +1026,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
830
1026
|
invalidateExpiry(peer);
|
|
831
1027
|
else if (!peer.closing && !peer.publishing)
|
|
832
1028
|
peer.expiry = new AbortController();
|
|
1029
|
+
waiters.get(peer)?.changed();
|
|
833
1030
|
changed = true;
|
|
834
1031
|
for (const job of [...jobs.values(), ...backgroundJobs])
|
|
835
1032
|
if (!job.committed && (job.client === id || job.peers.has(id)))
|
|
@@ -853,7 +1050,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
853
1050
|
if (participationChanged)
|
|
854
1051
|
await hooks.factsChanged?.();
|
|
855
1052
|
}
|
|
856
|
-
const lifetime = async () => closed || compromised ||
|
|
1053
|
+
const lifetime = async () => closed || compromised || ledger.failed ? "pause" : ((await hooks.lifetime?.()) ?? "pause");
|
|
857
1054
|
if (hooks.lifetime) {
|
|
858
1055
|
idleExit = createIdleExit({
|
|
859
1056
|
live: () => liveClientFacts().length > 0,
|
|
@@ -866,12 +1063,12 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
866
1063
|
await Promise.allSettled([...jobs.values()].map((job) => job.promise));
|
|
867
1064
|
await Promise.allSettled([...peerOperations]);
|
|
868
1065
|
await expiring;
|
|
869
|
-
await
|
|
1066
|
+
await ledger.drain();
|
|
870
1067
|
},
|
|
871
1068
|
close: (current) => admission.run(async () => {
|
|
872
|
-
if (!current() || closed ||
|
|
1069
|
+
if (!current() || closed || ledger.failed || peerOperations.size)
|
|
873
1070
|
return false;
|
|
874
|
-
await
|
|
1071
|
+
await ledger.drain();
|
|
875
1072
|
const owned = await known();
|
|
876
1073
|
const policy = await lifetime();
|
|
877
1074
|
if (!owned ||
|
|
@@ -879,7 +1076,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
879
1076
|
!current() ||
|
|
880
1077
|
closed ||
|
|
881
1078
|
compromised ||
|
|
882
|
-
|
|
1079
|
+
ledger.failed ||
|
|
883
1080
|
peerOperations.size ||
|
|
884
1081
|
backgroundJobs.size ||
|
|
885
1082
|
pending.size ||
|
|
@@ -895,7 +1092,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
895
1092
|
return true;
|
|
896
1093
|
}),
|
|
897
1094
|
resume: () => hooks.idle?.(),
|
|
898
|
-
failed:
|
|
1095
|
+
failed: failure,
|
|
899
1096
|
});
|
|
900
1097
|
void idleExit.tick();
|
|
901
1098
|
}
|
|
@@ -910,8 +1107,10 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
910
1107
|
return closing;
|
|
911
1108
|
closing = (async () => {
|
|
912
1109
|
closed = true;
|
|
913
|
-
for (const peer of participants.values())
|
|
1110
|
+
for (const peer of participants.values()) {
|
|
914
1111
|
invalidateExpiry(peer);
|
|
1112
|
+
waiters.get(peer)?.changed();
|
|
1113
|
+
}
|
|
915
1114
|
clearInterval(heartbeat);
|
|
916
1115
|
for (const waiting of [...pending.values()])
|
|
917
1116
|
if (!waiting.callback.kind.startsWith("queue-"))
|
|
@@ -931,19 +1130,31 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
931
1130
|
await admission.run(async () => { });
|
|
932
1131
|
await Promise.allSettled([...peerOperations]);
|
|
933
1132
|
await expiring;
|
|
934
|
-
await
|
|
1133
|
+
await ledger.drain();
|
|
935
1134
|
for (const waiting of [...pending.values()])
|
|
936
1135
|
waiting.reject(new Error("Daemon stopping."));
|
|
937
1136
|
// A failed engine drain must retain the live owner, not permit an implicit restart.
|
|
938
1137
|
if (closeError)
|
|
939
1138
|
throw closeError;
|
|
940
1139
|
await endpoint.close();
|
|
941
|
-
|
|
1140
|
+
const owned = await known();
|
|
1141
|
+
if (owned)
|
|
942
1142
|
await fs.rm(paths.identity, { force: true });
|
|
943
1143
|
await release();
|
|
1144
|
+
released = true;
|
|
1145
|
+
if (owned && !compromised) {
|
|
1146
|
+
try {
|
|
1147
|
+
diagnostic?.({ event: "lifecycle", outcome: "drained" }, () => {
|
|
1148
|
+
assertRoot();
|
|
1149
|
+
return (!lstatSync(paths.owner, { throwIfNoEntry: false }) &&
|
|
1150
|
+
!lstatSync(paths.identity, { throwIfNoEntry: false }));
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
catch { }
|
|
1154
|
+
}
|
|
944
1155
|
hooks.stopped?.();
|
|
945
1156
|
})().catch((error) => {
|
|
946
|
-
|
|
1157
|
+
failure();
|
|
947
1158
|
closing = undefined;
|
|
948
1159
|
throw error;
|
|
949
1160
|
});
|
|
@@ -974,6 +1185,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
974
1185
|
identity,
|
|
975
1186
|
paths,
|
|
976
1187
|
close,
|
|
1188
|
+
recordBootOutcome: (outcome) => debug?.({ event: "lifecycle", outcome }),
|
|
977
1189
|
backgroundExecution,
|
|
978
1190
|
get retainedEndpoint() {
|
|
979
1191
|
return endpoint.retainedDirectory;
|
|
@@ -986,6 +1198,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
986
1198
|
checkLifetime: () => idleExit?.tick() ?? Promise.resolve(),
|
|
987
1199
|
isIdle: () => !closed &&
|
|
988
1200
|
!stopRequested &&
|
|
1201
|
+
!foregroundRecoveryJob &&
|
|
989
1202
|
[...jobs.values()].every((job) => job.view.phase !== "queued" && job.view.phase !== "running"),
|
|
990
1203
|
get closed() {
|
|
991
1204
|
return closed;
|