@narumitw/pi-sync-daemon 0.2.0 → 0.4.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 +19 -0
- package/README.md +4 -2
- package/dist/cli.js +7 -8
- package/dist/client.d.ts +24 -2
- package/dist/client.js +235 -31
- package/dist/engine-service.d.ts +3 -0
- package/dist/engine-service.js +8 -1
- package/dist/idle-exit.d.ts +17 -0
- package/dist/idle-exit.js +77 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/monitor.d.ts +3 -0
- package/dist/monitor.js +35 -8
- package/dist/protocol.d.ts +19 -0
- package/dist/protocol.js +14 -0
- package/dist/server.d.ts +6 -0
- package/dist/server.js +235 -16
- package/docs/architecture.md +51 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @narumitw/pi-sync-daemon
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 223b0ba: Restore a live Pi session after its heartbeat expires without reloading Pi. The
|
|
8
|
+
daemon distinguishes heartbeat expiry from deliberate disconnection and keeps
|
|
9
|
+
file-queue and session protection in place. Pi Sync reconnects to the same owner
|
|
10
|
+
without resubmitting interrupted operations, and checks participation before
|
|
11
|
+
reporting that it is connected.
|
|
12
|
+
|
|
13
|
+
## 0.3.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- ea5b9f1: Exit the daemon after a 30-second grace period when no registered client PID remains and no valid active-setup after-exit grant applies. Keep live, passive, disconnected, and retired clients protected; preserve paused authorization barriers and drain committed work before releasing ownership. No new setting or final synchronization is added.
|
|
18
|
+
|
|
19
|
+
Let Pi Sync retry an authenticated idle-closing owner after confirmed process exit, with bounded, cancellable startup and no replay of submitted operations. Add the lightweight `waitForDaemonExit()` client helper. Let a later Pi Sync command reconnect after a cancelled unpublished attach by draining the old connection and using a fresh client ID and generation; keep failed cleanup blocked and never replay the cancelled operation. Publish and verify the daemon dependency before releasing Pi Sync; publication and real-data cutover still require separate approval.
|
|
20
|
+
- 5e251a8: Rename the daemon package to `@narumitw/pi-sync-daemon` and its executable to `pi-sync-daemon`, and update Pi Sync to use the renamed dependency. The new package does not provide the old `sync-daemon` executable alias. Stop an existing daemon before replacing its package, then use the new executable after installation. Preserve IPC identity, settings, state, recovery evidence, and authorization digests. Publish and verify the renamed dependency before releasing Pi Sync; publication and real-data cutover still require separate approval.
|
|
21
|
+
|
|
3
22
|
## 0.2.0
|
|
4
23
|
|
|
5
24
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -44,13 +44,13 @@ node packages/pi-sync-daemon/dist/cli.js stop --root /tmp/my-pi-sync-daemon-smok
|
|
|
44
44
|
|
|
45
45
|
`pi-sync-daemon <start|status|stop|restart|serve> --root <agent-directory>` uses an explicit root. `status` and `stop` never launch an absent service. `restart` drains the compatible owner before replacement; an incompatible or unreachable live owner fails closed. `serve` is the internal foreground launch target, not an OS registration command.
|
|
46
46
|
|
|
47
|
-
Pi starts the service only after configured interactive synchronization is needed or an explicit setup/command authorizes it. Closing Pi detaches that client
|
|
47
|
+
Pi starts the service only after configured interactive synchronization is needed or an explicit setup/command authorizes it. Closing Pi detaches that client; the daemon owns the shared lifetime decision. After no registered live client PID remains for that canonical root, a fixed 30-second grace period starts unless a valid after-exit grant keeps the service running. Explicit CLI `start` without clients follows the same rule. A client arriving before shutdown becomes final cancels automatic exit. `/new`, `/reload`, fork, and resume retain protection while their Pi process is alive. Use `/sync daemon` for status, reviewed old-process handover, and setup-bound unattended authorization.
|
|
48
48
|
|
|
49
49
|
## ⚙️ Settings
|
|
50
50
|
|
|
51
51
|
Existing `pi-sync.json`, canonical `pi-sync/`, and legacy `.pisync/` remain in the selected agent directory. There is no second backend or credential configuration format. The daemon is the authoritative Pi Sync settings writer; stale reviews must reopen rather than overwrite a newer document.
|
|
52
52
|
|
|
53
|
-
Automatic, Autonomous, and Continuous defaults remain unchanged. Old permission for work while Pi is open does not permit work after the last client exits. `/sync daemon allow-after-exit` reviews that extra permission for the current setup and selected independently reproducible provider/model; `/sync daemon revoke-after-exit` revokes it. Setup changes invalidate the saved digest. Changes to an interactive client’s model, working directory, or session-directory binding revoke older unattended grants, including across restart. Print/JSON never launch a service; passive attachment to an existing service protects their sessions and pauses automatic work.
|
|
53
|
+
Automatic, Autonomous, and Continuous defaults remain unchanged. Old permission for work while Pi is open does not permit work after the last client exits. `/sync daemon allow-after-exit` reviews that extra permission for the current setup and selected independently reproducible provider/model; `/sync daemon revoke-after-exit` revokes it. Setup changes invalidate the saved digest. Changes to an interactive client’s model, working directory, or session-directory binding revoke older unattended grants, including across restart. Print/JSON never launch a service; passive attachment to an existing service protects their sessions and pauses automatic work. Registered live PIDs keep the service alive, including passive, disconnected, publishing, and orderly retired clients. A valid explicit after-exit grant for the active setup keeps service lifetime under the existing fingerprint and binding rules; it does not expand transfer or model permission. Temporary provider or backend unavailability does not itself revoke that grant. Lifetime checks do not call a model, contact a provider or storage, or execute credential commands. There is no new setting, environment variable, or keep-alive flag.
|
|
54
54
|
|
|
55
55
|
## 🔒 Security and privacy
|
|
56
56
|
|
|
@@ -68,6 +68,8 @@ Close or upgrade every old Pi process before reviewed handover. An absent operat
|
|
|
68
68
|
|
|
69
69
|
## Recovery and development
|
|
70
70
|
|
|
71
|
+
Automatic exit first stops new automatic work, cancels cancellable work, and drains writes, queue-release acknowledgements, persistence, and owned callbacks before releasing ownership. It adds no final sync or model request. Uncertain consent publication, failed revocation, or cleanup failure keeps the owner paused with evidence retained; automatic restart must not restore an older grant. Repair persistence and use the existing revocation/repair path before explicit restart. The next eligible interactive client or explicit command can restart through singleton startup only after the old owner's exit is proven; print/JSON never launch a replacement.
|
|
72
|
+
|
|
71
73
|
Stop the service before package updates, local rebuilds, or rollback, verify owner exit, and preserve pending journals and backups. A compatible connection does not upgrade a running implementation; restart explicitly after installation. Do not downgrade over pending/newer recovery evidence or restore old settings over newer bytes. Expired or old-instance operation IDs must reconcile existing journals rather than replay a possible commit. The bounded per-instance result ledger requires an explicit drained restart when full.
|
|
72
74
|
|
|
73
75
|
CLI `status` reports the private lifecycle-log path. It retains at most 8 KiB of timestamps and lifecycle phases, not exception text, credentials, model output, or sync content; older entries roll over. It is diagnostic evidence, not a recovery journal. Child stdio is detached and discarded.
|
package/dist/cli.js
CHANGED
|
@@ -35,14 +35,13 @@ export async function main(args) {
|
|
|
35
35
|
try {
|
|
36
36
|
server = await startServer(paths.root, service.execute, {
|
|
37
37
|
...service.hooks,
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
38
|
+
stopped: () => {
|
|
39
|
+
note("drained");
|
|
40
|
+
log?.close();
|
|
41
|
+
},
|
|
42
|
+
failure: () => {
|
|
43
|
+
service.hooks.failure();
|
|
44
|
+
note("failed");
|
|
46
45
|
},
|
|
47
46
|
});
|
|
48
47
|
// Only the published owner may open or modify its shared diagnostic file.
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type RuntimePaths } from "./identity.js";
|
|
2
|
-
import { type Callback, type ClientEvent, type ClientFacts, type ClientHandoff, type Identity, type RemoteError } from "./protocol.js";
|
|
2
|
+
import { type Callback, type ClientEvent, type ClientFacts, type ClientHandoff, type ClientContact as ContactState, type Identity, type RemoteError } from "./protocol.js";
|
|
3
3
|
export declare class DaemonError extends Error {
|
|
4
4
|
readonly remote: RemoteError;
|
|
5
5
|
constructor(remote: RemoteError);
|
|
@@ -10,6 +10,8 @@ export declare function ensureDaemon(root: string, signal?: AbortSignal): Promis
|
|
|
10
10
|
paths: import("./identity.js").DaemonPaths;
|
|
11
11
|
identity: Identity;
|
|
12
12
|
}>;
|
|
13
|
+
/** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
|
|
14
|
+
export declare function waitForDaemonExit(identity: Identity, signal?: AbortSignal): Promise<void>;
|
|
13
15
|
/** Inspect an existing compatible owner without starting one. */
|
|
14
16
|
export declare function findDaemon(root: string): Promise<{
|
|
15
17
|
paths: import("./identity.js").DaemonPaths;
|
|
@@ -21,6 +23,8 @@ export interface ConnectionOptions {
|
|
|
21
23
|
callback(callback: Callback, signal: AbortSignal): Promise<unknown>;
|
|
22
24
|
event?(event: ClientEvent): void;
|
|
23
25
|
error?(error: unknown): void;
|
|
26
|
+
/** Each current background observation after admission, including repeated states. */
|
|
27
|
+
contact?(state: ContactState): void;
|
|
24
28
|
}
|
|
25
29
|
export declare class DaemonConnection {
|
|
26
30
|
readonly paths: RuntimePaths;
|
|
@@ -34,17 +38,35 @@ export declare class DaemonConnection {
|
|
|
34
38
|
private callbackTasks;
|
|
35
39
|
private updates;
|
|
36
40
|
private attached;
|
|
41
|
+
private admitting;
|
|
42
|
+
private observedContact;
|
|
43
|
+
private contactRevision;
|
|
44
|
+
private lifecycleRevision;
|
|
45
|
+
private resuming;
|
|
46
|
+
private resumeUncertain;
|
|
47
|
+
private pendingJobs;
|
|
37
48
|
private uncertain;
|
|
38
49
|
private reportedError;
|
|
39
50
|
private commits;
|
|
40
51
|
private completedCallbacks;
|
|
52
|
+
private pausing;
|
|
41
53
|
private disposing;
|
|
42
54
|
private polling;
|
|
43
55
|
private closed;
|
|
44
56
|
constructor(paths: RuntimePaths, identity: Identity, facts: ClientFacts, options: ConnectionOptions);
|
|
45
|
-
|
|
57
|
+
/** Latest owner observation, or undefined if contact is unsupported or not observed. */
|
|
58
|
+
get contactState(): ContactState | undefined;
|
|
59
|
+
/** An uncertain attempt must not be retried or turned into a new attach. */
|
|
60
|
+
get contactResumeState(): "idle" | "running" | "uncertain";
|
|
61
|
+
/** Original submitted jobs must finish (or be reconciled) before repairing contact. */
|
|
62
|
+
get hasPendingWork(): boolean;
|
|
63
|
+
attach(signal?: AbortSignal): Promise<this>;
|
|
46
64
|
update(facts: ClientFacts): Promise<void>;
|
|
65
|
+
/** Resume this participant without replacing its callbacks, jobs, or polling. */
|
|
66
|
+
resumeContact(facts: ClientFacts, signal?: AbortSignal): Promise<void>;
|
|
67
|
+
private sameClient;
|
|
47
68
|
run(operation: string, payload: unknown, signal?: AbortSignal, onCommit?: () => void): Promise<unknown>;
|
|
69
|
+
private publishContact;
|
|
48
70
|
private consume;
|
|
49
71
|
private performCallback;
|
|
50
72
|
private wait;
|
package/dist/client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { request as httpRequest } from "node:http";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
5
6
|
import lockfile from "proper-lockfile";
|
|
6
7
|
import { daemonPaths, privateDirectory, processExists, readIdentity, readJsonBody, runtimePaths, } from "./identity.js";
|
|
@@ -46,15 +47,15 @@ export async function requestDaemon(paths, identity, method, params, signal) {
|
|
|
46
47
|
})
|
|
47
48
|
.catch(reject);
|
|
48
49
|
});
|
|
49
|
-
//
|
|
50
|
-
// cancels that wait; an idle timeout must not let
|
|
51
|
-
request.setTimeout(method === "attach" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
|
|
50
|
+
// Admission can wait behind a complete apply. The request owner's signal
|
|
51
|
+
// cancels that wait; an idle timeout must not let admission escape the fence.
|
|
52
|
+
request.setTimeout(method === "attach" || method === "resume-contact" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
|
|
52
53
|
request.once("error", reject);
|
|
53
54
|
request.end(body);
|
|
54
55
|
});
|
|
55
56
|
}
|
|
56
|
-
async function hello(paths, identity) {
|
|
57
|
-
const value = await requestDaemon(paths, identity, "hello", {});
|
|
57
|
+
async function hello(paths, identity, signal) {
|
|
58
|
+
const value = await requestDaemon(paths, identity, "hello", {}, signal);
|
|
58
59
|
if (!record(value) ||
|
|
59
60
|
value.version !== 1 ||
|
|
60
61
|
value.root !== paths.root ||
|
|
@@ -77,18 +78,27 @@ export async function ensureDaemon(root, signal) {
|
|
|
77
78
|
});
|
|
78
79
|
try {
|
|
79
80
|
signal?.throwIfAborted();
|
|
80
|
-
|
|
81
|
-
|
|
81
|
+
let waited = false;
|
|
82
|
+
for (;;) {
|
|
83
|
+
const existing = await readIdentity(paths);
|
|
84
|
+
if (!existing)
|
|
85
|
+
break;
|
|
82
86
|
try {
|
|
83
|
-
await hello(paths, existing);
|
|
87
|
+
await hello(paths, existing, signal);
|
|
84
88
|
signal?.throwIfAborted();
|
|
85
89
|
return { paths: daemonPaths(paths, existing.instance), identity: existing };
|
|
86
90
|
}
|
|
87
91
|
catch (error) {
|
|
88
92
|
if (signal?.aborted)
|
|
89
93
|
throw signal.reason;
|
|
94
|
+
if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
|
|
95
|
+
waited = true;
|
|
96
|
+
await waitForDaemonExit(existing, signal);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
90
99
|
if (processExists(existing.pid))
|
|
91
100
|
throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
|
|
101
|
+
break;
|
|
92
102
|
}
|
|
93
103
|
}
|
|
94
104
|
const executable = process.versions.bun ? "node" : process.execPath;
|
|
@@ -142,7 +152,7 @@ export async function ensureDaemon(root, signal) {
|
|
|
142
152
|
child.unref();
|
|
143
153
|
});
|
|
144
154
|
// Never kill a published shared daemon on caller cancellation.
|
|
145
|
-
await hello(paths, ready);
|
|
155
|
+
await hello(paths, ready, signal);
|
|
146
156
|
signal?.throwIfAborted();
|
|
147
157
|
return { paths: daemonPaths(paths, ready.instance), identity: ready };
|
|
148
158
|
}
|
|
@@ -150,6 +160,17 @@ export async function ensureDaemon(root, signal) {
|
|
|
150
160
|
await release();
|
|
151
161
|
}
|
|
152
162
|
}
|
|
163
|
+
/** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
|
|
164
|
+
export async function waitForDaemonExit(identity, signal) {
|
|
165
|
+
const deadline = Date.now() + 30_000;
|
|
166
|
+
signal?.throwIfAborted();
|
|
167
|
+
while (processExists(identity.pid)) {
|
|
168
|
+
if (Date.now() >= deadline)
|
|
169
|
+
throw new Error("Closing daemon is still alive; replacement was not attempted.");
|
|
170
|
+
await delay(25, undefined, { signal });
|
|
171
|
+
}
|
|
172
|
+
signal?.throwIfAborted();
|
|
173
|
+
}
|
|
153
174
|
/** Inspect an existing compatible owner without starting one. */
|
|
154
175
|
export async function findDaemon(root) {
|
|
155
176
|
let paths;
|
|
@@ -164,7 +185,14 @@ export async function findDaemon(root) {
|
|
|
164
185
|
const identity = await readIdentity(paths);
|
|
165
186
|
if (!identity || !processExists(identity.pid))
|
|
166
187
|
return undefined;
|
|
167
|
-
|
|
188
|
+
try {
|
|
189
|
+
await hello(paths, identity);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
|
|
193
|
+
return undefined;
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
168
196
|
return { paths: daemonPaths(paths, identity.instance), identity };
|
|
169
197
|
}
|
|
170
198
|
/** Gracefully stop an existing compatible owner without creating a new service. */
|
|
@@ -198,10 +226,18 @@ export class DaemonConnection {
|
|
|
198
226
|
callbackTasks = new Set();
|
|
199
227
|
updates = Promise.resolve();
|
|
200
228
|
attached = false;
|
|
229
|
+
admitting = false;
|
|
230
|
+
observedContact;
|
|
231
|
+
contactRevision = 0;
|
|
232
|
+
lifecycleRevision = 0;
|
|
233
|
+
resuming;
|
|
234
|
+
resumeUncertain = false;
|
|
235
|
+
pendingJobs = 0;
|
|
201
236
|
uncertain = false;
|
|
202
237
|
reportedError = false;
|
|
203
238
|
commits = new Map();
|
|
204
239
|
completedCallbacks = new Set();
|
|
240
|
+
pausing;
|
|
205
241
|
disposing;
|
|
206
242
|
polling;
|
|
207
243
|
closed = false;
|
|
@@ -211,42 +247,171 @@ export class DaemonConnection {
|
|
|
211
247
|
this.facts = facts;
|
|
212
248
|
this.options = options;
|
|
213
249
|
}
|
|
214
|
-
|
|
215
|
-
|
|
250
|
+
/** Latest owner observation, or undefined if contact is unsupported or not observed. */
|
|
251
|
+
get contactState() {
|
|
252
|
+
return this.observedContact;
|
|
253
|
+
}
|
|
254
|
+
/** An uncertain attempt must not be retried or turned into a new attach. */
|
|
255
|
+
get contactResumeState() {
|
|
256
|
+
return this.resumeUncertain ? "uncertain" : this.resuming ? "running" : "idle";
|
|
257
|
+
}
|
|
258
|
+
/** Original submitted jobs must finish (or be reconciled) before repairing contact. */
|
|
259
|
+
get hasPendingWork() {
|
|
260
|
+
return this.pendingJobs > 0 || this.uncertain;
|
|
261
|
+
}
|
|
262
|
+
async attach(signal) {
|
|
263
|
+
if (this.closed ||
|
|
264
|
+
this.hasPendingWork ||
|
|
265
|
+
this.contactResumeState !== "idle" ||
|
|
266
|
+
this.admitting ||
|
|
267
|
+
this.pausing ||
|
|
268
|
+
this.disposing)
|
|
216
269
|
throw new Error("Daemon client is unavailable; reconnect after draining work.");
|
|
217
|
-
|
|
270
|
+
this.admitting = true;
|
|
271
|
+
this.lifecycleRevision++;
|
|
272
|
+
this.contactRevision++;
|
|
273
|
+
const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal);
|
|
218
274
|
// Poll during attach: stopping a previous controller may need release answers
|
|
219
275
|
// from this reattached participant before the attach response can complete.
|
|
220
276
|
this.polling ??= this.poll();
|
|
277
|
+
let admitted = false;
|
|
221
278
|
try {
|
|
222
279
|
const result = await request;
|
|
223
|
-
|
|
280
|
+
admitted = true;
|
|
281
|
+
this.publishContact(this.consume(result));
|
|
224
282
|
this.attached = true;
|
|
225
283
|
return this;
|
|
226
284
|
}
|
|
227
285
|
catch (error) {
|
|
228
286
|
return withCleanup(async () => {
|
|
229
287
|
throw error;
|
|
230
|
-
}, () =>
|
|
288
|
+
}, async () => {
|
|
289
|
+
try {
|
|
290
|
+
await this.dispose();
|
|
291
|
+
}
|
|
292
|
+
catch (cleanupError) {
|
|
293
|
+
if (!admitted &&
|
|
294
|
+
!this.attached &&
|
|
295
|
+
this.closed &&
|
|
296
|
+
!this.callbacks.size &&
|
|
297
|
+
!this.callbackTasks.size &&
|
|
298
|
+
!this.completedCallbacks.size &&
|
|
299
|
+
error instanceof DaemonError &&
|
|
300
|
+
error.remote.name === "DaemonStoppingError") {
|
|
301
|
+
// The fenced first attach owned no grants, and local tasks have drained.
|
|
302
|
+
// Keep its retry marker even if the owner closes the cleanup transport.
|
|
303
|
+
error.cause = cleanupError;
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
throw cleanupError;
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
this.admitting = false;
|
|
231
312
|
}
|
|
232
313
|
}
|
|
233
|
-
update(facts) {
|
|
314
|
+
async update(facts) {
|
|
315
|
+
const lifecycle = this.lifecycleRevision;
|
|
316
|
+
if (this.admitting || this.pausing || this.disposing)
|
|
317
|
+
throw new Error("Daemon client is changing; wait before updating facts.");
|
|
234
318
|
const update = this.updates.then(async () => {
|
|
235
|
-
if (this.closed || this.uncertain)
|
|
319
|
+
if (this.closed || this.uncertain || this.resumeUncertain || lifecycle !== this.lifecycleRevision)
|
|
236
320
|
throw new Error("Daemon client is unavailable; reconnect after draining work.");
|
|
237
|
-
const
|
|
321
|
+
const revision = this.contactRevision;
|
|
322
|
+
let result;
|
|
323
|
+
try {
|
|
324
|
+
result = await requestDaemon(this.paths, this.identity, "update", { facts }, this.controller.signal);
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
if (this.attached &&
|
|
328
|
+
revision === this.contactRevision &&
|
|
329
|
+
this.sameClient(facts) &&
|
|
330
|
+
error instanceof DaemonError &&
|
|
331
|
+
error.remote.name === "ClientContactExpiredError")
|
|
332
|
+
this.publishContact("expired");
|
|
333
|
+
throw error;
|
|
334
|
+
}
|
|
238
335
|
if (this.closed)
|
|
239
336
|
throw new Error("Daemon client closed during update.");
|
|
337
|
+
if (revision !== this.contactRevision)
|
|
338
|
+
throw new Error("Daemon client changed during update.");
|
|
339
|
+
const contact = this.consume(result);
|
|
340
|
+
if (revision !== this.contactRevision)
|
|
341
|
+
throw new Error("Daemon client changed during update.");
|
|
240
342
|
Object.assign(this.facts, facts);
|
|
241
|
-
this.
|
|
343
|
+
this.publishContact(contact);
|
|
242
344
|
});
|
|
243
345
|
this.updates = update.catch(() => { });
|
|
244
346
|
return update;
|
|
245
347
|
}
|
|
348
|
+
/** Resume this participant without replacing its callbacks, jobs, or polling. */
|
|
349
|
+
async resumeContact(facts, signal) {
|
|
350
|
+
signal?.throwIfAborted();
|
|
351
|
+
if (this.contactResumeState !== "idle")
|
|
352
|
+
throw new Error("Daemon contact resume is running or uncertain.");
|
|
353
|
+
const check = () => {
|
|
354
|
+
if (!this.attached || this.admitting || this.pausing || this.disposing || this.closed || this.hasPendingWork)
|
|
355
|
+
throw new Error("Daemon client is unavailable; reconnect after draining work.");
|
|
356
|
+
if (!this.sameClient(facts) || this.contactState !== "expired")
|
|
357
|
+
throw new Error("No confirmed contact expiry for this daemon client.");
|
|
358
|
+
};
|
|
359
|
+
facts = structuredClone(facts);
|
|
360
|
+
check();
|
|
361
|
+
const resume = new AbortController();
|
|
362
|
+
this.resuming = resume;
|
|
363
|
+
const ownedSignal = signal ? AbortSignal.any([signal, resume.signal]) : resume.signal;
|
|
364
|
+
let sent = false;
|
|
365
|
+
const attempt = this.updates.then(async () => {
|
|
366
|
+
ownedSignal.throwIfAborted();
|
|
367
|
+
check();
|
|
368
|
+
sent = true;
|
|
369
|
+
const reply = await requestDaemon(this.paths, this.identity, "resume-contact", facts, ownedSignal);
|
|
370
|
+
ownedSignal.throwIfAborted();
|
|
371
|
+
const contact = this.consume(reply);
|
|
372
|
+
ownedSignal.throwIfAborted();
|
|
373
|
+
if (contact !== "active")
|
|
374
|
+
throw new Error("Daemon did not confirm resumed contact.");
|
|
375
|
+
Object.assign(this.facts, facts);
|
|
376
|
+
this.publishContact(contact);
|
|
377
|
+
});
|
|
378
|
+
this.updates = attempt.catch(() => { });
|
|
379
|
+
// Reject a queued repair on cancellation even if the earlier update has not finished.
|
|
380
|
+
const cancellation = Promise.withResolvers();
|
|
381
|
+
const abort = () => cancellation.reject(ownedSignal.reason);
|
|
382
|
+
ownedSignal.addEventListener("abort", abort, { once: true });
|
|
383
|
+
try {
|
|
384
|
+
await Promise.race([attempt, cancellation.promise]);
|
|
385
|
+
}
|
|
386
|
+
catch (error) {
|
|
387
|
+
if (sent) {
|
|
388
|
+
// The protocol does not distinguish definite pre-publication refusal from a lost acknowledgement.
|
|
389
|
+
this.resumeUncertain = true;
|
|
390
|
+
for (const { controller, kind } of this.callbacks.values())
|
|
391
|
+
if (kind !== "queue-release")
|
|
392
|
+
controller.abort();
|
|
393
|
+
}
|
|
394
|
+
throw error;
|
|
395
|
+
}
|
|
396
|
+
finally {
|
|
397
|
+
this.resuming = undefined;
|
|
398
|
+
ownedSignal.removeEventListener("abort", abort);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
sameClient(facts) {
|
|
402
|
+
return facts.id === this.facts.id && facts.pid === this.facts.pid && facts.generation === this.facts.generation;
|
|
403
|
+
}
|
|
246
404
|
async run(operation, payload, signal, onCommit) {
|
|
247
|
-
if (this.closed ||
|
|
248
|
-
|
|
405
|
+
if (this.closed ||
|
|
406
|
+
this.uncertain ||
|
|
407
|
+
this.contactResumeState !== "idle" ||
|
|
408
|
+
this.pausing ||
|
|
409
|
+
this.disposing ||
|
|
410
|
+
this.contactState === "expired" ||
|
|
411
|
+
this.contactState === "inactive")
|
|
412
|
+
throw new Error("Daemon client is unavailable; confirm contact and drain work before submitting.");
|
|
249
413
|
signal?.throwIfAborted();
|
|
414
|
+
this.pendingJobs++;
|
|
250
415
|
const id = `${operationPrefix(this.identity)}${randomUUID()}`;
|
|
251
416
|
const abort = () => {
|
|
252
417
|
void requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id }, this.controller.signal).catch(() => { });
|
|
@@ -263,11 +428,11 @@ export class DaemonConnection {
|
|
|
263
428
|
const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor, job: id }, this.controller.signal);
|
|
264
429
|
this.consume(reply);
|
|
265
430
|
const job = record(reply) ? reply.job : undefined;
|
|
266
|
-
if (job?.phase === "failed") {
|
|
431
|
+
if (job?.id === id && job.phase === "failed") {
|
|
267
432
|
terminal = true;
|
|
268
433
|
throw new DaemonError(job.error ?? { name: "Error", message: "Daemon operation failed." });
|
|
269
434
|
}
|
|
270
|
-
if (job?.phase === "done") {
|
|
435
|
+
if (job?.id === id && job.phase === "done") {
|
|
271
436
|
terminal = true;
|
|
272
437
|
signal?.throwIfAborted();
|
|
273
438
|
return job.result;
|
|
@@ -293,7 +458,11 @@ export class DaemonConnection {
|
|
|
293
458
|
throw new Error("Operation outcome is uncertain; reload to reconnect and reconcile, never replay the write.", { cause: error });
|
|
294
459
|
}
|
|
295
460
|
}
|
|
296
|
-
});
|
|
461
|
+
}).finally(() => this.pendingJobs--);
|
|
462
|
+
}
|
|
463
|
+
publishContact(contact) {
|
|
464
|
+
this.contactRevision++;
|
|
465
|
+
this.observedContact = contact;
|
|
297
466
|
}
|
|
298
467
|
consume(reply) {
|
|
299
468
|
if (!record(reply) ||
|
|
@@ -303,8 +472,11 @@ export class DaemonConnection {
|
|
|
303
472
|
!Array.isArray(reply.callbacks) ||
|
|
304
473
|
!Array.isArray(reply.events))
|
|
305
474
|
throw new Error("Invalid daemon poll response.");
|
|
475
|
+
const { contact } = reply;
|
|
476
|
+
if (contact !== undefined && contact !== "active" && contact !== "expired" && contact !== "inactive")
|
|
477
|
+
throw new Error("Invalid daemon contact state.");
|
|
306
478
|
if (reply.cursor < this.cursor)
|
|
307
|
-
return;
|
|
479
|
+
return contact;
|
|
308
480
|
for (const event of reply.events)
|
|
309
481
|
if (event.id > this.cursor) {
|
|
310
482
|
if (event.kind === "commit" && record(event.payload) && typeof event.payload.job === "string") {
|
|
@@ -331,7 +503,7 @@ export class DaemonConnection {
|
|
|
331
503
|
let value;
|
|
332
504
|
let failed = false;
|
|
333
505
|
try {
|
|
334
|
-
if (this.uncertain && callback.kind !== "queue-release")
|
|
506
|
+
if ((this.uncertain || this.resumeUncertain) && callback.kind !== "queue-release")
|
|
335
507
|
throw new Error("Client is draining uncertain work.");
|
|
336
508
|
value = await this.performCallback(callback, controller.signal);
|
|
337
509
|
}
|
|
@@ -356,6 +528,7 @@ export class DaemonConnection {
|
|
|
356
528
|
});
|
|
357
529
|
this.callbackTasks.add(task);
|
|
358
530
|
}
|
|
531
|
+
return contact;
|
|
359
532
|
}
|
|
360
533
|
async performCallback(callback, signal) {
|
|
361
534
|
const reference = callback.review;
|
|
@@ -425,9 +598,25 @@ export class DaemonConnection {
|
|
|
425
598
|
async poll() {
|
|
426
599
|
while (!this.closed) {
|
|
427
600
|
try {
|
|
601
|
+
const revision = this.contactRevision;
|
|
428
602
|
const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor }, this.controller.signal);
|
|
429
|
-
|
|
430
|
-
this.
|
|
603
|
+
// An older poll must not undo typed update expiry or a successful resume.
|
|
604
|
+
if (revision === this.contactRevision) {
|
|
605
|
+
const contact = this.consume(reply);
|
|
606
|
+
this.reportedError = false;
|
|
607
|
+
if (revision === this.contactRevision &&
|
|
608
|
+
this.attached &&
|
|
609
|
+
!this.admitting &&
|
|
610
|
+
!this.pausing &&
|
|
611
|
+
!this.disposing &&
|
|
612
|
+
!this.closed) {
|
|
613
|
+
// A new observation fences older facts replies; identical polls do not.
|
|
614
|
+
if (contact !== this.observedContact)
|
|
615
|
+
this.publishContact(contact);
|
|
616
|
+
if (contact !== undefined)
|
|
617
|
+
this.options.contact?.(contact);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
431
620
|
await this.wait(100);
|
|
432
621
|
}
|
|
433
622
|
catch (error) {
|
|
@@ -445,16 +634,31 @@ export class DaemonConnection {
|
|
|
445
634
|
}
|
|
446
635
|
}
|
|
447
636
|
async pause() {
|
|
448
|
-
if (this.closed)
|
|
637
|
+
if (this.closed || this.disposing)
|
|
449
638
|
throw new Error("Daemon client is closed.");
|
|
450
|
-
|
|
451
|
-
|
|
639
|
+
if (this.pausing)
|
|
640
|
+
return this.pausing;
|
|
641
|
+
this.resuming?.abort(new DOMException("Client paused", "AbortError"));
|
|
642
|
+
this.lifecycleRevision++;
|
|
643
|
+
this.contactRevision++;
|
|
644
|
+
this.pausing = (async () => {
|
|
645
|
+
const reply = await requestDaemon(this.paths, this.identity, "pause", { client: this.facts.id });
|
|
646
|
+
const contact = this.consume(reply);
|
|
647
|
+
if (!this.disposing)
|
|
648
|
+
this.publishContact(contact);
|
|
649
|
+
})().finally(() => {
|
|
650
|
+
this.pausing = undefined;
|
|
651
|
+
});
|
|
652
|
+
return this.pausing;
|
|
452
653
|
}
|
|
453
654
|
async dispose(handoff) {
|
|
454
655
|
if (this.disposing)
|
|
455
656
|
return this.disposing;
|
|
456
657
|
if (this.closed)
|
|
457
658
|
return;
|
|
659
|
+
this.resuming?.abort(new DOMException("Client disposed", "AbortError"));
|
|
660
|
+
this.lifecycleRevision++;
|
|
661
|
+
this.contactRevision++;
|
|
458
662
|
this.disposing = (async () => {
|
|
459
663
|
this.polling ??= this.poll();
|
|
460
664
|
// Cancel UI before drain, but keep polling for acknowledged queue-release callbacks.
|
package/dist/engine-service.d.ts
CHANGED
|
@@ -7,5 +7,8 @@ export declare function createEngineService(root: string): {
|
|
|
7
7
|
factsChanged: () => Promise<void>;
|
|
8
8
|
idle: () => void;
|
|
9
9
|
close: () => Promise<void>;
|
|
10
|
+
lifetime: () => Promise<import("./idle-exit.js").IdleExitPolicy>;
|
|
11
|
+
quiesce: () => Promise<void>;
|
|
12
|
+
failure: () => void;
|
|
10
13
|
};
|
|
11
14
|
};
|
package/dist/engine-service.js
CHANGED
|
@@ -268,7 +268,14 @@ export function createEngineService(root) {
|
|
|
268
268
|
return {
|
|
269
269
|
execute,
|
|
270
270
|
bind: monitor.bind,
|
|
271
|
-
hooks: {
|
|
271
|
+
hooks: {
|
|
272
|
+
factsChanged: monitor.factsChanged,
|
|
273
|
+
idle: monitor.schedule,
|
|
274
|
+
close: monitor.close,
|
|
275
|
+
lifetime: monitor.lifetime,
|
|
276
|
+
quiesce: monitor.pause,
|
|
277
|
+
failure: monitor.blockAutomatic,
|
|
278
|
+
},
|
|
272
279
|
};
|
|
273
280
|
}
|
|
274
281
|
async function withJobTimings(ctx, execution, label, action) {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const IDLE_EXIT_GRACE_MS = 30000;
|
|
2
|
+
export type IdleExitPolicy = "exit" | "keep" | "pause";
|
|
3
|
+
interface IdleExitHooks {
|
|
4
|
+
live(): boolean;
|
|
5
|
+
policy(): Promise<IdleExitPolicy>;
|
|
6
|
+
quiesce(): Promise<void>;
|
|
7
|
+
close(current: () => boolean): Promise<boolean>;
|
|
8
|
+
resume(): void;
|
|
9
|
+
failed(): void;
|
|
10
|
+
}
|
|
11
|
+
/** The server heartbeat owns timing; this controller owns only one guarded deadline and evaluation. */
|
|
12
|
+
export declare function createIdleExit(hooks: IdleExitHooks): {
|
|
13
|
+
changed: () => void;
|
|
14
|
+
tick(): Promise<void>;
|
|
15
|
+
dispose(): Promise<void>;
|
|
16
|
+
};
|
|
17
|
+
export {};
|