@jini-ai/sidecar 0.7.1 → 0.7.2
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 -0
- package/dist/respawn-policy.d.ts +51 -0
- package/dist/respawn-policy.js +46 -0
- package/dist/supervisor-node.d.ts +71 -0
- package/dist/supervisor-node.js +120 -0
- package/dist/supervisor.d.ts +108 -0
- package/dist/supervisor.js +178 -0
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Rolling failure-window backoff with an independent consecutive port-conflict cap. */
|
|
2
|
+
/**
|
|
3
|
+
* Keep retry decisions free of process I/O and timers so an injected clock can exercise the
|
|
4
|
+
* policy without real delays or child processes. Backoff uses the same rolling window as the
|
|
5
|
+
* crash-loop cap, rather than lifetime attempts: hosts without a healthy-start acknowledgment
|
|
6
|
+
* still self-heal after quiet periods, and an isolated late crash starts at the fast end again.
|
|
7
|
+
* Consecutive port conflicts get a separate, tighter cap. A leaked port either clears during
|
|
8
|
+
* the first short retries or does not; climbing the entire crash ladder cannot fix a stuck port.
|
|
9
|
+
* A different failure resets that counter because it tracks this specific problem, not general health.
|
|
10
|
+
*/
|
|
11
|
+
export interface RespawnPolicyOptions {
|
|
12
|
+
backoffScheduleMs?: readonly number[];
|
|
13
|
+
crashLoopWindowMs?: number;
|
|
14
|
+
crashLoopMaxFailures?: number;
|
|
15
|
+
portConflictMaxAttempts?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface RespawnFailureInput {
|
|
18
|
+
isPortConflict: boolean;
|
|
19
|
+
}
|
|
20
|
+
export type RespawnDecision = {
|
|
21
|
+
action: "retry";
|
|
22
|
+
delayMs: number;
|
|
23
|
+
attempt: number;
|
|
24
|
+
} | {
|
|
25
|
+
action: "give-up";
|
|
26
|
+
kind: "crash-loop";
|
|
27
|
+
attempts: number;
|
|
28
|
+
windowMs: number;
|
|
29
|
+
} | {
|
|
30
|
+
action: "give-up";
|
|
31
|
+
kind: "port-conflict";
|
|
32
|
+
attempts: number;
|
|
33
|
+
};
|
|
34
|
+
export interface RespawnPolicy {
|
|
35
|
+
recordFailure(input: RespawnFailureInput): RespawnDecision;
|
|
36
|
+
/** Manual recovery clears counters and the trip so an operator can force a fresh attempt. */
|
|
37
|
+
reset(): void;
|
|
38
|
+
isTripped(): boolean;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Create an independent retry policy; a caller-owned clock is mandatory.
|
|
42
|
+
* @param required Clock port, read once for each recorded failure.
|
|
43
|
+
* @param options Backoff ladder and rolling/consecutive failure thresholds.
|
|
44
|
+
* @returns Stateful policy with explicit reset for manual recovery.
|
|
45
|
+
* @throws RangeError for empty/negative backoff or invalid thresholds.
|
|
46
|
+
* @complexity O(w) per failure for w retained timestamps; reset is O(1).
|
|
47
|
+
*/
|
|
48
|
+
export declare function createRespawnPolicy({ now }: {
|
|
49
|
+
now: () => number;
|
|
50
|
+
}, options?: RespawnPolicyOptions): RespawnPolicy;
|
|
51
|
+
//# sourceMappingURL=respawn-policy.d.ts.map
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Create an independent retry policy; a caller-owned clock is mandatory.
|
|
3
|
+
* @param required Clock port, read once for each recorded failure.
|
|
4
|
+
* @param options Backoff ladder and rolling/consecutive failure thresholds.
|
|
5
|
+
* @returns Stateful policy with explicit reset for manual recovery.
|
|
6
|
+
* @throws RangeError for empty/negative backoff or invalid thresholds.
|
|
7
|
+
* @complexity O(w) per failure for w retained timestamps; reset is O(1).
|
|
8
|
+
*/
|
|
9
|
+
export function createRespawnPolicy({ now }, options = {}) {
|
|
10
|
+
const backoffScheduleMs = [...(options.backoffScheduleMs ?? [1000, 2000, 4000, 8000, 16000, 30000])];
|
|
11
|
+
const crashLoopWindowMs = options.crashLoopWindowMs ?? 60000;
|
|
12
|
+
const crashLoopMaxFailures = options.crashLoopMaxFailures ?? 5;
|
|
13
|
+
const portConflictMaxAttempts = options.portConflictMaxAttempts ?? 3;
|
|
14
|
+
if (backoffScheduleMs.length === 0 || backoffScheduleMs.some((delay) => !Number.isFinite(delay) || delay < 0)) {
|
|
15
|
+
throw new RangeError("backoffScheduleMs must contain finite non-negative delays");
|
|
16
|
+
}
|
|
17
|
+
if (!Number.isFinite(crashLoopWindowMs) || crashLoopWindowMs <= 0)
|
|
18
|
+
throw new RangeError("crashLoopWindowMs must be positive and finite");
|
|
19
|
+
for (const count of [crashLoopMaxFailures, portConflictMaxAttempts]) {
|
|
20
|
+
if (!Number.isSafeInteger(count) || count < 1)
|
|
21
|
+
throw new RangeError("failure thresholds must be positive safe integers");
|
|
22
|
+
}
|
|
23
|
+
let timestamps = [];
|
|
24
|
+
let consecutivePortConflicts = 0;
|
|
25
|
+
let tripped = false;
|
|
26
|
+
return {
|
|
27
|
+
recordFailure({ isPortConflict }) {
|
|
28
|
+
consecutivePortConflicts = isPortConflict ? consecutivePortConflicts + 1 : 0;
|
|
29
|
+
const time = now();
|
|
30
|
+
timestamps = [...timestamps.filter((stamp) => stamp > time - crashLoopWindowMs), time];
|
|
31
|
+
if (consecutivePortConflicts >= portConflictMaxAttempts) {
|
|
32
|
+
tripped = true;
|
|
33
|
+
return { action: "give-up", kind: "port-conflict", attempts: consecutivePortConflicts };
|
|
34
|
+
}
|
|
35
|
+
if (timestamps.length >= crashLoopMaxFailures) {
|
|
36
|
+
tripped = true;
|
|
37
|
+
return { action: "give-up", kind: "crash-loop", attempts: timestamps.length, windowMs: crashLoopWindowMs };
|
|
38
|
+
}
|
|
39
|
+
const attempt = timestamps.length;
|
|
40
|
+
return { action: "retry", delayMs: backoffScheduleMs[Math.min(attempt - 1, backoffScheduleMs.length - 1)], attempt };
|
|
41
|
+
},
|
|
42
|
+
reset() { timestamps = []; consecutivePortConflicts = 0; tripped = false; },
|
|
43
|
+
isTripped() { return tripped; },
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=respawn-policy.js.map
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Writable } from "node:stream";
|
|
2
|
+
import type { ChildProcess, SpawnOptions } from "node:child_process";
|
|
3
|
+
import { listProcessSnapshots, stopProcesses, waitForProcessExit } from "@jini-ai/platform/process";
|
|
4
|
+
import type { LocalDaemonRegistryRecord } from "./daemon-registry.js";
|
|
5
|
+
import type { SpawnedDaemonProcess, SupervisorScheduler } from "./supervisor.js";
|
|
6
|
+
export interface SupervisorRegistry {
|
|
7
|
+
readLive(): Promise<LocalDaemonRegistryRecord | null>;
|
|
8
|
+
write(input: {
|
|
9
|
+
record: LocalDaemonRegistryRecord;
|
|
10
|
+
}): Promise<void>;
|
|
11
|
+
removeIfCurrent(input: {
|
|
12
|
+
pid: number;
|
|
13
|
+
}): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
|
|
17
|
+
* The child calls write only after it actually starts listening.
|
|
18
|
+
* @param required Host-owned registry path.
|
|
19
|
+
* @returns A registry port with object arguments at all data-bearing boundaries.
|
|
20
|
+
* @complexity O(1) operations, excluding filesystem I/O.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createSupervisorRegistry({ registryPath }: {
|
|
23
|
+
registryPath: string;
|
|
24
|
+
}): SupervisorRegistry;
|
|
25
|
+
export interface NodeDaemonProcessRequired {
|
|
26
|
+
command: string;
|
|
27
|
+
args: readonly string[];
|
|
28
|
+
cwd: string;
|
|
29
|
+
env: NodeJS.ProcessEnv;
|
|
30
|
+
registry: SupervisorRegistry;
|
|
31
|
+
}
|
|
32
|
+
export interface NodeDaemonProcessOptions {
|
|
33
|
+
stdout?: Writable;
|
|
34
|
+
stderr?: Writable;
|
|
35
|
+
platform?: NodeJS.Platform;
|
|
36
|
+
/** Native spawn effect port; the adapter still constructs argv, environment and process options. */
|
|
37
|
+
spawn?: (input: {
|
|
38
|
+
command: string;
|
|
39
|
+
args: string[];
|
|
40
|
+
options: SpawnOptions;
|
|
41
|
+
}, optional?: Record<string, never>) => ChildProcess;
|
|
42
|
+
/** Native effect ports retain their platform ABI so tests can supply DI fakes. */
|
|
43
|
+
listProcessSnapshots?: typeof listProcessSnapshots;
|
|
44
|
+
waitForProcessExit?: typeof waitForProcessExit;
|
|
45
|
+
stopProcesses?: typeof stopProcesses;
|
|
46
|
+
signalProcess?: typeof process.kill;
|
|
47
|
+
execFileSync?: (file: string, args: readonly string[], options: {
|
|
48
|
+
stdio: "ignore";
|
|
49
|
+
}) => unknown;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
|
|
53
|
+
* @param required Complete host launch settings and the shared sidecar registry port.
|
|
54
|
+
* @param options Optional native spawn port and sinks; output is piped through the parent rather than inherited.
|
|
55
|
+
* @returns Supervisor process ports. Construction has no process or filesystem effects.
|
|
56
|
+
* @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
|
|
57
|
+
*/
|
|
58
|
+
export declare function createNodeDaemonProcessAdapter(required: NodeDaemonProcessRequired, options?: NodeDaemonProcessOptions): {
|
|
59
|
+
spawnDaemonProcess(): SpawnedDaemonProcess;
|
|
60
|
+
terminateProcess(input: {
|
|
61
|
+
child: SpawnedDaemonProcess;
|
|
62
|
+
}): Promise<void>;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Node timer adapter; importing/constructing it schedules no work.
|
|
66
|
+
* @param required Empty required arguments object.
|
|
67
|
+
* @returns Scheduler using setTimeout and clearTimeout.
|
|
68
|
+
* @complexity O(1) per schedule/cancel.
|
|
69
|
+
*/
|
|
70
|
+
export declare function createNodeSupervisorScheduler(_required: Record<string, never>): SupervisorScheduler;
|
|
71
|
+
//# sourceMappingURL=supervisor-node.d.ts.map
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import { createCommandInvocation } from "@jini-ai/platform/command";
|
|
3
|
+
import { collectProcessTreePids, listProcessSnapshots, stopProcesses, waitForProcessExit } from "@jini-ai/platform/process";
|
|
4
|
+
import { readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, writeDaemonRegistryRecord } from "./daemon-registry.js";
|
|
5
|
+
/**
|
|
6
|
+
* Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
|
|
7
|
+
* The child calls write only after it actually starts listening.
|
|
8
|
+
* @param required Host-owned registry path.
|
|
9
|
+
* @returns A registry port with object arguments at all data-bearing boundaries.
|
|
10
|
+
* @complexity O(1) operations, excluding filesystem I/O.
|
|
11
|
+
*/
|
|
12
|
+
export function createSupervisorRegistry({ registryPath }) {
|
|
13
|
+
return {
|
|
14
|
+
readLive: () => readLiveDaemonRegistryRecord({ registryPath }),
|
|
15
|
+
write: ({ record }) => writeDaemonRegistryRecord({ registryPath, record }),
|
|
16
|
+
removeIfCurrent: ({ pid }) => removeDaemonRegistryRecordIfCurrent({ registryPath, pid }),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
|
|
21
|
+
* @param required Complete host launch settings and the shared sidecar registry port.
|
|
22
|
+
* @param options Optional native spawn port and sinks; output is piped through the parent rather than inherited.
|
|
23
|
+
* @returns Supervisor process ports. Construction has no process or filesystem effects.
|
|
24
|
+
* @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
|
|
25
|
+
*/
|
|
26
|
+
export function createNodeDaemonProcessAdapter(required, options = {}) {
|
|
27
|
+
return {
|
|
28
|
+
spawnDaemonProcess() {
|
|
29
|
+
const win32 = (options.platform ?? process.platform) === "win32";
|
|
30
|
+
const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env: required.env });
|
|
31
|
+
// detached creates a POSIX process group so teardown reaches the daemon below a
|
|
32
|
+
// launcher hop; windowsHide avoids an otherwise visible detached Windows console.
|
|
33
|
+
// Pipe output through the parent instead of inheriting its descriptors: an orphan
|
|
34
|
+
// retaining those descriptors previously kept parent/test teardown waiting forever.
|
|
35
|
+
const spawnOptions = {
|
|
36
|
+
cwd: required.cwd, env: { ...required.env, ...(win32 ? { JINI_STOP_ON_STDIN_EOF: "1" } : {}) }, detached: true, windowsHide: true,
|
|
37
|
+
stdio: [win32 ? "pipe" : "ignore", "pipe", "pipe"],
|
|
38
|
+
...(invocation.windowsVerbatimArguments === undefined ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments }),
|
|
39
|
+
};
|
|
40
|
+
const child = options.spawn
|
|
41
|
+
? options.spawn({ command: invocation.command, args: invocation.args, options: spawnOptions }, {})
|
|
42
|
+
: spawn(invocation.command, invocation.args, spawnOptions);
|
|
43
|
+
if (options.stdout !== undefined)
|
|
44
|
+
child.stdout?.pipe(options.stdout);
|
|
45
|
+
else
|
|
46
|
+
child.stdout?.resume();
|
|
47
|
+
if (options.stderr !== undefined)
|
|
48
|
+
child.stderr?.pipe(options.stderr);
|
|
49
|
+
else
|
|
50
|
+
child.stderr?.resume();
|
|
51
|
+
return {
|
|
52
|
+
get pid() { return child.pid; },
|
|
53
|
+
on(input) {
|
|
54
|
+
if (input.event === "exit")
|
|
55
|
+
child.on("exit", (code, signal) => input.listener({ code, signal }));
|
|
56
|
+
else
|
|
57
|
+
child.on("error", (error) => input.listener({ error }));
|
|
58
|
+
},
|
|
59
|
+
kill(_required, { signal } = {}) { return child.kill(signal); },
|
|
60
|
+
...(win32 && child.stdin ? { closeStdin(_required) {
|
|
61
|
+
// EPIPE when the daemon exits first must not become an unhandled stream error.
|
|
62
|
+
child.stdin.once("error", () => undefined).end();
|
|
63
|
+
} } : {}),
|
|
64
|
+
};
|
|
65
|
+
},
|
|
66
|
+
async terminateProcess({ child }) {
|
|
67
|
+
if (child.pid === undefined)
|
|
68
|
+
return;
|
|
69
|
+
const pid = child.pid;
|
|
70
|
+
const snapshotRequest = (options.listProcessSnapshots ?? listProcessSnapshots)();
|
|
71
|
+
// Request stop before the first await: even a parent exiting immediately starts tree teardown.
|
|
72
|
+
// Windows has no group signal, so taskkill supplies the tree-stop escalation.
|
|
73
|
+
// Windows has no POSIX group signal. Killing only the immediate launcher would
|
|
74
|
+
// orphan its daemon; taskkill /T walks the entire descendant tree instead.
|
|
75
|
+
if ((options.platform ?? process.platform) === "win32") {
|
|
76
|
+
let exited = false;
|
|
77
|
+
if (child.closeStdin !== undefined) {
|
|
78
|
+
try {
|
|
79
|
+
child.closeStdin({});
|
|
80
|
+
// Reuse platform's existing 5s grace before any forced Windows termination.
|
|
81
|
+
exited = await (options.waitForProcessExit ?? waitForProcessExit)(pid);
|
|
82
|
+
}
|
|
83
|
+
catch { /* A broken pipe cannot request shutdown; escalate to the whole tree. */ }
|
|
84
|
+
}
|
|
85
|
+
if (!exited) {
|
|
86
|
+
try {
|
|
87
|
+
(options.execFileSync ?? execFileSync)("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
child.kill({}, { signal: "SIGTERM" });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
try {
|
|
96
|
+
(options.signalProcess ?? process.kill)(-pid, "SIGTERM");
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
child.kill({}, { signal: "SIGTERM" });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const snapshots = await snapshotRequest;
|
|
103
|
+
const pids = collectProcessTreePids(snapshots, [pid]);
|
|
104
|
+
const result = await (options.stopProcesses ?? stopProcesses)(pids);
|
|
105
|
+
if (result.remainingPids.length > 0)
|
|
106
|
+
throw new Error(`daemon processes still running: ${result.remainingPids.join(", ")}`);
|
|
107
|
+
await required.registry.removeIfCurrent({ pid });
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Node timer adapter; importing/constructing it schedules no work.
|
|
113
|
+
* @param required Empty required arguments object.
|
|
114
|
+
* @returns Scheduler using setTimeout and clearTimeout.
|
|
115
|
+
* @complexity O(1) per schedule/cancel.
|
|
116
|
+
*/
|
|
117
|
+
export function createNodeSupervisorScheduler(_required) {
|
|
118
|
+
return { schedule: ({ delayMs, run }) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); } };
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=supervisor-node.js.map
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process signal handlers belong to the host boot wrapper, not the spawn loop: registering
|
|
3
|
+
* them on each automatic respawn would leak another set of global listeners. Retry
|
|
4
|
+
* decisions stay in the pure policy so backoff rules need neither real timers nor children.
|
|
5
|
+
* Construction is safe to import in tests because it does not invoke the host bootstrap.
|
|
6
|
+
*/
|
|
7
|
+
import type { RespawnDecision, RespawnPolicy } from "./respawn-policy.js";
|
|
8
|
+
export type DaemonProcessSubscription = {
|
|
9
|
+
event: "exit";
|
|
10
|
+
listener: (input: {
|
|
11
|
+
code: number | null;
|
|
12
|
+
signal: NodeJS.Signals | null;
|
|
13
|
+
}) => void;
|
|
14
|
+
} | {
|
|
15
|
+
event: "error";
|
|
16
|
+
listener: (input: {
|
|
17
|
+
error: Error;
|
|
18
|
+
}) => void;
|
|
19
|
+
};
|
|
20
|
+
export interface SpawnedDaemonProcess {
|
|
21
|
+
readonly pid?: number | undefined;
|
|
22
|
+
on(input: DaemonProcessSubscription): void;
|
|
23
|
+
kill(requiredArgs: Record<string, never>, optionalArgs?: {
|
|
24
|
+
signal?: NodeJS.Signals;
|
|
25
|
+
}): boolean;
|
|
26
|
+
/** Close the host-owned stdin pipe to request graceful shutdown on Windows. */
|
|
27
|
+
closeStdin?(requiredArgs: Record<string, never>, optionalArgs?: Record<string, never>): void;
|
|
28
|
+
}
|
|
29
|
+
/** Scheduling must defer run until after schedule returns; the returned function cancels it. */
|
|
30
|
+
export interface SupervisorScheduler {
|
|
31
|
+
schedule(input: {
|
|
32
|
+
delayMs: number;
|
|
33
|
+
run: () => void;
|
|
34
|
+
}): () => void;
|
|
35
|
+
}
|
|
36
|
+
export type SupervisorEvent = {
|
|
37
|
+
type: "spawn";
|
|
38
|
+
at: number;
|
|
39
|
+
pid: number | undefined;
|
|
40
|
+
attempt: number;
|
|
41
|
+
} | {
|
|
42
|
+
type: "exit";
|
|
43
|
+
at: number;
|
|
44
|
+
pid: number | undefined;
|
|
45
|
+
code: number | null;
|
|
46
|
+
signal: NodeJS.Signals | null;
|
|
47
|
+
deliberate: boolean;
|
|
48
|
+
} | {
|
|
49
|
+
type: "failure";
|
|
50
|
+
at: number;
|
|
51
|
+
reason: string;
|
|
52
|
+
decision?: RespawnDecision;
|
|
53
|
+
};
|
|
54
|
+
export interface DaemonSupervisorRequired {
|
|
55
|
+
spawnDaemonProcess: () => SpawnedDaemonProcess;
|
|
56
|
+
terminateProcess: (input: {
|
|
57
|
+
child: SpawnedDaemonProcess;
|
|
58
|
+
}) => void | Promise<void>;
|
|
59
|
+
policy: RespawnPolicy;
|
|
60
|
+
now: () => number;
|
|
61
|
+
scheduler: SupervisorScheduler;
|
|
62
|
+
classifyExit: (input: {
|
|
63
|
+
code: number | null;
|
|
64
|
+
signal: NodeJS.Signals | null;
|
|
65
|
+
}) => {
|
|
66
|
+
isPortConflict: boolean;
|
|
67
|
+
reason: string;
|
|
68
|
+
};
|
|
69
|
+
failureReporter: {
|
|
70
|
+
clear(): void;
|
|
71
|
+
record(input: {
|
|
72
|
+
reason: string;
|
|
73
|
+
}): void;
|
|
74
|
+
};
|
|
75
|
+
logger: {
|
|
76
|
+
emit(event: SupervisorEvent): void;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
export interface DaemonSupervisorOptions {
|
|
80
|
+
onDemandCooldownMs?: number;
|
|
81
|
+
quietRoutineLifecycle?: boolean;
|
|
82
|
+
formatGiveUp?: (input: {
|
|
83
|
+
decision: Extract<RespawnDecision, {
|
|
84
|
+
action: "give-up";
|
|
85
|
+
}>;
|
|
86
|
+
lastReason: string;
|
|
87
|
+
}) => string;
|
|
88
|
+
}
|
|
89
|
+
export interface DaemonSupervisorActionResult {
|
|
90
|
+
ok: boolean;
|
|
91
|
+
reason?: string;
|
|
92
|
+
}
|
|
93
|
+
export interface DaemonSupervisor {
|
|
94
|
+
start(): void;
|
|
95
|
+
restart(): DaemonSupervisorActionResult;
|
|
96
|
+
ensureStarted(): DaemonSupervisorActionResult;
|
|
97
|
+
shutdown(): void;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
|
|
101
|
+
* @param deps Required process, policy, clock, scheduler, readiness and observability ports.
|
|
102
|
+
* @param options On-demand cooldown, routine-event suppression and give-up message formatter.
|
|
103
|
+
* @returns Idempotent start, manual replacement, cooldown-limited recovery and terminal shutdown.
|
|
104
|
+
* @throws RangeError for a negative or non-finite cooldown.
|
|
105
|
+
* @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
|
|
106
|
+
*/
|
|
107
|
+
export declare function createDaemonSupervisor(deps: DaemonSupervisorRequired, options?: DaemonSupervisorOptions): DaemonSupervisor;
|
|
108
|
+
//# sourceMappingURL=supervisor.d.ts.map
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
function giveUpReason({ decision, lastReason }) {
|
|
2
|
+
if (decision.kind === "port-conflict")
|
|
3
|
+
return `gave up after ${decision.attempts} consecutive port conflicts: ${lastReason}`;
|
|
4
|
+
return `gave up after ${decision.attempts} attempts in ${Math.round(decision.windowMs / 1000)}s: ${lastReason}`;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
|
|
8
|
+
* @param deps Required process, policy, clock, scheduler, readiness and observability ports.
|
|
9
|
+
* @param options On-demand cooldown, routine-event suppression and give-up message formatter.
|
|
10
|
+
* @returns Idempotent start, manual replacement, cooldown-limited recovery and terminal shutdown.
|
|
11
|
+
* @throws RangeError for a negative or non-finite cooldown.
|
|
12
|
+
* @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
|
|
13
|
+
*/
|
|
14
|
+
export function createDaemonSupervisor(deps, options = {}) {
|
|
15
|
+
const cooldown = options.onDemandCooldownMs ?? 30000;
|
|
16
|
+
if (!Number.isFinite(cooldown) || cooldown < 0)
|
|
17
|
+
throw new RangeError("onDemandCooldownMs must be finite and non-negative");
|
|
18
|
+
const formatGiveUp = options.formatGiveUp ?? giveUpReason;
|
|
19
|
+
let current;
|
|
20
|
+
let cancelRetry;
|
|
21
|
+
// Terminal shutdown is a one-way latch, unlike a tripped retry cap. A restart racing
|
|
22
|
+
// host teardown must not resurrect a child that the host is actively trying to kill.
|
|
23
|
+
let terminating = false;
|
|
24
|
+
let spawnAttempts = 0;
|
|
25
|
+
let lastOnDemandAttemptAt;
|
|
26
|
+
function reportFailure(reason, decision) {
|
|
27
|
+
deps.failureReporter.record({ reason });
|
|
28
|
+
deps.logger.emit({ type: "failure", at: deps.now(), reason, ...(decision === undefined ? {} : { decision }) });
|
|
29
|
+
}
|
|
30
|
+
function cancelPendingRetry() { cancelRetry?.(); cancelRetry = undefined; }
|
|
31
|
+
function terminate(state) {
|
|
32
|
+
state.stopping = true;
|
|
33
|
+
function stopped() {
|
|
34
|
+
state.stopping = false;
|
|
35
|
+
if (current === state && state.exited && state.replaceAfterExit && !terminating)
|
|
36
|
+
attemptSpawn();
|
|
37
|
+
}
|
|
38
|
+
function failed(error) {
|
|
39
|
+
state.stopping = false;
|
|
40
|
+
state.replaceAfterExit = false;
|
|
41
|
+
if (current === state)
|
|
42
|
+
reportFailure(`failed to stop daemon: ${String(error)}`);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
const result = deps.terminateProcess({ child: state.child });
|
|
46
|
+
if (result !== undefined) {
|
|
47
|
+
void result.then(stopped, failed);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
stopped();
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
failed(error);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function handleUnexpectedExit(code, signal) {
|
|
57
|
+
const classification = deps.classifyExit({ code, signal });
|
|
58
|
+
reportFailure(classification.reason);
|
|
59
|
+
const decision = deps.policy.recordFailure({ isPortConflict: classification.isPortConflict });
|
|
60
|
+
if (decision.action === "give-up") {
|
|
61
|
+
reportFailure(formatGiveUp({ decision, lastReason: classification.reason }), decision);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
cancelRetry = deps.scheduler.schedule({ delayMs: decision.delayMs, run: () => { cancelRetry = undefined; attemptSpawn(); } });
|
|
65
|
+
}
|
|
66
|
+
function attemptSpawn() {
|
|
67
|
+
if (terminating || (current !== undefined && (!current.exited || current.stopping)))
|
|
68
|
+
return;
|
|
69
|
+
// A new attempt must not inherit a stale readiness failure from an earlier child.
|
|
70
|
+
deps.failureReporter.clear();
|
|
71
|
+
let child;
|
|
72
|
+
try {
|
|
73
|
+
child = deps.spawnDaemonProcess();
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
reportFailure(`failed to start daemon: ${error instanceof Error ? error.message : String(error)}`);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const state = { child, exited: false, deliberate: false, replaceAfterExit: false, stopping: false };
|
|
80
|
+
// Assign synchronously: run-to-completion makes request-driven recovery single-flight
|
|
81
|
+
// without a lock or an await between checking the current child and publishing it.
|
|
82
|
+
current = state;
|
|
83
|
+
// A respawn ends every run in flight. Timestamped lifecycle events let operators
|
|
84
|
+
// correlate apparently stalled work with a replacement, including deliberate exits
|
|
85
|
+
// when routine lifecycle logging is enabled.
|
|
86
|
+
spawnAttempts++;
|
|
87
|
+
if (!options.quietRoutineLifecycle || spawnAttempts > 1) {
|
|
88
|
+
deps.logger.emit({ type: "spawn", at: deps.now(), pid: child.pid, attempt: spawnAttempts });
|
|
89
|
+
}
|
|
90
|
+
// Missing scripts/permissions are not transient crashes: repeating the broken spawn
|
|
91
|
+
// on backoff only burns the retry cap. Manual or cooldown-limited recovery can try
|
|
92
|
+
// again after the underlying launch problem is repaired.
|
|
93
|
+
child.on({ event: "error", listener: ({ error }) => {
|
|
94
|
+
if (current !== state || state.exited)
|
|
95
|
+
return;
|
|
96
|
+
// Spawn failure has no pid and never emits exit. A live child's error may instead be a failed kill.
|
|
97
|
+
if (child.pid === undefined)
|
|
98
|
+
state.exited = true;
|
|
99
|
+
reportFailure(`failed to start daemon: ${error.message}`);
|
|
100
|
+
} });
|
|
101
|
+
child.on({ event: "exit", listener: ({ code, signal }) => {
|
|
102
|
+
if (current !== state || state.exited)
|
|
103
|
+
return;
|
|
104
|
+
state.exited = true;
|
|
105
|
+
if (!options.quietRoutineLifecycle || !state.deliberate) {
|
|
106
|
+
deps.logger.emit({ type: "exit", at: deps.now(), pid: child.pid, code, signal, deliberate: state.deliberate });
|
|
107
|
+
}
|
|
108
|
+
if (terminating)
|
|
109
|
+
return;
|
|
110
|
+
if (state.replaceAfterExit) {
|
|
111
|
+
if (!state.stopping)
|
|
112
|
+
attemptSpawn();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!state.deliberate)
|
|
116
|
+
handleUnexpectedExit(code, signal);
|
|
117
|
+
} });
|
|
118
|
+
}
|
|
119
|
+
// Wait for a still-live child to exit before replacement: spawning alongside it would
|
|
120
|
+
// collide on its listening port and manufacture the bind failure we are recovering from.
|
|
121
|
+
function forceFreshSpawn() {
|
|
122
|
+
if (current?.stopping) {
|
|
123
|
+
current.replaceAfterExit = true;
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (current !== undefined && !current.exited) {
|
|
127
|
+
if (current.replaceAfterExit)
|
|
128
|
+
return;
|
|
129
|
+
current.deliberate = true;
|
|
130
|
+
current.replaceAfterExit = true;
|
|
131
|
+
terminate(current);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
attemptSpawn();
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
start() { if (cancelRetry === undefined)
|
|
138
|
+
attemptSpawn(); },
|
|
139
|
+
restart() {
|
|
140
|
+
if (terminating)
|
|
141
|
+
return { ok: false, reason: "shutting down" };
|
|
142
|
+
cancelPendingRetry();
|
|
143
|
+
deps.policy.reset();
|
|
144
|
+
forceFreshSpawn();
|
|
145
|
+
return { ok: true };
|
|
146
|
+
},
|
|
147
|
+
ensureStarted() {
|
|
148
|
+
if (terminating)
|
|
149
|
+
return { ok: false, reason: "shutting down" };
|
|
150
|
+
// A scheduled retry keeps its own backoff; request traffic must not accelerate it.
|
|
151
|
+
if ((current !== undefined && (!current.exited || current.stopping)) || cancelRetry !== undefined)
|
|
152
|
+
return { ok: true };
|
|
153
|
+
// Single-flight alone cannot stop a storm against a durably broken launch. The 30s
|
|
154
|
+
// default floor matches the standard backoff ceiling, bounding traffic-driven retries
|
|
155
|
+
// to the same worst-case rate as timer-driven recovery after a cap or spawn failure.
|
|
156
|
+
const now = deps.now();
|
|
157
|
+
if (lastOnDemandAttemptAt !== undefined && now - lastOnDemandAttemptAt < cooldown)
|
|
158
|
+
return { ok: false, reason: "cooling down before trying again" };
|
|
159
|
+
lastOnDemandAttemptAt = now;
|
|
160
|
+
deps.policy.reset();
|
|
161
|
+
forceFreshSpawn();
|
|
162
|
+
return { ok: true };
|
|
163
|
+
},
|
|
164
|
+
shutdown() {
|
|
165
|
+
if (terminating)
|
|
166
|
+
return;
|
|
167
|
+
terminating = true;
|
|
168
|
+
cancelPendingRetry();
|
|
169
|
+
if (current === undefined)
|
|
170
|
+
return;
|
|
171
|
+
current.deliberate = true;
|
|
172
|
+
current.replaceAfterExit = false;
|
|
173
|
+
if (!current.exited && !current.stopping)
|
|
174
|
+
terminate(current);
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
//# sourceMappingURL=supervisor.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/sidecar",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
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.7.2",
|
|
67
|
+
"@jini-ai/platform": "0.7.2"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
|
-
"@jini-ai/core": "^0.7.
|
|
71
|
-
"@jini-ai/platform": "^0.7.
|
|
70
|
+
"@jini-ai/core": "^0.7.2",
|
|
71
|
+
"@jini-ai/platform": "^0.7.2"
|
|
72
72
|
},
|
|
73
73
|
"scripts": {
|
|
74
74
|
"build": "tsc -p tsconfig.json",
|