@narumitw/pi-sync-daemon 0.0.0-stage → 0.2.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 +13 -0
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +128 -0
- package/dist/client.d.ts +55 -0
- package/dist/client.js +484 -0
- package/dist/consent.d.ts +24 -0
- package/dist/consent.js +205 -0
- package/dist/document.d.ts +10 -0
- package/dist/document.js +6 -0
- package/dist/endpoint.d.ts +8 -0
- package/dist/endpoint.js +91 -0
- package/dist/engine/backends/backend-factory.d.ts +6 -0
- package/dist/engine/backends/backend-factory.js +16 -0
- package/dist/engine/backends/backend-identity.d.ts +3 -0
- package/dist/engine/backends/backend-identity.js +38 -0
- package/dist/engine/backends/backend-types.d.ts +70 -0
- package/dist/engine/backends/backend-types.js +1 -0
- package/dist/engine/backends/git/git-backend.d.ts +55 -0
- package/dist/engine/backends/git/git-backend.js +700 -0
- package/dist/engine/backends/git/git-config.d.ts +5 -0
- package/dist/engine/backends/git/git-config.js +118 -0
- package/dist/engine/backends/git/git-runner.d.ts +25 -0
- package/dist/engine/backends/git/git-runner.js +232 -0
- package/dist/engine/backends/git/git-storage.d.ts +39 -0
- package/dist/engine/backends/git/git-storage.js +226 -0
- package/dist/engine/backends/s3/s3-backend.d.ts +32 -0
- package/dist/engine/backends/s3/s3-backend.js +436 -0
- package/dist/engine/backends/s3/s3-client.d.ts +36 -0
- package/dist/engine/backends/s3/s3-client.js +352 -0
- package/dist/engine/backends/s3/s3-conditions.d.ts +4 -0
- package/dist/engine/backends/s3/s3-conditions.js +66 -0
- package/dist/engine/backends/snapshot-pointer.d.ts +6 -0
- package/dist/engine/backends/snapshot-pointer.js +22 -0
- package/dist/engine/backends/sync-backend.d.ts +71 -0
- package/dist/engine/backends/sync-backend.js +23 -0
- package/dist/engine/backends/webdav/webdav-backend.d.ts +34 -0
- package/dist/engine/backends/webdav/webdav-backend.js +534 -0
- package/dist/engine/backends/webdav/webdav-client.d.ts +36 -0
- package/dist/engine/backends/webdav/webdav-client.js +326 -0
- package/dist/engine/backends/webdav/webdav-config.d.ts +5 -0
- package/dist/engine/backends/webdav/webdav-config.js +73 -0
- package/dist/engine/commands/command-types.d.ts +31 -0
- package/dist/engine/commands/command-types.js +1 -0
- package/dist/engine/host.d.ts +70 -0
- package/dist/engine/host.js +16 -0
- package/dist/engine/paths.d.ts +9 -0
- package/dist/engine/paths.js +71 -0
- package/dist/engine/settings/config-errors.d.ts +1 -0
- package/dist/engine/settings/config-errors.js +4 -0
- package/dist/engine/settings/config-file.d.ts +33 -0
- package/dist/engine/settings/config-file.js +630 -0
- package/dist/engine/settings/config.d.ts +24 -0
- package/dist/engine/settings/config.js +200 -0
- package/dist/engine/settings/settings-management.d.ts +24 -0
- package/dist/engine/settings/settings-management.js +191 -0
- package/dist/engine/settings/settings-store.d.ts +8 -0
- package/dist/engine/settings/settings-store.js +41 -0
- package/dist/engine/settings/settings-types.d.ts +134 -0
- package/dist/engine/settings/settings-types.js +1 -0
- package/dist/engine/settings/settings-validation.d.ts +15 -0
- package/dist/engine/settings/settings-validation.js +356 -0
- package/dist/engine/snapshot/session-paths.d.ts +12 -0
- package/dist/engine/snapshot/session-paths.js +91 -0
- package/dist/engine/snapshot/snapshot-apply.d.ts +22 -0
- package/dist/engine/snapshot/snapshot-apply.js +262 -0
- package/dist/engine/snapshot/snapshot-case-replacement.d.ts +15 -0
- package/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
- package/dist/engine/snapshot/snapshot-codec.d.ts +6 -0
- package/dist/engine/snapshot/snapshot-codec.js +53 -0
- package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -0
- package/dist/engine/snapshot/snapshot-exclude-safety.js +47 -0
- package/dist/engine/snapshot/snapshot-mutation-queues.d.ts +9 -0
- package/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
- package/dist/engine/snapshot/snapshot-paths.d.ts +1 -0
- package/dist/engine/snapshot/snapshot-paths.js +11 -0
- package/dist/engine/snapshot/snapshot-root-transition.d.ts +25 -0
- package/dist/engine/snapshot/snapshot-root-transition.js +122 -0
- package/dist/engine/snapshot/snapshot-transaction-directory.d.ts +2 -0
- package/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
- package/dist/engine/snapshot/snapshot-transaction-plan.d.ts +12 -0
- package/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
- package/dist/engine/snapshot/snapshot-transaction.d.ts +15 -0
- package/dist/engine/snapshot/snapshot-transaction.js +787 -0
- package/dist/engine/snapshot/snapshot-types.d.ts +48 -0
- package/dist/engine/snapshot/snapshot-types.js +1 -0
- package/dist/engine/snapshot/snapshot.d.ts +30 -0
- package/dist/engine/snapshot/snapshot.js +364 -0
- package/dist/engine/state/json-file.d.ts +6 -0
- package/dist/engine/state/json-file.js +49 -0
- package/dist/engine/state/lock-policy.d.ts +2 -0
- package/dist/engine/state/lock-policy.js +2 -0
- package/dist/engine/state/lock.d.ts +20 -0
- package/dist/engine/state/lock.js +259 -0
- package/dist/engine/state/lockfile-fs.d.ts +13 -0
- package/dist/engine/state/lockfile-fs.js +13 -0
- package/dist/engine/state/merge-baseline-store.d.ts +11 -0
- package/dist/engine/state/merge-baseline-store.js +187 -0
- package/dist/engine/state/mutation-directory-sync.d.ts +5 -0
- package/dist/engine/state/mutation-directory-sync.js +34 -0
- package/dist/engine/state/operation-availability.d.ts +49 -0
- package/dist/engine/state/operation-availability.js +40 -0
- package/dist/engine/state/state-directory.d.ts +14 -0
- package/dist/engine/state/state-directory.js +225 -0
- package/dist/engine/state/state-types.d.ts +27 -0
- package/dist/engine/state/state-types.js +1 -0
- package/dist/engine/state/sync-state-store.d.ts +11 -0
- package/dist/engine/state/sync-state-store.js +54 -0
- package/dist/engine/sync/agent-candidate.d.ts +44 -0
- package/dist/engine/sync/agent-candidate.js +207 -0
- package/dist/engine/sync/agent-plan.d.ts +8 -0
- package/dist/engine/sync/agent-plan.js +84 -0
- package/dist/engine/sync/agent-policy.d.ts +9 -0
- package/dist/engine/sync/agent-policy.js +10 -0
- package/dist/engine/sync/agent-refusal-retry.d.ts +4 -0
- package/dist/engine/sync/agent-refusal-retry.js +39 -0
- package/dist/engine/sync/agent-request.d.ts +14 -0
- package/dist/engine/sync/agent-request.js +13 -0
- package/dist/engine/sync/agent-runner.d.ts +6 -0
- package/dist/engine/sync/agent-runner.js +183 -0
- package/dist/engine/sync/agent-store.d.ts +7 -0
- package/dist/engine/sync/agent-store.js +177 -0
- package/dist/engine/sync/agent-sync.d.ts +4 -0
- package/dist/engine/sync/agent-sync.js +132 -0
- package/dist/engine/sync/apply-review.d.ts +8 -0
- package/dist/engine/sync/apply-review.js +51 -0
- package/dist/engine/sync/conflict-artifact-ownership.d.ts +4 -0
- package/dist/engine/sync/conflict-artifact-ownership.js +53 -0
- package/dist/engine/sync/conflict-artifacts.d.ts +32 -0
- package/dist/engine/sync/conflict-artifacts.js +158 -0
- package/dist/engine/sync/conflict-groups.d.ts +9 -0
- package/dist/engine/sync/conflict-groups.js +76 -0
- package/dist/engine/sync/conflict-preview.d.ts +4 -0
- package/dist/engine/sync/conflict-preview.js +53 -0
- package/dist/engine/sync/conflict-resolution.d.ts +13 -0
- package/dist/engine/sync/conflict-resolution.js +53 -0
- package/dist/engine/sync/conflict-retention.d.ts +5 -0
- package/dist/engine/sync/conflict-retention.js +61 -0
- package/dist/engine/sync/conflict-review.d.ts +4 -0
- package/dist/engine/sync/conflict-review.js +73 -0
- package/dist/engine/sync/content-conflicts.d.ts +10 -0
- package/dist/engine/sync/content-conflicts.js +70 -0
- package/dist/engine/sync/continuous-errors.d.ts +14 -0
- package/dist/engine/sync/continuous-errors.js +66 -0
- package/dist/engine/sync/continuous-lease.d.ts +9 -0
- package/dist/engine/sync/continuous-lease.js +206 -0
- package/dist/engine/sync/continuous-record.d.ts +31 -0
- package/dist/engine/sync/continuous-record.js +199 -0
- package/dist/engine/sync/continuous-storage.d.ts +14 -0
- package/dist/engine/sync/continuous-storage.js +59 -0
- package/dist/engine/sync/continuous-sync.d.ts +15 -0
- package/dist/engine/sync/continuous-sync.js +496 -0
- package/dist/engine/sync/continuous-watch.d.ts +3 -0
- package/dist/engine/sync/continuous-watch.js +65 -0
- package/dist/engine/sync/exclude-policy.d.ts +5 -0
- package/dist/engine/sync/exclude-policy.js +79 -0
- package/dist/engine/sync/field-migration.d.ts +5 -0
- package/dist/engine/sync/field-migration.js +20 -0
- package/dist/engine/sync/file-merge-planner.d.ts +36 -0
- package/dist/engine/sync/file-merge-planner.js +123 -0
- package/dist/engine/sync/initialization.d.ts +12 -0
- package/dist/engine/sync/initialization.js +75 -0
- package/dist/engine/sync/json-document.d.ts +29 -0
- package/dist/engine/sync/json-document.js +172 -0
- package/dist/engine/sync/local-field-policy.d.ts +2 -0
- package/dist/engine/sync/local-field-policy.js +26 -0
- package/dist/engine/sync/local-fields.d.ts +9 -0
- package/dist/engine/sync/local-fields.js +116 -0
- package/dist/engine/sync/merge-apply.d.ts +5 -0
- package/dist/engine/sync/merge-apply.js +386 -0
- package/dist/engine/sync/merge-journal.d.ts +31 -0
- package/dist/engine/sync/merge-journal.js +179 -0
- package/dist/engine/sync/merge-transfer-error.d.ts +3 -0
- package/dist/engine/sync/merge-transfer-error.js +64 -0
- package/dist/engine/sync/merged-sync.d.ts +6 -0
- package/dist/engine/sync/merged-sync.js +618 -0
- package/dist/engine/sync/mutation-owner.d.ts +2 -0
- package/dist/engine/sync/mutation-owner.js +18 -0
- package/dist/engine/sync/package-merge.d.ts +3 -0
- package/dist/engine/sync/package-merge.js +82 -0
- package/dist/engine/sync/partial-progress.d.ts +15 -0
- package/dist/engine/sync/partial-progress.js +39 -0
- package/dist/engine/sync/remote-snapshot.d.ts +28 -0
- package/dist/engine/sync/remote-snapshot.js +62 -0
- package/dist/engine/sync/resolver-stream.d.ts +4 -0
- package/dist/engine/sync/resolver-stream.js +34 -0
- package/dist/engine/sync/session-merge.d.ts +3 -0
- package/dist/engine/sync/session-merge.js +178 -0
- package/dist/engine/sync/session-push.d.ts +5 -0
- package/dist/engine/sync/session-push.js +32 -0
- package/dist/engine/sync/settings-conflicts.d.ts +8 -0
- package/dist/engine/sync/settings-conflicts.js +56 -0
- package/dist/engine/sync/settings-merge.d.ts +13 -0
- package/dist/engine/sync/settings-merge.js +93 -0
- package/dist/engine/sync/signals.d.ts +2 -0
- package/dist/engine/sync/signals.js +8 -0
- package/dist/engine/sync/startup-timings.d.ts +11 -0
- package/dist/engine/sync/startup-timings.js +44 -0
- package/dist/engine/sync/sync-decision.d.ts +35 -0
- package/dist/engine/sync/sync-decision.js +66 -0
- package/dist/engine/sync/sync-error-guidance.d.ts +2 -0
- package/dist/engine/sync/sync-error-guidance.js +55 -0
- package/dist/engine/sync/sync-errors.d.ts +9 -0
- package/dist/engine/sync/sync-errors.js +18 -0
- package/dist/engine/sync/sync-inspection.d.ts +26 -0
- package/dist/engine/sync/sync-inspection.js +40 -0
- package/dist/engine/sync/sync-loaders.d.ts +7 -0
- package/dist/engine/sync/sync-loaders.js +8 -0
- package/dist/engine/sync/sync-local.d.ts +5 -0
- package/dist/engine/sync/sync-local.js +40 -0
- package/dist/engine/sync/sync-mutations.d.ts +30 -0
- package/dist/engine/sync/sync-mutations.js +589 -0
- package/dist/engine/sync/sync-operations.d.ts +2 -0
- package/dist/engine/sync/sync-operations.js +3 -0
- package/dist/engine/sync/sync-policy.d.ts +85 -0
- package/dist/engine/sync/sync-policy.js +356 -0
- package/dist/engine/sync/sync-queries.d.ts +7 -0
- package/dist/engine/sync/sync-queries.js +195 -0
- package/dist/engine/sync/sync-state.d.ts +31 -0
- package/dist/engine/sync/sync-state.js +92 -0
- package/dist/engine/sync/text-merge.d.ts +19 -0
- package/dist/engine/sync/text-merge.js +124 -0
- package/dist/engine/types.d.ts +5 -0
- package/dist/engine/types.js +2 -0
- package/dist/engine/ui/merge-review.d.ts +2 -0
- package/dist/engine/ui/merge-review.js +7 -0
- package/dist/engine/ui/merged-sync-summary.d.ts +25 -0
- package/dist/engine/ui/merged-sync-summary.js +86 -0
- package/dist/engine/ui/sync-format.d.ts +13 -0
- package/dist/engine/ui/sync-format.js +150 -0
- package/dist/engine/ui/sync-status.d.ts +9 -0
- package/dist/engine/ui/sync-status.js +30 -0
- package/dist/engine/ui/terminal-text.d.ts +3 -0
- package/dist/engine/ui/terminal-text.js +9 -0
- package/dist/engine/ui/transfer-changes.d.ts +12 -0
- package/dist/engine/ui/transfer-changes.js +24 -0
- package/dist/engine/ui/transfer-review.d.ts +3 -0
- package/dist/engine/ui/transfer-review.js +19 -0
- package/dist/engine-service.d.ts +11 -0
- package/dist/engine-service.js +315 -0
- package/dist/identity.d.ts +20 -0
- package/dist/identity.js +133 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/lifecycle-log.d.ts +7 -0
- package/dist/lifecycle-log.js +53 -0
- package/dist/lifecycle.d.ts +2 -0
- package/dist/lifecycle.js +21 -0
- package/dist/model-signature.d.ts +2 -0
- package/dist/model-signature.js +7 -0
- package/dist/monitor.d.ts +11 -0
- package/dist/monitor.js +245 -0
- package/dist/participant-admission.d.ts +5 -0
- package/dist/participant-admission.js +30 -0
- package/dist/protocol.d.ts +97 -0
- package/dist/protocol.js +90 -0
- package/dist/resolver-host.d.ts +11 -0
- package/dist/resolver-host.js +78 -0
- package/dist/server.d.ts +18 -0
- package/dist/server.js +724 -0
- package/dist/service-host.d.ts +7 -0
- package/dist/service-host.js +174 -0
- package/docs/architecture.md +133 -0
- package/package.json +54 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,724 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import lockfile from "proper-lockfile";
|
|
6
|
+
import { endpointOwner } from "./endpoint.js";
|
|
7
|
+
import { canonicalRootGuard, daemonPaths, privateDirectory, processExists, publishIdentity, readIdentity, readJsonBody, runtimePaths, } from "./identity.js";
|
|
8
|
+
import { withCleanup } from "./lifecycle.js";
|
|
9
|
+
import { ParticipantAdmission } from "./participant-admission.js";
|
|
10
|
+
import { MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, validateFacts, validateHandoff, validId, } from "./protocol.js";
|
|
11
|
+
export async function startServer(root, execute, hooks = {}) {
|
|
12
|
+
const base = await runtimePaths(root);
|
|
13
|
+
const identity = {
|
|
14
|
+
version: 1,
|
|
15
|
+
root: base.root,
|
|
16
|
+
instance: randomUUID(),
|
|
17
|
+
pid: process.pid,
|
|
18
|
+
token: randomBytes(32).toString("hex"),
|
|
19
|
+
};
|
|
20
|
+
const paths = daemonPaths(base, identity.instance);
|
|
21
|
+
const assertRoot = canonicalRootGuard(paths.root);
|
|
22
|
+
assertRoot();
|
|
23
|
+
await privateDirectory(paths.directory);
|
|
24
|
+
const previous = await readIdentity(paths);
|
|
25
|
+
if (previous && processExists(previous.pid))
|
|
26
|
+
throw new Error("A daemon owner is still alive; refusing replacement.");
|
|
27
|
+
let compromised = false;
|
|
28
|
+
let published = false;
|
|
29
|
+
const release = await lockfile.lock(paths.directory, {
|
|
30
|
+
realpath: false,
|
|
31
|
+
lockfilePath: paths.owner,
|
|
32
|
+
stale: 30_000,
|
|
33
|
+
update: 5_000,
|
|
34
|
+
onCompromised: () => {
|
|
35
|
+
compromised = true;
|
|
36
|
+
if (published)
|
|
37
|
+
void close().catch(() => { });
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
const participants = new Map();
|
|
41
|
+
const admission = new ParticipantAdmission();
|
|
42
|
+
const jobs = new Map();
|
|
43
|
+
const backgroundJobs = new Set();
|
|
44
|
+
const cancelled = new Set();
|
|
45
|
+
const closedClients = new Set();
|
|
46
|
+
// Retain tombstones after result eviction; replay must never dispatch a second write.
|
|
47
|
+
const retired = new Set();
|
|
48
|
+
const pending = new Map();
|
|
49
|
+
const peersFile = path.join(paths.directory, "clients.json");
|
|
50
|
+
let sequence = 0;
|
|
51
|
+
let closed = false;
|
|
52
|
+
let queue = Promise.resolve();
|
|
53
|
+
let closing;
|
|
54
|
+
let peerWrites = Promise.resolve();
|
|
55
|
+
let heartbeat;
|
|
56
|
+
function savePeers() {
|
|
57
|
+
const operation = peerWrites.then(writePeers);
|
|
58
|
+
peerWrites = operation.catch(() => { });
|
|
59
|
+
return operation;
|
|
60
|
+
}
|
|
61
|
+
async function writePeers() {
|
|
62
|
+
const temporary = path.join(paths.directory, `.${randomUUID()}.clients`);
|
|
63
|
+
const data = {
|
|
64
|
+
version: 1,
|
|
65
|
+
root: paths.root,
|
|
66
|
+
clients: [...participants.values()]
|
|
67
|
+
.filter((peer) => processExists(peer.facts.pid))
|
|
68
|
+
.map((peer) => ({ ...peer.facts, handoff: peer.handoff })),
|
|
69
|
+
};
|
|
70
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
71
|
+
try {
|
|
72
|
+
await handle.writeFile(JSON.stringify(data));
|
|
73
|
+
await handle.sync();
|
|
74
|
+
await handle.close();
|
|
75
|
+
await fs.rename(temporary, peersFile);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await handle.close().catch(() => { });
|
|
79
|
+
await fs.rm(temporary, { force: true });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
try {
|
|
84
|
+
const before = await fs.lstat(peersFile);
|
|
85
|
+
if (!before.isFile() ||
|
|
86
|
+
before.isSymbolicLink() ||
|
|
87
|
+
before.size > MAX_MESSAGE_BYTES ||
|
|
88
|
+
(process.getuid && before.uid !== process.getuid()) ||
|
|
89
|
+
(process.platform !== "win32" && before.mode & 0o077))
|
|
90
|
+
throw new Error("Unsafe daemon client record.");
|
|
91
|
+
const handle = await fs.open(peersFile, "r");
|
|
92
|
+
try {
|
|
93
|
+
const opened = await handle.stat();
|
|
94
|
+
if (opened.dev !== before.dev || opened.ino !== before.ino)
|
|
95
|
+
throw new Error("Daemon client record changed while opening.");
|
|
96
|
+
const data = JSON.parse(await handle.readFile("utf8"));
|
|
97
|
+
if (!record(data) ||
|
|
98
|
+
data.version !== 1 ||
|
|
99
|
+
data.root !== paths.root ||
|
|
100
|
+
!Array.isArray(data.clients) ||
|
|
101
|
+
data.clients.length > 64)
|
|
102
|
+
throw new Error("Invalid daemon client record; evidence retained.");
|
|
103
|
+
for (const stored of data.clients) {
|
|
104
|
+
if (!record(stored))
|
|
105
|
+
throw new Error("Invalid stored participant.");
|
|
106
|
+
const { handoff, ...value } = stored;
|
|
107
|
+
validateFacts(value);
|
|
108
|
+
if (handoff !== undefined)
|
|
109
|
+
validateHandoff(handoff);
|
|
110
|
+
if (processExists(value.pid)) {
|
|
111
|
+
if (handoff?.kind === "exit")
|
|
112
|
+
closedClients.add(value.id);
|
|
113
|
+
participants.set(value.id, {
|
|
114
|
+
facts: value,
|
|
115
|
+
handoff,
|
|
116
|
+
callbacks: new Map(),
|
|
117
|
+
events: [],
|
|
118
|
+
connected: false,
|
|
119
|
+
closing: false,
|
|
120
|
+
suspected: handoff?.kind !== "exit",
|
|
121
|
+
seen: 0,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
await handle.close();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error.code !== "ENOENT")
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
await release();
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
const known = async () => {
|
|
140
|
+
const current = await readIdentity(paths);
|
|
141
|
+
return current?.instance === identity.instance && current.pid === process.pid && current.token === identity.token;
|
|
142
|
+
};
|
|
143
|
+
const emit = (kind, payload, target) => {
|
|
144
|
+
const event = { id: ++sequence, kind, payload };
|
|
145
|
+
if (Buffer.byteLength(JSON.stringify(event)) > MAX_MESSAGE_BYTES / 8)
|
|
146
|
+
throw new Error("Notification exceeds the local API limit; use bounded diagnostics. No review was truncated.");
|
|
147
|
+
for (const [id, peer] of participants) {
|
|
148
|
+
if (target && id !== target)
|
|
149
|
+
continue;
|
|
150
|
+
peer.events.push(event);
|
|
151
|
+
while (peer.events.length > 128 || Buffer.byteLength(JSON.stringify(peer.events)) > MAX_MESSAGE_BYTES / 8)
|
|
152
|
+
peer.events.shift();
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const assertOwner = () => {
|
|
156
|
+
if (closed || compromised)
|
|
157
|
+
throw new Error("Daemon ownership is no longer valid.");
|
|
158
|
+
assertRoot();
|
|
159
|
+
};
|
|
160
|
+
const requireParticipant = (id, cleanup = false) => {
|
|
161
|
+
if (!validId(id))
|
|
162
|
+
throw new Error("Invalid client identity.");
|
|
163
|
+
const peer = participants.get(id);
|
|
164
|
+
if (!peer ||
|
|
165
|
+
(!cleanup &&
|
|
166
|
+
(peer.publishing ||
|
|
167
|
+
!peer.connected ||
|
|
168
|
+
peer.closing ||
|
|
169
|
+
Date.now() - peer.seen > 5_000 ||
|
|
170
|
+
!processExists(peer.facts.pid))))
|
|
171
|
+
throw new Error("Client is not attached or is closing.");
|
|
172
|
+
return peer;
|
|
173
|
+
};
|
|
174
|
+
const liveClientFacts = () => [...participants.values()].filter((peer) => processExists(peer.facts.pid)).map((peer) => peer.facts);
|
|
175
|
+
const participantFacts = () => [...participants.values()]
|
|
176
|
+
.filter((peer) => !peer.publishing && (peer.connected || peer.suspected) && processExists(peer.facts.pid))
|
|
177
|
+
.map((peer) => (peer.closing || peer.suspected ? { ...peer.facts, idle: false } : peer.facts));
|
|
178
|
+
const poll = (peer, cursor, job) => ({
|
|
179
|
+
cursor: sequence,
|
|
180
|
+
callbacks: [...peer.callbacks.values()],
|
|
181
|
+
events: peer.events.filter((event) => event.id > (typeof cursor === "number" && Number.isSafeInteger(cursor) ? cursor : 0)),
|
|
182
|
+
job: job?.view,
|
|
183
|
+
});
|
|
184
|
+
function makeExecution(job) {
|
|
185
|
+
const validate = () => {
|
|
186
|
+
if (compromised)
|
|
187
|
+
throw new Error("Daemon ownership is no longer valid.");
|
|
188
|
+
// Finish journal/publication bookkeeping after commit even if a UI detaches or stop begins.
|
|
189
|
+
if (job.committed) {
|
|
190
|
+
assertRoot();
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
assertOwner();
|
|
194
|
+
job.controller.signal.throwIfAborted();
|
|
195
|
+
if (job.client) {
|
|
196
|
+
const peer = requireParticipant(job.client);
|
|
197
|
+
if (peer.facts.generation !== job.generation)
|
|
198
|
+
throw new Error("Client session generation changed.");
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
const request = (kind, data, target = job.client, signal = job.controller.signal) => {
|
|
202
|
+
const cleanup = kind === "queue-release";
|
|
203
|
+
if (!cleanup)
|
|
204
|
+
validate();
|
|
205
|
+
if (!target)
|
|
206
|
+
throw new Error("This operation requires an attached UI client.");
|
|
207
|
+
const peer = requireParticipant(target, cleanup);
|
|
208
|
+
const callback = { id: randomUUID(), job: job.view.id, kind, payload: data };
|
|
209
|
+
let review;
|
|
210
|
+
if (kind === "merge-review" &&
|
|
211
|
+
record(data) &&
|
|
212
|
+
typeof data.content === "string" &&
|
|
213
|
+
Buffer.byteLength(data.content) > REVIEW_PAGE_CHARS) {
|
|
214
|
+
const bytes = Buffer.byteLength(data.content);
|
|
215
|
+
if (bytes > MAX_REVIEW_BYTES)
|
|
216
|
+
throw new Error("Exact review exceeds its byte limit; no truncated review was approved.");
|
|
217
|
+
review = data.content;
|
|
218
|
+
callback.payload = { ...data, content: undefined };
|
|
219
|
+
callback.review = {
|
|
220
|
+
pages: Math.ceil(review.length / REVIEW_PAGE_CHARS),
|
|
221
|
+
bytes,
|
|
222
|
+
sha256: createHash("sha256").update(review).digest("hex"),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
if (peer.callbacks.size >= 64 ||
|
|
226
|
+
Buffer.byteLength(JSON.stringify([...peer.callbacks.values(), callback])) > MAX_MESSAGE_BYTES / 8)
|
|
227
|
+
throw new Error("Callback exceeds its byte limit; no review was approved.");
|
|
228
|
+
job.peers.add(target);
|
|
229
|
+
return new Promise((resolve, reject) => {
|
|
230
|
+
let timer;
|
|
231
|
+
const effectiveSignal = cleanup ? undefined : signal;
|
|
232
|
+
const abort = () => finish(undefined, effectiveSignal?.reason);
|
|
233
|
+
const finish = (value, error) => {
|
|
234
|
+
if (timer)
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
effectiveSignal?.removeEventListener("abort", abort);
|
|
237
|
+
if (!pending.delete(callback.id))
|
|
238
|
+
return;
|
|
239
|
+
peer.callbacks.delete(callback.id);
|
|
240
|
+
sequence++;
|
|
241
|
+
if (error)
|
|
242
|
+
reject(error);
|
|
243
|
+
else
|
|
244
|
+
resolve(value);
|
|
245
|
+
};
|
|
246
|
+
pending.set(callback.id, {
|
|
247
|
+
callback,
|
|
248
|
+
review,
|
|
249
|
+
target,
|
|
250
|
+
resolve: (value) => finish(value),
|
|
251
|
+
reject: (error) => finish(undefined, error),
|
|
252
|
+
});
|
|
253
|
+
peer.callbacks.set(callback.id, callback);
|
|
254
|
+
sequence++;
|
|
255
|
+
effectiveSignal?.addEventListener("abort", abort, { once: true });
|
|
256
|
+
if (kind.startsWith("queue-")) {
|
|
257
|
+
timer = setTimeout(() => finish(undefined, new Error("Client file-queue acknowledgement timed out; work was stopped.")), 30_000);
|
|
258
|
+
timer.unref?.();
|
|
259
|
+
}
|
|
260
|
+
if (effectiveSignal?.aborted)
|
|
261
|
+
abort();
|
|
262
|
+
});
|
|
263
|
+
};
|
|
264
|
+
return {
|
|
265
|
+
root: paths.root,
|
|
266
|
+
clientId: job.client,
|
|
267
|
+
signal: job.controller.signal,
|
|
268
|
+
facts: () => (job.client ? participants.get(job.client)?.facts : undefined),
|
|
269
|
+
participants: participantFacts,
|
|
270
|
+
liveClients: liveClientFacts,
|
|
271
|
+
withParticipants: (action) => admission.run(async () => {
|
|
272
|
+
validate();
|
|
273
|
+
return action(participantFacts());
|
|
274
|
+
}, job.committed ? undefined : job.controller.signal),
|
|
275
|
+
validate,
|
|
276
|
+
request,
|
|
277
|
+
emit: (kind, data, target = job.client) => emit(kind, data, target),
|
|
278
|
+
committed: () => {
|
|
279
|
+
job.committed = true;
|
|
280
|
+
emit("commit", { job: job.view.id }, job.client);
|
|
281
|
+
},
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
function enqueue(id, client, operation, payload) {
|
|
285
|
+
const peer = requireParticipant(client);
|
|
286
|
+
if (!id.startsWith(operationPrefix(identity)))
|
|
287
|
+
throw new Error("Operation belongs to another daemon instance; reconcile journals instead of replaying.");
|
|
288
|
+
const digest = createHash("sha256").update(JSON.stringify({ client, operation, payload })).digest("hex");
|
|
289
|
+
const duplicate = jobs.get(id);
|
|
290
|
+
if (duplicate) {
|
|
291
|
+
if (duplicate.digest !== digest || duplicate.client !== client)
|
|
292
|
+
throw new Error("Operation ID was reused with different input.");
|
|
293
|
+
return duplicate;
|
|
294
|
+
}
|
|
295
|
+
if (retired.has(id))
|
|
296
|
+
throw new Error("Operation result expired; reconcile the existing journal before starting new work.");
|
|
297
|
+
if (retired.size + jobs.size >= 4096)
|
|
298
|
+
throw new Error("Daemon operation ledger is full; drain and restart explicitly.");
|
|
299
|
+
if (jobs.size >= 64) {
|
|
300
|
+
for (const [key, job] of jobs)
|
|
301
|
+
if (job.view.phase === "done" || job.view.phase === "failed") {
|
|
302
|
+
retired.add(key);
|
|
303
|
+
jobs.delete(key);
|
|
304
|
+
break;
|
|
305
|
+
}
|
|
306
|
+
if (jobs.size >= 64)
|
|
307
|
+
throw new Error("Daemon job capacity reached.");
|
|
308
|
+
}
|
|
309
|
+
const job = {
|
|
310
|
+
view: { id, phase: "queued" },
|
|
311
|
+
digest,
|
|
312
|
+
client,
|
|
313
|
+
generation: peer.facts.generation,
|
|
314
|
+
controller: new AbortController(),
|
|
315
|
+
committed: false,
|
|
316
|
+
promise: Promise.resolve(),
|
|
317
|
+
peers: new Set(),
|
|
318
|
+
};
|
|
319
|
+
if (cancelled.has(`${client}:${id}`))
|
|
320
|
+
job.controller.abort(new DOMException("Operation cancelled before dispatch", "AbortError"));
|
|
321
|
+
const execution = makeExecution(job);
|
|
322
|
+
job.promise = queue
|
|
323
|
+
.then(async () => {
|
|
324
|
+
execution.validate();
|
|
325
|
+
job.view.phase = "running";
|
|
326
|
+
const result = await execute(operation, payload, execution);
|
|
327
|
+
if (Buffer.byteLength(JSON.stringify(result ?? null)) > MAX_MESSAGE_BYTES / 2)
|
|
328
|
+
throw new Error("Operation result exceeds its byte limit; use bounded inspection.");
|
|
329
|
+
job.view.result = result;
|
|
330
|
+
job.view.phase = "done";
|
|
331
|
+
})
|
|
332
|
+
.catch((error) => {
|
|
333
|
+
job.view.phase = "failed";
|
|
334
|
+
job.view.error = remoteError(error);
|
|
335
|
+
})
|
|
336
|
+
.finally(() => {
|
|
337
|
+
for (const waiting of [...pending.values()])
|
|
338
|
+
if (waiting.callback.job === id)
|
|
339
|
+
waiting.reject(new Error("Operation finished."));
|
|
340
|
+
hooks.idle?.();
|
|
341
|
+
});
|
|
342
|
+
queue = job.promise;
|
|
343
|
+
jobs.set(id, job);
|
|
344
|
+
return job;
|
|
345
|
+
}
|
|
346
|
+
async function detach(id, retain = false, handoff) {
|
|
347
|
+
const peer = participants.get(id);
|
|
348
|
+
if (!peer) {
|
|
349
|
+
if (closedClients.size < 10_000)
|
|
350
|
+
closedClients.add(id);
|
|
351
|
+
return { cursor: sequence, callbacks: [], events: [] };
|
|
352
|
+
}
|
|
353
|
+
if (closedClients.has(id))
|
|
354
|
+
return poll(peer, 0);
|
|
355
|
+
peer.closing = true;
|
|
356
|
+
for (const waiting of [...pending.values()])
|
|
357
|
+
if (waiting.target === id && !waiting.callback.kind.startsWith("queue-"))
|
|
358
|
+
waiting.reject(new Error("Client detaching."));
|
|
359
|
+
await hooks.factsChanged?.();
|
|
360
|
+
const affected = [...jobs.values(), ...backgroundJobs].filter((job) => job.client === id || job.peers.has(id));
|
|
361
|
+
for (const job of affected)
|
|
362
|
+
if (!job.committed)
|
|
363
|
+
job.controller.abort(new DOMException("Client detached", "AbortError"));
|
|
364
|
+
await Promise.allSettled(affected.map((job) => job.promise));
|
|
365
|
+
peer.connected = false;
|
|
366
|
+
// Orderly exit remains protected by PID, but is not an ambiguous active participant.
|
|
367
|
+
peer.suspected = retain && handoff?.kind !== "exit";
|
|
368
|
+
peer.closing = false;
|
|
369
|
+
peer.handoff = handoff ?? (retain ? undefined : { kind: "exit" });
|
|
370
|
+
if (!retain || handoff?.kind === "exit")
|
|
371
|
+
closedClients.add(id);
|
|
372
|
+
await savePeers();
|
|
373
|
+
const result = poll(peer, 0);
|
|
374
|
+
hooks.idle?.();
|
|
375
|
+
return result;
|
|
376
|
+
}
|
|
377
|
+
async function handle(method, params, signal) {
|
|
378
|
+
const cleanup = ["answer", "poll", "cancel", "detach", "pause", "handoff", "stop"].includes(method);
|
|
379
|
+
if (!published && !cleanup)
|
|
380
|
+
throw new Error("Daemon readiness is not published.");
|
|
381
|
+
if (!cleanup)
|
|
382
|
+
assertOwner();
|
|
383
|
+
if (method === "hello")
|
|
384
|
+
return { version: PROTOCOL_VERSION, root: identity.root, instance: identity.instance, pid: identity.pid };
|
|
385
|
+
if (method === "attach") {
|
|
386
|
+
const attached = await admission.run(async () => {
|
|
387
|
+
assertOwner();
|
|
388
|
+
validateFacts(params);
|
|
389
|
+
if (closedClients.has(params.id))
|
|
390
|
+
throw new Error("Client was retired; attach a new client identity.");
|
|
391
|
+
if (closedClients.size >= 10_000)
|
|
392
|
+
throw new Error("Client retirement ledger is full; stop and restart the service.");
|
|
393
|
+
if (!processExists(params.pid))
|
|
394
|
+
throw new Error("Client process is not alive.");
|
|
395
|
+
for (const [id, peer] of participants)
|
|
396
|
+
if (!processExists(peer.facts.pid) && !peer.callbacks.size)
|
|
397
|
+
participants.delete(id);
|
|
398
|
+
if (!participants.has(params.id) && participants.size >= 64)
|
|
399
|
+
throw new Error("Daemon client capacity reached.");
|
|
400
|
+
const old = participants.get(params.id);
|
|
401
|
+
if (old &&
|
|
402
|
+
(old.facts.pid !== params.pid ||
|
|
403
|
+
((old.connected || old.suspected) && old.facts.generation !== params.generation)))
|
|
404
|
+
throw new Error("Client identity collision.");
|
|
405
|
+
participants.set(params.id, {
|
|
406
|
+
facts: structuredClone(params),
|
|
407
|
+
callbacks: old?.callbacks ?? new Map(),
|
|
408
|
+
events: old?.events ?? [],
|
|
409
|
+
connected: true,
|
|
410
|
+
closing: false,
|
|
411
|
+
suspected: false,
|
|
412
|
+
seen: Date.now(),
|
|
413
|
+
publishing: !old,
|
|
414
|
+
});
|
|
415
|
+
try {
|
|
416
|
+
await savePeers();
|
|
417
|
+
assertOwner();
|
|
418
|
+
}
|
|
419
|
+
catch (error) {
|
|
420
|
+
if (old)
|
|
421
|
+
participants.set(params.id, old);
|
|
422
|
+
else
|
|
423
|
+
participants.delete(params.id);
|
|
424
|
+
throw error;
|
|
425
|
+
}
|
|
426
|
+
const attached = requireParticipant(params.id, true);
|
|
427
|
+
attached.publishing = false;
|
|
428
|
+
// A shutdown-confirmed handoff keeps protection across SDK invalidation.
|
|
429
|
+
// Publish the replacement first, then retire only the matching closed scope.
|
|
430
|
+
for (const [id, peer] of participants) {
|
|
431
|
+
const next = peer.handoff;
|
|
432
|
+
if (id === params.id || peer.facts.pid !== params.pid || next?.kind !== "replace")
|
|
433
|
+
continue;
|
|
434
|
+
const matches = next.file !== undefined
|
|
435
|
+
? next.file === params.sessionFile
|
|
436
|
+
: next.sessionId !== undefined
|
|
437
|
+
? next.sessionId === params.sessionId
|
|
438
|
+
: params.sessionFile === undefined && next.cwd === params.cwd;
|
|
439
|
+
if (matches) {
|
|
440
|
+
participants.delete(id);
|
|
441
|
+
closedClients.add(id);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
await savePeers();
|
|
445
|
+
assertOwner();
|
|
446
|
+
return attached;
|
|
447
|
+
}, signal);
|
|
448
|
+
// Monitoring can await a queued reservation; never call it while admission is held.
|
|
449
|
+
await hooks.factsChanged?.();
|
|
450
|
+
assertOwner();
|
|
451
|
+
return poll(attached, 0);
|
|
452
|
+
}
|
|
453
|
+
if (!record(params))
|
|
454
|
+
throw new Error("Invalid request parameters.");
|
|
455
|
+
const contact = typeof params.client === "string" ? participants.get(params.client) : undefined;
|
|
456
|
+
if (contact)
|
|
457
|
+
contact.seen = Date.now();
|
|
458
|
+
if (method === "update" && record(params.facts) && typeof params.facts.id === "string") {
|
|
459
|
+
const peer = participants.get(params.facts.id);
|
|
460
|
+
if (peer)
|
|
461
|
+
peer.seen = Date.now();
|
|
462
|
+
}
|
|
463
|
+
if (method === "update") {
|
|
464
|
+
validateFacts(params.facts);
|
|
465
|
+
const peer = requireParticipant(params.facts.id);
|
|
466
|
+
const old = peer.facts;
|
|
467
|
+
if (old.pid !== params.facts.pid || old.generation !== params.facts.generation)
|
|
468
|
+
throw new Error("Client generation mismatch.");
|
|
469
|
+
peer.facts = structuredClone(params.facts);
|
|
470
|
+
const published = peer.facts;
|
|
471
|
+
try {
|
|
472
|
+
await savePeers();
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
if (peer.facts === published)
|
|
476
|
+
peer.facts = old;
|
|
477
|
+
throw error;
|
|
478
|
+
}
|
|
479
|
+
await hooks.factsChanged?.();
|
|
480
|
+
return poll(peer, 0);
|
|
481
|
+
}
|
|
482
|
+
if (["detach", "pause", "handoff"].includes(method)) {
|
|
483
|
+
if (!validId(params.client))
|
|
484
|
+
throw new Error("Invalid client.");
|
|
485
|
+
const peer = participants.get(params.client);
|
|
486
|
+
if (peer &&
|
|
487
|
+
((params.generation !== undefined && params.generation !== peer.facts.generation) ||
|
|
488
|
+
(params.pid !== undefined && params.pid !== peer.facts.pid)))
|
|
489
|
+
throw new Error("Stale client cleanup cannot detach a replacement generation.");
|
|
490
|
+
if (method === "handoff")
|
|
491
|
+
validateHandoff(params.handoff);
|
|
492
|
+
return detach(params.client, method !== "detach", method === "handoff" ? params.handoff : undefined);
|
|
493
|
+
}
|
|
494
|
+
if (method === "submit") {
|
|
495
|
+
if (!validId(params.id) ||
|
|
496
|
+
!validId(params.client) ||
|
|
497
|
+
typeof params.operation !== "string" ||
|
|
498
|
+
params.operation.length > 64)
|
|
499
|
+
throw new Error("Invalid operation envelope.");
|
|
500
|
+
return enqueue(params.id, params.client, params.operation, params.payload).view;
|
|
501
|
+
}
|
|
502
|
+
if (method === "poll") {
|
|
503
|
+
const peer = requireParticipant(params.client, true);
|
|
504
|
+
const job = typeof params.job === "string" ? jobs.get(params.job) : undefined;
|
|
505
|
+
if (params.job !== undefined && !job)
|
|
506
|
+
throw new Error("Operation is unknown or its result expired; reconcile journals instead of replaying.");
|
|
507
|
+
if (job && job.client !== params.client)
|
|
508
|
+
throw new Error("Operation belongs to another client.");
|
|
509
|
+
return poll(peer, params.cursor, job);
|
|
510
|
+
}
|
|
511
|
+
if (method === "review-page") {
|
|
512
|
+
requireParticipant(params.client);
|
|
513
|
+
const waiting = typeof params.id === "string" ? pending.get(params.id) : undefined;
|
|
514
|
+
if (!waiting?.review ||
|
|
515
|
+
waiting.target !== params.client ||
|
|
516
|
+
!Number.isSafeInteger(params.index) ||
|
|
517
|
+
Number(params.index) < 0 ||
|
|
518
|
+
Number(params.index) >= Math.ceil(waiting.review.length / REVIEW_PAGE_CHARS))
|
|
519
|
+
throw new Error("Stale, foreign, or invalid review page.");
|
|
520
|
+
const start = Number(params.index) * REVIEW_PAGE_CHARS;
|
|
521
|
+
return { id: params.id, index: params.index, content: waiting.review.slice(start, start + REVIEW_PAGE_CHARS) };
|
|
522
|
+
}
|
|
523
|
+
if (method === "answer") {
|
|
524
|
+
requireParticipant(params.client, true);
|
|
525
|
+
const waiting = typeof params.id === "string" ? pending.get(params.id) : undefined;
|
|
526
|
+
if (!waiting || waiting.target !== params.client)
|
|
527
|
+
throw new Error("Stale or foreign callback response.");
|
|
528
|
+
if (typeof params.error === "string")
|
|
529
|
+
waiting.reject(new Error(params.error.slice(0, 1024)));
|
|
530
|
+
else
|
|
531
|
+
waiting.resolve(params.value);
|
|
532
|
+
return {};
|
|
533
|
+
}
|
|
534
|
+
if (method === "cancel") {
|
|
535
|
+
requireParticipant(params.client, true);
|
|
536
|
+
if (!validId(params.id))
|
|
537
|
+
throw new Error("Invalid operation identity.");
|
|
538
|
+
const job = jobs.get(params.id);
|
|
539
|
+
if (!job) {
|
|
540
|
+
if (cancelled.size >= 128)
|
|
541
|
+
throw new Error("Cancellation capacity reached.");
|
|
542
|
+
cancelled.add(`${params.client}:${params.id}`);
|
|
543
|
+
return { cancelled: true };
|
|
544
|
+
}
|
|
545
|
+
if (job.client !== params.client)
|
|
546
|
+
throw new Error("Operation belongs to another client.");
|
|
547
|
+
if (!job.committed)
|
|
548
|
+
job.controller.abort(new DOMException("Operation cancelled", "AbortError"));
|
|
549
|
+
await job.promise;
|
|
550
|
+
return job.view;
|
|
551
|
+
}
|
|
552
|
+
if (method === "stop") {
|
|
553
|
+
setImmediate(() => {
|
|
554
|
+
void close().catch(() => { });
|
|
555
|
+
});
|
|
556
|
+
return { stopping: true };
|
|
557
|
+
}
|
|
558
|
+
throw new Error("Unknown daemon method.");
|
|
559
|
+
}
|
|
560
|
+
const respond = (response, status, value) => {
|
|
561
|
+
let encoded = JSON.stringify(value);
|
|
562
|
+
if (Buffer.byteLength(encoded) > MAX_MESSAGE_BYTES) {
|
|
563
|
+
status = 413;
|
|
564
|
+
encoded = JSON.stringify({ error: { name: "Error", message: "Daemon response exceeds its byte limit." } });
|
|
565
|
+
}
|
|
566
|
+
response.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
567
|
+
response.end(encoded);
|
|
568
|
+
};
|
|
569
|
+
const server = createServer(async (request, response) => {
|
|
570
|
+
let admissionController;
|
|
571
|
+
const disconnect = () => admissionController?.abort(new DOMException("Client disconnected", "AbortError"));
|
|
572
|
+
try {
|
|
573
|
+
if (request.method !== "POST" || request.url !== "/v1") {
|
|
574
|
+
respond(response, 404, { error: { message: "Not found." } });
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
const body = await readJsonBody(request);
|
|
578
|
+
if (!record(body) ||
|
|
579
|
+
body.version !== 1 ||
|
|
580
|
+
body.root !== identity.root ||
|
|
581
|
+
body.instance !== identity.instance ||
|
|
582
|
+
typeof body.token !== "string" ||
|
|
583
|
+
!/^[a-f0-9]{64}$/u.test(body.token) ||
|
|
584
|
+
!timingSafeEqual(Buffer.from(body.token), Buffer.from(identity.token)) ||
|
|
585
|
+
typeof body.method !== "string") {
|
|
586
|
+
respond(response, 403, { error: { name: "Error", message: "Invalid daemon identity or protocol." } });
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
if (body.method === "attach") {
|
|
590
|
+
admissionController = new AbortController();
|
|
591
|
+
response.once("close", disconnect);
|
|
592
|
+
}
|
|
593
|
+
respond(response, 200, { result: await handle(body.method, body.params, admissionController?.signal) });
|
|
594
|
+
}
|
|
595
|
+
catch (error) {
|
|
596
|
+
if (!response.destroyed)
|
|
597
|
+
respond(response, 400, { error: remoteError(error) });
|
|
598
|
+
}
|
|
599
|
+
finally {
|
|
600
|
+
response.removeListener("close", disconnect);
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
server.requestTimeout = 30_000;
|
|
604
|
+
server.headersTimeout = 10_000;
|
|
605
|
+
const endpoint = endpointOwner(server, paths);
|
|
606
|
+
try {
|
|
607
|
+
assertOwner();
|
|
608
|
+
await endpoint.listen();
|
|
609
|
+
assertOwner();
|
|
610
|
+
await publishIdentity(paths, identity);
|
|
611
|
+
assertOwner();
|
|
612
|
+
published = true;
|
|
613
|
+
}
|
|
614
|
+
catch (error) {
|
|
615
|
+
closed = true;
|
|
616
|
+
return withCleanup(async () => {
|
|
617
|
+
throw error;
|
|
618
|
+
}, () => withCleanup(() => endpoint.close(), release));
|
|
619
|
+
}
|
|
620
|
+
async function expireClients() {
|
|
621
|
+
let changed = false;
|
|
622
|
+
for (const [id, peer] of participants) {
|
|
623
|
+
const exited = !processExists(peer.facts.pid);
|
|
624
|
+
if (!exited && (!peer.connected || Date.now() - peer.seen <= 5_000))
|
|
625
|
+
continue;
|
|
626
|
+
peer.connected = false;
|
|
627
|
+
peer.suspected = !exited;
|
|
628
|
+
changed = true;
|
|
629
|
+
for (const job of [...jobs.values(), ...backgroundJobs])
|
|
630
|
+
if (!job.committed && (job.client === id || job.peers.has(id)))
|
|
631
|
+
job.controller.abort(new DOMException(exited ? "Client exited" : "Client contact expired", "AbortError"));
|
|
632
|
+
if (exited) {
|
|
633
|
+
for (const waiting of [...pending.values()])
|
|
634
|
+
if (waiting.target === id) {
|
|
635
|
+
if (waiting.callback.kind === "queue-release")
|
|
636
|
+
waiting.resolve(true);
|
|
637
|
+
else
|
|
638
|
+
waiting.reject(new Error("Client process exited."));
|
|
639
|
+
}
|
|
640
|
+
participants.delete(id);
|
|
641
|
+
}
|
|
642
|
+
// Contact expiry alone retains the live session and its uncertain grants.
|
|
643
|
+
}
|
|
644
|
+
if (changed) {
|
|
645
|
+
await savePeers();
|
|
646
|
+
await hooks.factsChanged?.();
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
heartbeat = setInterval(() => {
|
|
650
|
+
void expireClients().catch(() => { });
|
|
651
|
+
}, 1_000);
|
|
652
|
+
heartbeat.unref();
|
|
653
|
+
async function close() {
|
|
654
|
+
if (closing)
|
|
655
|
+
return closing;
|
|
656
|
+
closing = (async () => {
|
|
657
|
+
closed = true;
|
|
658
|
+
clearInterval(heartbeat);
|
|
659
|
+
for (const waiting of [...pending.values()])
|
|
660
|
+
if (!waiting.callback.kind.startsWith("queue-"))
|
|
661
|
+
waiting.reject(new Error("Daemon stopping."));
|
|
662
|
+
for (const job of [...jobs.values(), ...backgroundJobs])
|
|
663
|
+
if (!job.committed)
|
|
664
|
+
job.controller.abort(new DOMException("Daemon stopping", "AbortError"));
|
|
665
|
+
let closeError;
|
|
666
|
+
try {
|
|
667
|
+
await hooks.close?.();
|
|
668
|
+
}
|
|
669
|
+
catch (error) {
|
|
670
|
+
closeError = error;
|
|
671
|
+
}
|
|
672
|
+
await Promise.allSettled([...jobs.values()].map((job) => job.promise));
|
|
673
|
+
await admission.run(async () => { });
|
|
674
|
+
for (const waiting of [...pending.values()])
|
|
675
|
+
waiting.reject(new Error("Daemon stopping."));
|
|
676
|
+
await endpoint.close();
|
|
677
|
+
if (await known())
|
|
678
|
+
await fs.rm(paths.identity, { force: true });
|
|
679
|
+
await release();
|
|
680
|
+
if (closeError)
|
|
681
|
+
throw closeError;
|
|
682
|
+
})().catch((error) => {
|
|
683
|
+
closing = undefined;
|
|
684
|
+
throw error;
|
|
685
|
+
});
|
|
686
|
+
return closing;
|
|
687
|
+
}
|
|
688
|
+
function backgroundExecution(signal) {
|
|
689
|
+
assertOwner();
|
|
690
|
+
const job = {
|
|
691
|
+
view: { id: randomUUID(), phase: "running" },
|
|
692
|
+
digest: "",
|
|
693
|
+
controller: new AbortController(),
|
|
694
|
+
committed: false,
|
|
695
|
+
promise: Promise.resolve(),
|
|
696
|
+
peers: new Set(),
|
|
697
|
+
};
|
|
698
|
+
const abort = () => {
|
|
699
|
+
job.controller.abort(signal.reason);
|
|
700
|
+
backgroundJobs.delete(job);
|
|
701
|
+
};
|
|
702
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
703
|
+
backgroundJobs.add(job);
|
|
704
|
+
if (signal.aborted)
|
|
705
|
+
abort();
|
|
706
|
+
return makeExecution(job);
|
|
707
|
+
}
|
|
708
|
+
return {
|
|
709
|
+
identity,
|
|
710
|
+
paths,
|
|
711
|
+
close,
|
|
712
|
+
backgroundExecution,
|
|
713
|
+
get retainedEndpoint() {
|
|
714
|
+
return endpoint.retainedDirectory;
|
|
715
|
+
},
|
|
716
|
+
participants: participantFacts,
|
|
717
|
+
liveClients: liveClientFacts,
|
|
718
|
+
expireClients,
|
|
719
|
+
isIdle: () => !closed && [...jobs.values()].every((job) => job.view.phase !== "queued" && job.view.phase !== "running"),
|
|
720
|
+
get closed() {
|
|
721
|
+
return closed;
|
|
722
|
+
},
|
|
723
|
+
};
|
|
724
|
+
}
|