@jini-ai/sidecar 0.6.16 → 0.6.19
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 +7 -1
- package/dist/supervisor-node.d.ts +70 -0
- package/dist/supervisor-node.js +180 -11
- package/dist/supervisor.d.ts +12 -2
- package/dist/supervisor.js +61 -10
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @jini-ai/sidecar
|
|
2
2
|
|
|
3
|
+
## 0.6.17
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Version bump only.
|
|
8
|
+
|
|
3
9
|
## 0.6.13
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
|
@@ -59,7 +65,7 @@
|
|
|
59
65
|
- Atomic filesystem handling is canonical in platform and Node supervisor defaults are isolated in ./supervisor/node.
|
|
60
66
|
- Distribution includes runtime output, release documentation and required assets only. Process records and per-job neutrality checks are no longer part of the package surface.
|
|
61
67
|
|
|
62
|
-
##
|
|
68
|
+
## 0.6.19
|
|
63
69
|
|
|
64
70
|
- Fix supervisor test compilation by checking event-array emptiness without narrowing later lifecycle events to `never`.
|
|
65
71
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Writable } from "node:stream";
|
|
2
2
|
import type { ChildProcess, SpawnOptions } from "node:child_process";
|
|
3
|
+
import type { Serializable } from "node:child_process";
|
|
3
4
|
import { listProcessSnapshots, stopProcesses, waitForProcessExit } from "@jini-ai/platform/process";
|
|
4
5
|
import type { LocalDaemonRegistryRecord } from "./daemon-registry.js";
|
|
5
6
|
import type { SpawnedDaemonProcess, SupervisorScheduler } from "./supervisor.js";
|
|
@@ -30,6 +31,10 @@ export interface NodeDaemonProcessRequired {
|
|
|
30
31
|
registry: SupervisorRegistry;
|
|
31
32
|
}
|
|
32
33
|
export interface NodeDaemonProcessOptions {
|
|
34
|
+
/** Inherit a separate native control channel; stdin remains the Windows EOF shutdown pipe. */
|
|
35
|
+
ipc?: boolean;
|
|
36
|
+
/** Delivered once over native IPC, removed case-insensitively from the OS environment. */
|
|
37
|
+
startupSecrets?: Readonly<Record<string, string>>;
|
|
33
38
|
stdout?: Writable;
|
|
34
39
|
stderr?: Writable;
|
|
35
40
|
platform?: NodeJS.Platform;
|
|
@@ -68,4 +73,69 @@ export declare function createNodeDaemonProcessAdapter(required: NodeDaemonProce
|
|
|
68
73
|
* @complexity O(1) per schedule/cancel.
|
|
69
74
|
*/
|
|
70
75
|
export declare function createNodeSupervisorScheduler(_required: Record<string, never>): SupervisorScheduler;
|
|
76
|
+
/** A channel bound to one native child (or its process end), never an address supplied by a caller. */
|
|
77
|
+
export interface NodeIpcPeer {
|
|
78
|
+
readonly connected?: boolean;
|
|
79
|
+
send?: (message: Serializable, callback: (error: Error | null) => void) => boolean;
|
|
80
|
+
on(event: "message" | "disconnect", listener: (message: unknown) => void): unknown;
|
|
81
|
+
removeListener(event: "message" | "disconnect", listener: (message: unknown) => void): unknown;
|
|
82
|
+
}
|
|
83
|
+
/** Native request/reply with bounded pending work. Errors never echo a request, payload or handler error.
|
|
84
|
+
* @param required The actual spawned child or inherited process channel.
|
|
85
|
+
* @param optional Handler, deadline and pending-request cap; construction starts no requests.
|
|
86
|
+
* @returns Request and idempotent disposal; disconnect rejects and clears every pending request.
|
|
87
|
+
* @throws On disconnected IPC, timeout, refusal, >1 MiB envelope or capacity overflow.
|
|
88
|
+
* @complexity O(payload bytes) per send, O(p) disconnect for at most maxPending requests.
|
|
89
|
+
*/
|
|
90
|
+
export declare function createNodeIpcChannel({ peer }: {
|
|
91
|
+
peer: NodeIpcPeer;
|
|
92
|
+
}, { handle, timeoutMs, maxPending, channel, }?: {
|
|
93
|
+
handle?: (payload: unknown) => Promise<Serializable>;
|
|
94
|
+
timeoutMs?: number;
|
|
95
|
+
maxPending?: number;
|
|
96
|
+
channel?: string;
|
|
97
|
+
}): {
|
|
98
|
+
request({ payload }: {
|
|
99
|
+
payload: Serializable;
|
|
100
|
+
}, _optional?: {}): Promise<unknown>;
|
|
101
|
+
dispose: (_required: Record<string, never>, _optional?: {}) => void;
|
|
102
|
+
};
|
|
103
|
+
/** Non-secret launch marker; the payload itself never enters argv or process.env. */
|
|
104
|
+
export declare const STARTUP_SECRETS_ENV = "JINI_STARTUP_SECRETS_IPC";
|
|
105
|
+
/** Separate host-selected capabilities from a launch environment without mutating it.
|
|
106
|
+
* Windows case variants map to the canonical host key; absent values create no credential.
|
|
107
|
+
* @returns Independent environment and capability records; throws beyond the 64 KiB/256-key limit.
|
|
108
|
+
* @complexity O(e + k) time/space.
|
|
109
|
+
* @example splitNodeStartupSecrets({ env, keys: ['HOST_TOKEN'] });
|
|
110
|
+
*/
|
|
111
|
+
export declare function splitNodeStartupSecrets({ env, keys }: {
|
|
112
|
+
env: Readonly<NodeJS.ProcessEnv>;
|
|
113
|
+
keys: readonly string[];
|
|
114
|
+
}, _optional?: Record<string, never>): {
|
|
115
|
+
env: NodeJS.ProcessEnv;
|
|
116
|
+
secrets: Record<string, string>;
|
|
117
|
+
};
|
|
118
|
+
/** Offer credentials to this native child once, sharing IPC with the existing control owner.
|
|
119
|
+
* @returns A disposer for child exit/error; disconnect also clears the channel.
|
|
120
|
+
* @throws For an invalid/oversized record. Refusals never contain credentials.
|
|
121
|
+
* @complexity O(bytes) bounded copy; one in-memory record until the child's first read.
|
|
122
|
+
* @example provideNodeStartupSecrets({ peer: child, secrets: { HOST_TOKEN: token } });
|
|
123
|
+
*/
|
|
124
|
+
export declare function provideNodeStartupSecrets({ peer, secrets }: {
|
|
125
|
+
peer: NodeIpcPeer;
|
|
126
|
+
secrets: Readonly<Record<string, string>>;
|
|
127
|
+
}, _optional?: Record<string, never>): {
|
|
128
|
+
dispose(_required?: Record<string, never>, _options?: Record<string, never>): void;
|
|
129
|
+
};
|
|
130
|
+
/** Read credentials over inherited IPC and release the receiver even on timeout/disconnect.
|
|
131
|
+
* The caller retains the returned record in memory; it must never assign it to process.env.
|
|
132
|
+
* @throws On unavailable IPC, refusal, timeout or malformed credentials.
|
|
133
|
+
* @complexity O(bytes) bounded validation; one request with a 30s default deadline.
|
|
134
|
+
* @example const secrets = await receiveNodeStartupSecrets({ peer: process });
|
|
135
|
+
*/
|
|
136
|
+
export declare function receiveNodeStartupSecrets({ peer }: {
|
|
137
|
+
peer: NodeIpcPeer;
|
|
138
|
+
}, { timeoutMs, }?: {
|
|
139
|
+
timeoutMs?: number;
|
|
140
|
+
}): Promise<Record<string, string>>;
|
|
71
141
|
//# sourceMappingURL=supervisor-node.d.ts.map
|
package/dist/supervisor-node.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
2
3
|
import { createCommandInvocation } from "@jini-ai/platform/command";
|
|
4
|
+
import { omitEnvironmentKeys } from "@jini-ai/platform/child-environment";
|
|
3
5
|
import { collectProcessTreePids, listProcessSnapshots, stopProcesses, waitForProcessExit } from "@jini-ai/platform/process";
|
|
4
6
|
import { readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, writeDaemonRegistryRecord } from "./daemon-registry.js";
|
|
5
7
|
/**
|
|
@@ -45,6 +47,31 @@ async function stopWindowsProcess({ child, pid }, options = {}) {
|
|
|
45
47
|
}
|
|
46
48
|
}
|
|
47
49
|
}
|
|
50
|
+
/** Build an OS environment, reserving IPC for capabilities while stdin remains the stop pipe.
|
|
51
|
+
* @returns A detached launch environment. @complexity O(e + k) for env entries and secret keys.
|
|
52
|
+
*/
|
|
53
|
+
function daemonLaunchEnvironment(required, options = {}) {
|
|
54
|
+
if (options.startupSecrets === undefined)
|
|
55
|
+
return required.env;
|
|
56
|
+
return { ...splitNodeStartupSecrets({ env: required.env, keys: Object.keys(options.startupSecrets) }).env,
|
|
57
|
+
[STARTUP_SECRETS_ENV]: '1' };
|
|
58
|
+
}
|
|
59
|
+
/** Resolve command quoting and native descriptors without creating a process.
|
|
60
|
+
* Detached groups enable tree stopping; parent output pipes cannot strand inherited descriptors.
|
|
61
|
+
* @returns The command invocation, Windows mode and native spawn options. @complexity O(e) env copy.
|
|
62
|
+
*/
|
|
63
|
+
function daemonLaunchPlan(required, options = {}) {
|
|
64
|
+
const win32 = (options.platform ?? process.platform) === 'win32';
|
|
65
|
+
const env = daemonLaunchEnvironment(required, options);
|
|
66
|
+
const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env });
|
|
67
|
+
const ipc = options.ipc || options.startupSecrets !== undefined;
|
|
68
|
+
const spawnOptions = {
|
|
69
|
+
cwd: required.cwd, env: { ...env, ...(win32 ? { JINI_STOP_ON_STDIN_EOF: '1' } : {}) }, detached: true, windowsHide: true,
|
|
70
|
+
stdio: [win32 ? 'pipe' : 'ignore', 'pipe', 'pipe', ...(ipc ? ['ipc'] : [])],
|
|
71
|
+
...(invocation.windowsVerbatimArguments === undefined ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments }),
|
|
72
|
+
};
|
|
73
|
+
return { invocation, spawnOptions, win32 };
|
|
74
|
+
}
|
|
48
75
|
/**
|
|
49
76
|
* Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
|
|
50
77
|
* @param required Complete host launch settings and the shared sidecar registry port.
|
|
@@ -53,22 +80,20 @@ async function stopWindowsProcess({ child, pid }, options = {}) {
|
|
|
53
80
|
* @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
|
|
54
81
|
*/
|
|
55
82
|
export function createNodeDaemonProcessAdapter(required, options = {}) {
|
|
83
|
+
// Validate/snapshot before spawning: a launch must not orphan a child when delivery is refused.
|
|
84
|
+
const startupSecrets = options.startupSecrets === undefined ? undefined : startupSecretRecord(options.startupSecrets);
|
|
85
|
+
const launchOptions = startupSecrets === undefined ? options : { ...options, startupSecrets };
|
|
56
86
|
return {
|
|
57
87
|
spawnDaemonProcess() {
|
|
58
|
-
const win32 = (
|
|
59
|
-
const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env: required.env });
|
|
60
|
-
// detached creates a POSIX process group so teardown reaches the daemon below a
|
|
61
|
-
// launcher hop; windowsHide avoids an otherwise visible detached Windows console.
|
|
62
|
-
// Pipe output through the parent instead of inheriting its descriptors: an orphan
|
|
63
|
-
// retaining those descriptors previously kept parent/test teardown waiting forever.
|
|
64
|
-
const spawnOptions = {
|
|
65
|
-
cwd: required.cwd, env: { ...required.env, ...(win32 ? { JINI_STOP_ON_STDIN_EOF: "1" } : {}) }, detached: true, windowsHide: true,
|
|
66
|
-
stdio: [win32 ? "pipe" : "ignore", "pipe", "pipe"],
|
|
67
|
-
...(invocation.windowsVerbatimArguments === undefined ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments }),
|
|
68
|
-
};
|
|
88
|
+
const { invocation, spawnOptions, win32 } = daemonLaunchPlan(required, launchOptions);
|
|
69
89
|
const child = options.spawn
|
|
70
90
|
? options.spawn({ command: invocation.command, args: invocation.args, options: spawnOptions }, {})
|
|
71
91
|
: spawn(invocation.command, invocation.args, spawnOptions);
|
|
92
|
+
if (startupSecrets !== undefined) {
|
|
93
|
+
const delivery = provideNodeStartupSecrets({ peer: child, secrets: startupSecrets });
|
|
94
|
+
child.once('exit', () => delivery.dispose({}));
|
|
95
|
+
child.once('error', () => delivery.dispose({}));
|
|
96
|
+
}
|
|
72
97
|
relayProcessOutput({ stream: child.stdout, sink: options.stdout });
|
|
73
98
|
relayProcessOutput({ stream: child.stderr, sink: options.stderr });
|
|
74
99
|
return {
|
|
@@ -121,4 +146,148 @@ export function createNodeDaemonProcessAdapter(required, options = {}) {
|
|
|
121
146
|
export function createNodeSupervisorScheduler(_required) {
|
|
122
147
|
return { schedule: ({ delayMs, run }) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); } };
|
|
123
148
|
}
|
|
149
|
+
/** Native deserialization supplies plain objects; accept only this channel's envelope. O(1). */
|
|
150
|
+
function isIpcEnvelope(message) {
|
|
151
|
+
if (typeof message !== "object" || message === null)
|
|
152
|
+
return false;
|
|
153
|
+
return "jiniIpc" in message && message.jiniIpc === 1 && "id" in message && typeof message.id === "string" && "kind" in message;
|
|
154
|
+
}
|
|
155
|
+
/** Native request/reply with bounded pending work. Errors never echo a request, payload or handler error.
|
|
156
|
+
* @param required The actual spawned child or inherited process channel.
|
|
157
|
+
* @param optional Handler, deadline and pending-request cap; construction starts no requests.
|
|
158
|
+
* @returns Request and idempotent disposal; disconnect rejects and clears every pending request.
|
|
159
|
+
* @throws On disconnected IPC, timeout, refusal, >1 MiB envelope or capacity overflow.
|
|
160
|
+
* @complexity O(payload bytes) per send, O(p) disconnect for at most maxPending requests.
|
|
161
|
+
*/
|
|
162
|
+
export function createNodeIpcChannel({ peer }, { handle, timeoutMs = 30_000, maxPending = 64, channel, } = {}) {
|
|
163
|
+
const pending = new Map();
|
|
164
|
+
let disposed = false;
|
|
165
|
+
let handling = 0;
|
|
166
|
+
function send(envelope) {
|
|
167
|
+
const message = channel === undefined ? envelope : { ...envelope, channel };
|
|
168
|
+
if (disposed || !peer.connected || !peer.send)
|
|
169
|
+
throw new Error("IPC disconnected");
|
|
170
|
+
if (Buffer.byteLength(JSON.stringify(message)) > 1024 * 1024)
|
|
171
|
+
throw new Error("IPC envelope too large");
|
|
172
|
+
peer.send(message, error => { if (error)
|
|
173
|
+
dispose({}); });
|
|
174
|
+
}
|
|
175
|
+
function reply(message) {
|
|
176
|
+
try {
|
|
177
|
+
send(message);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
dispose({});
|
|
181
|
+
} // A departing peer cannot receive a refusal.
|
|
182
|
+
}
|
|
183
|
+
function receive(message) {
|
|
184
|
+
if (disposed || !isIpcEnvelope(message) || message.channel !== channel)
|
|
185
|
+
return;
|
|
186
|
+
const { id } = message;
|
|
187
|
+
if (message.kind === "reply") {
|
|
188
|
+
pending.get(id)?.finish(message.ok === true ? null : new Error("IPC request refused"), message.payload);
|
|
189
|
+
}
|
|
190
|
+
else if (message.kind === "request" && handle) {
|
|
191
|
+
if (handling >= maxPending) {
|
|
192
|
+
reply({ jiniIpc: 1, kind: "reply", id, ok: false });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
handling++;
|
|
196
|
+
void Promise.resolve().then(() => handle(message.payload)).then(payload => reply({ jiniIpc: 1, kind: "reply", id, ok: true, payload }), () => reply({ jiniIpc: 1, kind: "reply", id, ok: false })).catch(() => { }).finally(() => { handling--; }); // A disconnected peer cannot receive its reply.
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function dispose(_required, _optional = {}) {
|
|
200
|
+
disposed = true;
|
|
201
|
+
peer.removeListener("message", receive);
|
|
202
|
+
peer.removeListener("disconnect", disconnect);
|
|
203
|
+
for (const request of pending.values())
|
|
204
|
+
request.finish(new Error("IPC disconnected"));
|
|
205
|
+
}
|
|
206
|
+
const disconnect = () => dispose({});
|
|
207
|
+
peer.on("message", receive);
|
|
208
|
+
peer.on("disconnect", disconnect);
|
|
209
|
+
return {
|
|
210
|
+
request({ payload }, _optional = {}) {
|
|
211
|
+
if (disposed || !peer.connected)
|
|
212
|
+
return Promise.reject(new Error("IPC disconnected"));
|
|
213
|
+
if (pending.size >= maxPending)
|
|
214
|
+
return Promise.reject(new Error("IPC capacity exceeded"));
|
|
215
|
+
const id = randomUUID();
|
|
216
|
+
return new Promise((resolve, reject) => {
|
|
217
|
+
const timer = setTimeout(() => pending.get(id)?.finish(new Error("IPC request timed out")), timeoutMs);
|
|
218
|
+
pending.set(id, { finish(error, value) { clearTimeout(timer); pending.delete(id); if (error)
|
|
219
|
+
reject(error);
|
|
220
|
+
else
|
|
221
|
+
resolve(value); } });
|
|
222
|
+
try {
|
|
223
|
+
send({ jiniIpc: 1, kind: "request", id, payload });
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
const reason = error instanceof Error && error.message === "IPC envelope too large" ? error.message : "IPC send failed";
|
|
227
|
+
pending.get(id)?.finish(new Error(reason));
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
},
|
|
231
|
+
dispose,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/** Non-secret launch marker; the payload itself never enters argv or process.env. */
|
|
235
|
+
export const STARTUP_SECRETS_ENV = 'JINI_STARTUP_SECRETS_IPC';
|
|
236
|
+
/** Separate host-selected capabilities from a launch environment without mutating it.
|
|
237
|
+
* Windows case variants map to the canonical host key; absent values create no credential.
|
|
238
|
+
* @returns Independent environment and capability records; throws beyond the 64 KiB/256-key limit.
|
|
239
|
+
* @complexity O(e + k) time/space.
|
|
240
|
+
* @example splitNodeStartupSecrets({ env, keys: ['HOST_TOKEN'] });
|
|
241
|
+
*/
|
|
242
|
+
export function splitNodeStartupSecrets({ env, keys }, _optional = {}) {
|
|
243
|
+
const names = new Map(keys.map(key => [key.toUpperCase(), key]));
|
|
244
|
+
const secrets = Object.fromEntries(Object.entries(env).flatMap(([key, value]) => {
|
|
245
|
+
const name = names.get(key.toUpperCase());
|
|
246
|
+
return name !== undefined && value !== undefined ? [[name, value]] : [];
|
|
247
|
+
}));
|
|
248
|
+
return { env: omitEnvironmentKeys({ env, keys }, { caseInsensitive: true }).env, secrets: startupSecretRecord(secrets) };
|
|
249
|
+
}
|
|
250
|
+
/** Validate the small startup record without echoing values into diagnostics. O(bytes), capped at 64 KiB. */
|
|
251
|
+
function startupSecretRecord(value) {
|
|
252
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
253
|
+
throw new Error('Invalid startup credentials');
|
|
254
|
+
const entries = Object.entries(value);
|
|
255
|
+
if (entries.length > 256 || entries.some(([, secret]) => typeof secret !== 'string'))
|
|
256
|
+
throw new Error('Invalid startup credentials');
|
|
257
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 65536)
|
|
258
|
+
throw new Error('Startup credentials exceed limit');
|
|
259
|
+
return Object.fromEntries(entries);
|
|
260
|
+
}
|
|
261
|
+
/** Offer credentials to this native child once, sharing IPC with the existing control owner.
|
|
262
|
+
* @returns A disposer for child exit/error; disconnect also clears the channel.
|
|
263
|
+
* @throws For an invalid/oversized record. Refusals never contain credentials.
|
|
264
|
+
* @complexity O(bytes) bounded copy; one in-memory record until the child's first read.
|
|
265
|
+
* @example provideNodeStartupSecrets({ peer: child, secrets: { HOST_TOKEN: token } });
|
|
266
|
+
*/
|
|
267
|
+
export function provideNodeStartupSecrets({ peer, secrets }, _optional = {}) {
|
|
268
|
+
let remaining = startupSecretRecord(secrets);
|
|
269
|
+
const channel = createNodeIpcChannel({ peer }, { channel: 'startup-secrets', handle: async (payload) => {
|
|
270
|
+
if (payload !== 'read' || remaining === undefined)
|
|
271
|
+
throw new Error('Startup credentials already consumed');
|
|
272
|
+
const result = remaining;
|
|
273
|
+
remaining = undefined;
|
|
274
|
+
return result;
|
|
275
|
+
} });
|
|
276
|
+
return { dispose(_required = {}, _options = {}) { remaining = undefined; channel.dispose({}); } };
|
|
277
|
+
}
|
|
278
|
+
/** Read credentials over inherited IPC and release the receiver even on timeout/disconnect.
|
|
279
|
+
* The caller retains the returned record in memory; it must never assign it to process.env.
|
|
280
|
+
* @throws On unavailable IPC, refusal, timeout or malformed credentials.
|
|
281
|
+
* @complexity O(bytes) bounded validation; one request with a 30s default deadline.
|
|
282
|
+
* @example const secrets = await receiveNodeStartupSecrets({ peer: process });
|
|
283
|
+
*/
|
|
284
|
+
export async function receiveNodeStartupSecrets({ peer }, { timeoutMs = 30_000, } = {}) {
|
|
285
|
+
const channel = createNodeIpcChannel({ peer }, { channel: 'startup-secrets', timeoutMs });
|
|
286
|
+
try {
|
|
287
|
+
return startupSecretRecord(await channel.request({ payload: 'read' }, {}));
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
channel.dispose({});
|
|
291
|
+
}
|
|
292
|
+
}
|
|
124
293
|
//# sourceMappingURL=supervisor-node.js.map
|
package/dist/supervisor.d.ts
CHANGED
|
@@ -85,6 +85,8 @@ export interface DaemonSupervisorRequired {
|
|
|
85
85
|
export interface DaemonSupervisorOptions {
|
|
86
86
|
onDemandCooldownMs?: number;
|
|
87
87
|
quietRoutineLifecycle?: boolean;
|
|
88
|
+
/** Normal exit codes that park until demand or manual restart, without charging the retry budget. */
|
|
89
|
+
parkedExitCodes?: readonly number[];
|
|
88
90
|
formatGiveUp?: (input: {
|
|
89
91
|
decision: Extract<RespawnDecision, {
|
|
90
92
|
action: "give-up";
|
|
@@ -96,7 +98,15 @@ export interface DaemonSupervisorActionResult {
|
|
|
96
98
|
ok: boolean;
|
|
97
99
|
reason?: string;
|
|
98
100
|
}
|
|
101
|
+
/** Lifecycle inspection; running describes a child, not discovery readiness. */
|
|
102
|
+
export type DaemonSupervisorState = "stopped" | "running" | "parked" | "shutting-down";
|
|
99
103
|
export interface DaemonSupervisor {
|
|
104
|
+
/** Inspect lifecycle synchronously without starting a child or changing retry policy. */
|
|
105
|
+
getState(): DaemonSupervisorState;
|
|
106
|
+
/** Child refused intake before its normal park exit. Demand waits for exit before replacing it. */
|
|
107
|
+
markParking(requiredArgs: {
|
|
108
|
+
pid: number;
|
|
109
|
+
}, optionalArgs?: Record<string, never>): void;
|
|
100
110
|
start(): void;
|
|
101
111
|
restart(): DaemonSupervisorActionResult;
|
|
102
112
|
ensureStarted(): DaemonSupervisorActionResult;
|
|
@@ -109,8 +119,8 @@ export interface DaemonSupervisor {
|
|
|
109
119
|
/**
|
|
110
120
|
* Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
|
|
111
121
|
* @param deps Required process, policy, clock, scheduler, readiness and observability ports.
|
|
112
|
-
* @param options On-demand cooldown, routine-event suppression and give-up
|
|
113
|
-
* @returns
|
|
122
|
+
* @param options On-demand cooldown, park exit codes, routine-event suppression and give-up formatter.
|
|
123
|
+
* @returns Inspectable lifecycle with idempotent start, demand wake, manual replacement and terminal shutdown.
|
|
114
124
|
* @throws RangeError for a negative or non-finite cooldown.
|
|
115
125
|
* @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
|
|
116
126
|
*/
|
package/dist/supervisor.js
CHANGED
|
@@ -6,8 +6,8 @@ function giveUpReason({ decision, lastReason }) {
|
|
|
6
6
|
/**
|
|
7
7
|
* Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
|
|
8
8
|
* @param deps Required process, policy, clock, scheduler, readiness and observability ports.
|
|
9
|
-
* @param options On-demand cooldown, routine-event suppression and give-up
|
|
10
|
-
* @returns
|
|
9
|
+
* @param options On-demand cooldown, park exit codes, routine-event suppression and give-up formatter.
|
|
10
|
+
* @returns Inspectable lifecycle with idempotent start, demand wake, manual replacement and terminal shutdown.
|
|
11
11
|
* @throws RangeError for a negative or non-finite cooldown.
|
|
12
12
|
* @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
|
|
13
13
|
*/
|
|
@@ -16,6 +16,8 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
16
16
|
if (!Number.isFinite(cooldown) || cooldown < 0)
|
|
17
17
|
throw new RangeError("onDemandCooldownMs must be finite and non-negative");
|
|
18
18
|
const formatGiveUp = options.formatGiveUp ?? giveUpReason;
|
|
19
|
+
const parkedExitCodes = new Set(options.parkedExitCodes);
|
|
20
|
+
let parked = false;
|
|
19
21
|
let current;
|
|
20
22
|
let cancelRetry;
|
|
21
23
|
// Terminal shutdown is a one-way latch, unlike a tripped retry cap. A restart racing
|
|
@@ -28,18 +30,22 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
28
30
|
let discoveryWork;
|
|
29
31
|
let cancelReadiness;
|
|
30
32
|
function isCurrentLive({ candidate }) {
|
|
31
|
-
return candidate !== undefined && current === candidate && !terminating && !candidate.exited && !candidate.stopping;
|
|
33
|
+
return candidate !== undefined && current === candidate && !terminating && !candidate.exited && !candidate.stopping && !candidate.parking;
|
|
32
34
|
}
|
|
33
35
|
function isReady() {
|
|
34
36
|
return readyChild !== undefined && isCurrentLive({ candidate: readyChild });
|
|
35
37
|
}
|
|
38
|
+
/** An exited child can still own unfinished termination work. O(1), no process effects. */
|
|
39
|
+
function hasUnreapedChild() {
|
|
40
|
+
return current !== undefined && (!current.exited || current.stopping);
|
|
41
|
+
}
|
|
36
42
|
/** Discovery outlives individual request deadlines; never re-enter the demand cooldown.
|
|
37
43
|
* O(1) state and at most one discovery read per 250ms, excluding the injected read itself. */
|
|
38
44
|
function waitForReady() {
|
|
39
45
|
return new Promise((resolve, reject) => {
|
|
40
46
|
let settled = false;
|
|
41
47
|
let cancelPoll;
|
|
42
|
-
cancelReadiness = (
|
|
48
|
+
cancelReadiness = (error = new Error("shutting down")) => finish(error);
|
|
43
49
|
function finish(error) {
|
|
44
50
|
if (settled)
|
|
45
51
|
return;
|
|
@@ -83,14 +89,25 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
83
89
|
return Promise.resolve();
|
|
84
90
|
if (!deps.readiness)
|
|
85
91
|
return Promise.reject(new Error("readiness port is not configured"));
|
|
92
|
+
// A shared discovery may already exist; this demand still has to request replacement after
|
|
93
|
+
// the retiring child exits. Reuse that discovery rather than canceling its current waiters.
|
|
94
|
+
if (current?.parking)
|
|
95
|
+
supervisor.ensureStarted();
|
|
86
96
|
if (!readyWork) {
|
|
87
97
|
const start = supervisor.ensureStarted();
|
|
88
98
|
if (!start.ok)
|
|
89
99
|
return Promise.reject(new Error(start.reason));
|
|
90
100
|
// A slow healthy child must keep being discovered after an HTTP caller gives up.
|
|
91
|
-
// Share the monitor across subsequent demands;
|
|
92
|
-
|
|
93
|
-
|
|
101
|
+
// Share the monitor across subsequent demands; shutdown or parking cancels polling.
|
|
102
|
+
// A parked waiter's cleanup must not clear a fresh wake's discovery or request work.
|
|
103
|
+
if (!discoveryWork) {
|
|
104
|
+
const discovery = waitForReady().finally(() => { if (discoveryWork === discovery)
|
|
105
|
+
discoveryWork = undefined; });
|
|
106
|
+
discoveryWork = discovery;
|
|
107
|
+
}
|
|
108
|
+
const ready = readinessDeadline({ work: discoveryWork, scheduler: deps.scheduler }).finally(() => { if (readyWork === ready)
|
|
109
|
+
readyWork = undefined; });
|
|
110
|
+
readyWork = ready;
|
|
94
111
|
}
|
|
95
112
|
return signal ? awaitForCaller({ work: readyWork, signal }) : readyWork;
|
|
96
113
|
}
|
|
@@ -127,6 +144,16 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
127
144
|
}
|
|
128
145
|
}
|
|
129
146
|
function handleUnexpectedExit(code, signal) {
|
|
147
|
+
// Recognize the host's normal park code before classification can charge a crash or bind failure.
|
|
148
|
+
if (code !== null && parkedExitCodes.has(code)) {
|
|
149
|
+
parked = true;
|
|
150
|
+
cancelPendingRetry();
|
|
151
|
+
cancelReadiness?.(new Error("daemon parked"));
|
|
152
|
+
readyChild = undefined;
|
|
153
|
+
readyWork = undefined;
|
|
154
|
+
discoveryWork = undefined;
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
130
157
|
const classification = deps.classifyExit({ code, signal });
|
|
131
158
|
reportFailure(classification.reason);
|
|
132
159
|
const decision = deps.policy.recordFailure({ isPortConflict: classification.isPortConflict });
|
|
@@ -137,7 +164,7 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
137
164
|
cancelRetry = deps.scheduler.schedule({ delayMs: decision.delayMs, run: () => { cancelRetry = undefined; attemptSpawn(); } });
|
|
138
165
|
}
|
|
139
166
|
function attemptSpawn() {
|
|
140
|
-
if (terminating ||
|
|
167
|
+
if (terminating || parked || hasUnreapedChild())
|
|
141
168
|
return;
|
|
142
169
|
// A new attempt must not inherit a stale readiness failure from an earlier child.
|
|
143
170
|
deps.failureReporter.clear();
|
|
@@ -149,7 +176,7 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
149
176
|
reportFailure(`failed to start daemon: ${error instanceof Error ? error.message : String(error)}`);
|
|
150
177
|
return;
|
|
151
178
|
}
|
|
152
|
-
const state = { child, exited: false, deliberate: false, replaceAfterExit: false, stopping: false };
|
|
179
|
+
const state = { child, exited: false, deliberate: false, replaceAfterExit: false, stopping: false, parking: false };
|
|
153
180
|
// Assign synchronously: run-to-completion makes request-driven recovery single-flight
|
|
154
181
|
// without a lock or an await between checking the current child and publishing it.
|
|
155
182
|
current = state;
|
|
@@ -192,6 +219,7 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
192
219
|
// Wait for a still-live child to exit before replacement: spawning alongside it would
|
|
193
220
|
// collide on its listening port and manufacture the bind failure we are recovering from.
|
|
194
221
|
function forceFreshSpawn() {
|
|
222
|
+
parked = false;
|
|
195
223
|
if (current?.stopping) {
|
|
196
224
|
current.replaceAfterExit = true;
|
|
197
225
|
return;
|
|
@@ -208,6 +236,19 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
208
236
|
}
|
|
209
237
|
const supervisor = {
|
|
210
238
|
isReady, ensureReady,
|
|
239
|
+
markParking({ pid }, _optional = {}) {
|
|
240
|
+
if (!current || current.child.pid !== pid || current.exited || terminating)
|
|
241
|
+
return;
|
|
242
|
+
current.parking = true;
|
|
243
|
+
readyChild = undefined;
|
|
244
|
+
},
|
|
245
|
+
getState() {
|
|
246
|
+
if (terminating)
|
|
247
|
+
return "shutting-down";
|
|
248
|
+
if (parked)
|
|
249
|
+
return "parked";
|
|
250
|
+
return current !== undefined && !current.exited ? "running" : "stopped";
|
|
251
|
+
},
|
|
211
252
|
start() { if (cancelRetry === undefined)
|
|
212
253
|
attemptSpawn(); },
|
|
213
254
|
restart() {
|
|
@@ -221,9 +262,19 @@ export function createDaemonSupervisor(deps, options = {}) {
|
|
|
221
262
|
ensureStarted() {
|
|
222
263
|
if (terminating)
|
|
223
264
|
return { ok: false, reason: "shutting down" };
|
|
265
|
+
if (current?.parking && !current.exited) {
|
|
266
|
+
current.replaceAfterExit = true;
|
|
267
|
+
return { ok: true };
|
|
268
|
+
}
|
|
224
269
|
// A scheduled retry keeps its own backoff; request traffic must not accelerate it.
|
|
225
|
-
if ((
|
|
270
|
+
if (hasUnreapedChild() || cancelRetry !== undefined)
|
|
271
|
+
return { ok: true };
|
|
272
|
+
// Parking is healthy idleness: wake immediately, retaining all earlier crash history.
|
|
273
|
+
if (parked) {
|
|
274
|
+
lastOnDemandAttemptAt = deps.now();
|
|
275
|
+
forceFreshSpawn();
|
|
226
276
|
return { ok: true };
|
|
277
|
+
}
|
|
227
278
|
// Single-flight alone cannot stop a storm against a durably broken launch. The 30s
|
|
228
279
|
// default floor matches the standard backoff ceiling, bounding traffic-driven retries
|
|
229
280
|
// to the same worst-case rate as timer-driven recovery after a cap or spawn failure.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/sidecar",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.19",
|
|
4
4
|
"description": "Sidecar process runtime: JSON-IPC server and client, IPC path validation, namespace/runtime path resolution, port allocation, launch bootstrap, and a local daemon registry.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -63,12 +63,12 @@
|
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
65
|
"@vitest/coverage-v8": "^2.1.9",
|
|
66
|
-
"@jini-ai/
|
|
67
|
-
"@jini-ai/
|
|
66
|
+
"@jini-ai/core": "0.6.19",
|
|
67
|
+
"@jini-ai/platform": "0.6.19"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
|
-
"@jini-ai/
|
|
71
|
-
"@jini-ai/
|
|
70
|
+
"@jini-ai/core": "^0.6.19",
|
|
71
|
+
"@jini-ai/platform": "^0.6.19"
|
|
72
72
|
},
|
|
73
73
|
"scripts": {
|
|
74
74
|
"build": "tsc -p tsconfig.json",
|