@jini-ai/sidecar 0.7.1 → 0.7.3-next.1
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 +1 -1
- package/dist/daemon-registry.d.ts +7 -5
- package/dist/daemon-registry.js +5 -5
- package/dist/index.d.ts +1 -1
- package/dist/ipc-path.d.ts +2 -2
- package/dist/ipc-path.js +2 -2
- package/dist/json-file.d.ts +11 -7
- package/dist/json-file.js +7 -8
- package/dist/json-ipc.d.ts +1 -18
- package/dist/json-ipc.js +11 -35
- package/dist/net.d.ts +7 -2
- package/dist/net.js +2 -2
- package/dist/paths.d.ts +11 -11
- package/dist/paths.js +11 -11
- package/dist/port.js +4 -4
- package/dist/supervision/child-entries.d.ts +85 -0
- package/dist/supervision/child-entries.js +139 -0
- package/dist/supervision/child-exit-signal.d.ts +21 -0
- package/dist/supervision/child-exit-signal.js +24 -0
- package/dist/supervision/child-orphans.d.ts +37 -0
- package/dist/supervision/child-orphans.js +48 -0
- package/dist/supervision/child-process-inspection.d.ts +29 -0
- package/dist/supervision/child-process-inspection.js +32 -0
- package/dist/supervision/child-readiness.d.ts +57 -0
- package/dist/supervision/child-readiness.js +83 -0
- package/dist/supervision/child-registry.d.ts +98 -0
- package/dist/supervision/child-registry.js +118 -0
- package/dist/supervision/child-stop.d.ts +39 -0
- package/dist/supervision/child-stop.js +81 -0
- package/dist/supervision/child-transitions.d.ts +54 -0
- package/dist/supervision/child-transitions.js +62 -0
- package/dist/supervision/keyed-serializer.d.ts +29 -0
- package/dist/supervision/keyed-serializer.js +50 -0
- package/dist/supervision/supervisor-node.d.ts +29 -11
- package/dist/supervision/supervisor-node.js +40 -29
- package/dist/supervision/supervisor.d.ts +3 -0
- package/dist/supervision/supervisor.js +312 -276
- package/package.json +4 -5
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { errorCodeOf } from "@jini-ai/core/primitives";
|
|
4
|
+
import { reconcileRows } from "./child-orphans.js";
|
|
5
|
+
/** One file per instance has one writer. The host supplies filename and codec policy.
|
|
6
|
+
* Reconciliation never rewrites a sibling's file: a row recorded during a grace window must survive.
|
|
7
|
+
* A recycled owner pid conservatively keeps the file, while per-row parentage still permits reaping.
|
|
8
|
+
* The registry does not fabricate handles for recovered children: no pipe exists to supervise them. */
|
|
9
|
+
export function createChildRegistry(required, _optional = {}) {
|
|
10
|
+
return new ChildRegistryStore(required);
|
|
11
|
+
}
|
|
12
|
+
class ChildRegistryStore {
|
|
13
|
+
deps;
|
|
14
|
+
constructor(deps) {
|
|
15
|
+
this.deps = deps;
|
|
16
|
+
}
|
|
17
|
+
/** Missing is empty; a directory that cannot be listed contains UNKNOWN rows. */
|
|
18
|
+
listInstanceFiles({ registryDir }, _optional = {}) {
|
|
19
|
+
let names;
|
|
20
|
+
try {
|
|
21
|
+
names = fs.readdirSync(registryDir);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
return errorCodeOf({ error }) === "ENOENT" ? [] : null;
|
|
25
|
+
}
|
|
26
|
+
return names.flatMap(name => {
|
|
27
|
+
const parsed = this.deps.parseInstanceName({ name });
|
|
28
|
+
return parsed ? [{ filePath: path.join(registryDir, name), ...parsed }] : [];
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** Include legacy rows: older hosts remain writers of that shared file.
|
|
32
|
+
* Files that disappear after listing are absent; unreadable rows are unknown, never empty. */
|
|
33
|
+
read({ registryDir }, _optional = {}) {
|
|
34
|
+
const files = this.listInstanceFiles({ registryDir });
|
|
35
|
+
const snapshot = { rows: [], unreadable: files === null ? [registryDir] : [] };
|
|
36
|
+
for (const filePath of [...(files ?? []).map(file => file.filePath), this.deps.legacyPath({ registryDir })]) {
|
|
37
|
+
const read = this.deps.storage.read({ filePath });
|
|
38
|
+
if (read.state === "ok")
|
|
39
|
+
snapshot.rows.push(...read.rows);
|
|
40
|
+
if (read.state === "unreadable")
|
|
41
|
+
snapshot.unreadable.push(filePath);
|
|
42
|
+
}
|
|
43
|
+
return snapshot;
|
|
44
|
+
}
|
|
45
|
+
/** Preserve damaged bytes before recording a just-started/stopped child. Refusal leaves that
|
|
46
|
+
* child unrecorded, but throwing would strand its live handle; a failed quarantine forbids writing. */
|
|
47
|
+
readOwnRowsForUpdate({ filePath }, { quarantine = this.deps.storage.quarantine } = {}) {
|
|
48
|
+
const read = this.deps.storage.read({ filePath });
|
|
49
|
+
if (read.state === "ok")
|
|
50
|
+
return read.rows;
|
|
51
|
+
if (read.state === "missing")
|
|
52
|
+
return [];
|
|
53
|
+
return quarantine({ filePath }) ? [] : null;
|
|
54
|
+
}
|
|
55
|
+
/** Refuse to replace a live same-key row: a closed window may still have a draining child.
|
|
56
|
+
* Only proven-dead or recycled identities can be displaced, or a hard host kill would strand them. */
|
|
57
|
+
recordOpened({ registryDir, row }, { instanceId = this.deps.instanceId, isLiveRow = this.deps.processes.isLiveRow } = {}) {
|
|
58
|
+
const filePath = this.deps.storage.instancePath({ registryDir, instanceId });
|
|
59
|
+
const rows = this.readOwnRowsForUpdate({ filePath });
|
|
60
|
+
if (rows === null)
|
|
61
|
+
return;
|
|
62
|
+
const retained = rows.filter(existing => this.deps.keyOf({ row: existing }) !== this.deps.keyOf({ row }) || isLiveRow({ row: existing }));
|
|
63
|
+
this.deps.storage.write({ filePath, rows: [row, ...retained] });
|
|
64
|
+
}
|
|
65
|
+
/** A replacement and its draining predecessor may share a key: close only the supplied pid.
|
|
66
|
+
* Omitting pid retains the original forget-all-rows-for-this-key behavior. */
|
|
67
|
+
recordClosed({ registryDir, key }, { pid, instanceId = this.deps.instanceId, quarantine } = {}) {
|
|
68
|
+
const filePath = this.deps.storage.instancePath({ registryDir, instanceId });
|
|
69
|
+
const rows = this.readOwnRowsForUpdate({ filePath }, { quarantine });
|
|
70
|
+
if (rows === null)
|
|
71
|
+
return;
|
|
72
|
+
const isDoomed = (existing) => this.deps.keyOf({ row: existing }) === key && (pid === undefined || existing.pid === pid);
|
|
73
|
+
this.deps.storage.write({ filePath, rows: rows.filter(existing => !isDoomed(existing)) });
|
|
74
|
+
}
|
|
75
|
+
/** Run before creating host windows. Only dead owners permit file removal; own files are skipped.
|
|
76
|
+
* Parentage is proved per row, since a live sibling's child exactly matches its own argv. */
|
|
77
|
+
async reconcileOrphans({ registryDir }, { instanceId = this.deps.instanceId } = {}) {
|
|
78
|
+
const files = this.listInstanceFiles({ registryDir });
|
|
79
|
+
if (files === null)
|
|
80
|
+
this.deps.report({ type: "list-failed", registryDir });
|
|
81
|
+
const reconciled = [];
|
|
82
|
+
for (const file of files ?? []) {
|
|
83
|
+
if (file.instanceId === instanceId)
|
|
84
|
+
continue;
|
|
85
|
+
reconciled.push(...await this.reconcileInstanceFile({ file }));
|
|
86
|
+
}
|
|
87
|
+
reconciled.push(...await this.reconcileLegacyFile({ legacyPath: this.deps.legacyPath({ registryDir }) }));
|
|
88
|
+
return reconciled;
|
|
89
|
+
}
|
|
90
|
+
/** Never touch a live owner's unreadable file; its own next write owns quarantine.
|
|
91
|
+
* Native dead-file cleanup (including dangling links and owner-specific temp files) is host-owned. */
|
|
92
|
+
async reconcileInstanceFile({ file }, _optional = {}) {
|
|
93
|
+
const ownerGone = !this.deps.processes.isAlive({ pid: file.ownerPid });
|
|
94
|
+
const read = this.deps.storage.read({ filePath: file.filePath });
|
|
95
|
+
if (read.state === "unreadable") {
|
|
96
|
+
if (ownerGone)
|
|
97
|
+
this.deps.storage.quarantine({ filePath: file.filePath });
|
|
98
|
+
else
|
|
99
|
+
this.deps.report({ type: "live-owner-unreadable", filePath: file.filePath, ownerPid: file.ownerPid });
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
const reconciled = read.state === "ok" ? await reconcileRows({ rows: read.rows, processes: this.deps.processes }) : [];
|
|
103
|
+
if (ownerGone)
|
|
104
|
+
this.deps.storage.removeDeadFile({ filePath: file.filePath, ownerPid: file.ownerPid });
|
|
105
|
+
return reconciled;
|
|
106
|
+
}
|
|
107
|
+
/** Legacy files remain read-only because older hosts still write them. Quarantine preserves torn
|
|
108
|
+
* bytes and stops repeatedly processing the same damage. */
|
|
109
|
+
async reconcileLegacyFile({ legacyPath }, _optional = {}) {
|
|
110
|
+
const read = this.deps.storage.read({ filePath: legacyPath });
|
|
111
|
+
if (read.state === "unreadable") {
|
|
112
|
+
this.deps.storage.quarantine({ filePath: legacyPath });
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
return read.state === "ok" ? reconcileRows({ rows: read.rows, processes: this.deps.processes }) : [];
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=child-registry.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Writable } from "node:stream";
|
|
2
|
+
/** Native structural surface, so hosts and test doubles need no casts to ChildProcess. */
|
|
3
|
+
export interface StoppableChild {
|
|
4
|
+
pid?: number | undefined;
|
|
5
|
+
stdin?: Writable | null;
|
|
6
|
+
exitCode: number | null;
|
|
7
|
+
signalCode: NodeJS.Signals | null;
|
|
8
|
+
kill(signal?: NodeJS.Signals | number): boolean;
|
|
9
|
+
once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown;
|
|
10
|
+
removeListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown;
|
|
11
|
+
}
|
|
12
|
+
export type ChildStopFailure = {
|
|
13
|
+
type: "timeout";
|
|
14
|
+
pid: number | undefined;
|
|
15
|
+
graceMs: number;
|
|
16
|
+
} | {
|
|
17
|
+
type: "missing-pid";
|
|
18
|
+
phase: "windows-tree" | "force";
|
|
19
|
+
};
|
|
20
|
+
export interface ChildStopRequired {
|
|
21
|
+
child: StoppableChild;
|
|
22
|
+
graceMs: number;
|
|
23
|
+
killTree(required: {
|
|
24
|
+
pid: number;
|
|
25
|
+
}): void;
|
|
26
|
+
describeFailure(required: ChildStopFailure): string;
|
|
27
|
+
}
|
|
28
|
+
export interface ChildStopOptions {
|
|
29
|
+
platform?: NodeJS.Platform;
|
|
30
|
+
forceGroup?: (required: {
|
|
31
|
+
pid: number;
|
|
32
|
+
}) => void;
|
|
33
|
+
}
|
|
34
|
+
/** Resolve only after actual exit, even when force was accepted or a signal failed.
|
|
35
|
+
* A second grace window bounds forced-exit confirmation; callers must retain recovery rows on
|
|
36
|
+
* failure. The most recent signal error remains the timeout cause, including ESRCH races.
|
|
37
|
+
* @complexity O(1) state, waiting at most twice graceMs. */
|
|
38
|
+
export declare function stopSpawnedChild(required: ChildStopRequired, { platform, forceGroup }?: ChildStopOptions): Promise<void>;
|
|
39
|
+
//# sourceMappingURL=child-stop.d.ts.map
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { orFallbackSync } from "@jini-ai/core/errors/idioms";
|
|
2
|
+
function forceProcessGroup({ pid }, _optional = {}) {
|
|
3
|
+
process.kill(-pid, "SIGKILL");
|
|
4
|
+
}
|
|
5
|
+
/** Windows ignores signal names and terminates the immediate child, which would cancel escalation
|
|
6
|
+
* and orphan descendants if done first. Without stdin EOF, tree kill must be the first request.
|
|
7
|
+
* A missing native command or disappearing pid falls back to killing only the direct child. */
|
|
8
|
+
function killWin32Tree({ child, killTree, describeFailure }, _optional = {}) {
|
|
9
|
+
if (child.pid == null)
|
|
10
|
+
throw new Error(describeFailure({ type: "missing-pid", phase: "windows-tree" }));
|
|
11
|
+
const killed = orFallbackSync({ work: () => { killTree({ pid: child.pid }); return true; }, fallback: false, step: "stop-child-windows-tree" });
|
|
12
|
+
if (!killed)
|
|
13
|
+
child.kill("SIGTERM");
|
|
14
|
+
}
|
|
15
|
+
/** Closing stdin asks the Windows child to drain. An EPIPE if it exited first must not become an
|
|
16
|
+
* unhandled stream error. POSIX SIGTERM reaches the child's own graceful descendant cleanup. */
|
|
17
|
+
function requestGracefulStop({ request, platform }, _optional = {}) {
|
|
18
|
+
const { child } = request;
|
|
19
|
+
if (platform === "win32") {
|
|
20
|
+
if (child.stdin)
|
|
21
|
+
child.stdin.once("error", () => undefined).end();
|
|
22
|
+
else
|
|
23
|
+
killWin32Tree(request);
|
|
24
|
+
}
|
|
25
|
+
else
|
|
26
|
+
child.kill("SIGTERM");
|
|
27
|
+
}
|
|
28
|
+
/** A wedged child has not drained its descendants: force targets its whole POSIX group or Windows
|
|
29
|
+
* tree. Without a Windows stdin pipe, the initial request already attempted the whole tree. */
|
|
30
|
+
function requestForcedStop({ request, platform, forceGroup }, _optional = {}) {
|
|
31
|
+
const { child, describeFailure } = request;
|
|
32
|
+
if (platform === "win32") {
|
|
33
|
+
if (child.stdin)
|
|
34
|
+
killWin32Tree(request);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
// Stop normally receives an already-spawned child, so a missing pid is a failure.
|
|
38
|
+
if (child.pid == null)
|
|
39
|
+
throw new Error(describeFailure({ type: "missing-pid", phase: "force" }));
|
|
40
|
+
forceGroup({ pid: child.pid });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Resolve only after actual exit, even when force was accepted or a signal failed.
|
|
44
|
+
* A second grace window bounds forced-exit confirmation; callers must retain recovery rows on
|
|
45
|
+
* failure. The most recent signal error remains the timeout cause, including ESRCH races.
|
|
46
|
+
* @complexity O(1) state, waiting at most twice graceMs. */
|
|
47
|
+
export function stopSpawnedChild(required, { platform = process.platform, forceGroup = forceProcessGroup } = {}) {
|
|
48
|
+
const { child, graceMs, describeFailure } = required;
|
|
49
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
50
|
+
return Promise.resolve();
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
let exitTimer;
|
|
53
|
+
let signalError;
|
|
54
|
+
const timer = setTimeout(() => {
|
|
55
|
+
// Arm confirmation before signalling: a synchronous exit must cancel both timers.
|
|
56
|
+
exitTimer = setTimeout(() => {
|
|
57
|
+
child.removeListener("exit", onExit);
|
|
58
|
+
reject(new Error(describeFailure({ type: "timeout", pid: child.pid, graceMs }), { cause: signalError }));
|
|
59
|
+
}, graceMs);
|
|
60
|
+
try {
|
|
61
|
+
requestForcedStop({ request: required, platform, forceGroup });
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
signalError = error;
|
|
65
|
+
}
|
|
66
|
+
}, graceMs);
|
|
67
|
+
const onExit = () => {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
clearTimeout(exitTimer);
|
|
70
|
+
resolve();
|
|
71
|
+
};
|
|
72
|
+
child.once("exit", onExit);
|
|
73
|
+
try {
|
|
74
|
+
requestGracefulStop({ request: required, platform });
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
signalError = error;
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=child-stop.js.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The one holder of "which site dirs are MID-TRANSITION right now" — the fact `openSites`
|
|
3
|
+
* cannot express and the Projects screen needs to stop lying with.
|
|
4
|
+
*
|
|
5
|
+
* `child-entries.ts` answers "is this site's child server alive". That is a two-valued answer, and
|
|
6
|
+
* the host snapshot builder (the host lifecycle handler) turned it straight into `running` or `stopped`. Both of a
|
|
7
|
+
* site's lifecycle transitions take real wall-clock time — a boot is seconds, a graceful stop is a
|
|
8
|
+
* SIGTERM plus however long the child takes to drain — and during either one the two-valued answer
|
|
9
|
+
* is wrong in the direction the operator can see:
|
|
10
|
+
*
|
|
11
|
+
* - a site being started reads `stopped` for the whole boot, so a Start button they just pressed
|
|
12
|
+
* looks like it did nothing, and they press it again;
|
|
13
|
+
* - a site being stopped reads `running` until the child is gone, so a Stop button looks the same.
|
|
14
|
+
*
|
|
15
|
+
* the host lifecycle contract has declared `starting` and `stopping` in `SiteLifecycleStatus` since the
|
|
16
|
+
* port; nothing had ever been able to produce them. This is what produces them.
|
|
17
|
+
*
|
|
18
|
+
* **Not folded into the supervisor**, though the two are read together. The supervisor's entries are
|
|
19
|
+
* owned by the child process — it learns about them from `set`/`delete` and from the child's own
|
|
20
|
+
* `exit`. These are owned by an IPC handler's call stack: they exist exactly while a `handleStart`
|
|
21
|
+
* or `handleStop` body is awaiting, and their correctness rule is a `finally`, not a lifecycle
|
|
22
|
+
* event. Merging them would put two different ownership models behind one `get`.
|
|
23
|
+
*
|
|
24
|
+
* No `electron` import, so all of it is testable under plain `node --test` — same convention as
|
|
25
|
+
* `child-entries.ts`, the directory registry and the directory delete guard.
|
|
26
|
+
*/
|
|
27
|
+
/** Which lifecycle transition a site is in the middle of. Both are `SiteLifecycleStatus` members
|
|
28
|
+
* verbatim (the host lifecycle contract), so a reader can use the value as the status directly. */
|
|
29
|
+
type ChildTransition = "starting" | "stopping";
|
|
30
|
+
/** What {@link createChildTransitions} returns. */
|
|
31
|
+
interface ChildTransitions {
|
|
32
|
+
/**
|
|
33
|
+
* Mark `key` as mid-`transition`, run `body`, and unmark it — whether `body` resolves or
|
|
34
|
+
* rejects. The unmark is the whole contract: a start that fails must leave the card `stopped`,
|
|
35
|
+
* not `starting` forever.
|
|
36
|
+
*/
|
|
37
|
+
during<T>({ key, transition, body }: {
|
|
38
|
+
key: string;
|
|
39
|
+
transition: ChildTransition;
|
|
40
|
+
body: () => Promise<T>;
|
|
41
|
+
}, optional?: Record<string, never>): Promise<T>;
|
|
42
|
+
/** The transition `key` is in the middle of, or `null`. */
|
|
43
|
+
get({ key }: {
|
|
44
|
+
key: string;
|
|
45
|
+
}, optional?: Record<string, never>): ChildTransition | null;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* @returns an empty transition store.
|
|
49
|
+
* @complexity O(1) to construct.
|
|
50
|
+
*/
|
|
51
|
+
declare function createChildTransitions(_required: Record<string, never>, _optional?: Record<string, never>): ChildTransitions;
|
|
52
|
+
export { createChildTransitions };
|
|
53
|
+
export type { ChildTransition, ChildTransitions };
|
|
54
|
+
//# sourceMappingURL=child-transitions.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The one holder of "which site dirs are MID-TRANSITION right now" — the fact `openSites`
|
|
3
|
+
* cannot express and the Projects screen needs to stop lying with.
|
|
4
|
+
*
|
|
5
|
+
* `child-entries.ts` answers "is this site's child server alive". That is a two-valued answer, and
|
|
6
|
+
* the host snapshot builder (the host lifecycle handler) turned it straight into `running` or `stopped`. Both of a
|
|
7
|
+
* site's lifecycle transitions take real wall-clock time — a boot is seconds, a graceful stop is a
|
|
8
|
+
* SIGTERM plus however long the child takes to drain — and during either one the two-valued answer
|
|
9
|
+
* is wrong in the direction the operator can see:
|
|
10
|
+
*
|
|
11
|
+
* - a site being started reads `stopped` for the whole boot, so a Start button they just pressed
|
|
12
|
+
* looks like it did nothing, and they press it again;
|
|
13
|
+
* - a site being stopped reads `running` until the child is gone, so a Stop button looks the same.
|
|
14
|
+
*
|
|
15
|
+
* the host lifecycle contract has declared `starting` and `stopping` in `SiteLifecycleStatus` since the
|
|
16
|
+
* port; nothing had ever been able to produce them. This is what produces them.
|
|
17
|
+
*
|
|
18
|
+
* **Not folded into the supervisor**, though the two are read together. The supervisor's entries are
|
|
19
|
+
* owned by the child process — it learns about them from `set`/`delete` and from the child's own
|
|
20
|
+
* `exit`. These are owned by an IPC handler's call stack: they exist exactly while a `handleStart`
|
|
21
|
+
* or `handleStop` body is awaiting, and their correctness rule is a `finally`, not a lifecycle
|
|
22
|
+
* event. Merging them would put two different ownership models behind one `get`.
|
|
23
|
+
*
|
|
24
|
+
* No `electron` import, so all of it is testable under plain `node --test` — same convention as
|
|
25
|
+
* `child-entries.ts`, the directory registry and the directory delete guard.
|
|
26
|
+
*/
|
|
27
|
+
/**
|
|
28
|
+
* @returns an empty transition store.
|
|
29
|
+
* @complexity O(1) to construct.
|
|
30
|
+
*/
|
|
31
|
+
function createChildTransitions(_required, _optional = {}) {
|
|
32
|
+
/**
|
|
33
|
+
* Site dir -> the marker object for the transition currently running on it.
|
|
34
|
+
*
|
|
35
|
+
* The stored value is a fresh object per call rather than the bare string so {@link during}'s
|
|
36
|
+
* `finally` can check IDENTITY before clearing — the same rule, and for the same reason, as
|
|
37
|
+
* `child-entries.ts`'s `handleExit`. the host lifecycle handler serializes start and stop per site dir,
|
|
38
|
+
* so overlapping transitions on one site should not happen; "should not happen" is not a reason
|
|
39
|
+
* for a later transition's mark to be cleared by an earlier one's unwind if it ever does.
|
|
40
|
+
*/
|
|
41
|
+
const active = new Map();
|
|
42
|
+
return {
|
|
43
|
+
/** @complexity O(1) beyond `body`'s own cost. */
|
|
44
|
+
async during({ key, transition, body }, _optional = {}) {
|
|
45
|
+
const marker = { transition };
|
|
46
|
+
active.set(key, marker);
|
|
47
|
+
try {
|
|
48
|
+
return await body();
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
if (active.get(key) === marker)
|
|
52
|
+
active.delete(key);
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
/** @complexity O(1). */
|
|
56
|
+
get({ key }, _optional = {}) {
|
|
57
|
+
return active.get(key)?.transition ?? null;
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export { createChildTransitions };
|
|
62
|
+
//# sourceMappingURL=child-transitions.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Per-key promise chaining, so two calls for the SAME key never race — the host's
|
|
3
|
+
* existing per-project serialization pattern, generalized: this file has no
|
|
4
|
+
* notion of a "project", just a string key and a function to chain.
|
|
5
|
+
*
|
|
6
|
+
* Multiple keys reintroduce exactly the race the host built that pattern for: with one site and one
|
|
7
|
+
* button, a double-click could only ever double-spawn the same single child. With N sites, each
|
|
8
|
+
* exposed through its own menu entry (open, or open-recent), the same double-click risk reappears
|
|
9
|
+
* per site — this closes it generically rather than needing a guard duplicated at every call site
|
|
10
|
+
* (the host's open-window and open-new-directory operations).
|
|
11
|
+
*
|
|
12
|
+
* Calls for DIFFERENT keys are never serialized against each other — opening site A must not wait on
|
|
13
|
+
* site B's own in-flight open.
|
|
14
|
+
*/
|
|
15
|
+
/** What {@link createKeyedSerializer} returns. */
|
|
16
|
+
interface KeyedSerializer {
|
|
17
|
+
run<T>({ key, fn }: {
|
|
18
|
+
key: string;
|
|
19
|
+
fn: () => T | PromiseLike<T>;
|
|
20
|
+
}, optional?: Record<string, never>): Promise<T>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* @returns `{ run({ key, fn }) }` — a fresh, independent chain store.
|
|
24
|
+
* @complexity O(1) to construct.
|
|
25
|
+
*/
|
|
26
|
+
declare function createKeyedSerializer(_required: Record<string, never>, _optional?: Record<string, never>): KeyedSerializer;
|
|
27
|
+
export { createKeyedSerializer };
|
|
28
|
+
export type { KeyedSerializer };
|
|
29
|
+
//# sourceMappingURL=keyed-serializer.d.ts.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Per-key promise chaining, so two calls for the SAME key never race — the host's
|
|
3
|
+
* existing per-project serialization pattern, generalized: this file has no
|
|
4
|
+
* notion of a "project", just a string key and a function to chain.
|
|
5
|
+
*
|
|
6
|
+
* Multiple keys reintroduce exactly the race the host built that pattern for: with one site and one
|
|
7
|
+
* button, a double-click could only ever double-spawn the same single child. With N sites, each
|
|
8
|
+
* exposed through its own menu entry (open, or open-recent), the same double-click risk reappears
|
|
9
|
+
* per site — this closes it generically rather than needing a guard duplicated at every call site
|
|
10
|
+
* (the host's open-window and open-new-directory operations).
|
|
11
|
+
*
|
|
12
|
+
* Calls for DIFFERENT keys are never serialized against each other — opening site A must not wait on
|
|
13
|
+
* site B's own in-flight open.
|
|
14
|
+
*/
|
|
15
|
+
import { afterSettled } from "@jini-ai/core/errors/idioms";
|
|
16
|
+
/**
|
|
17
|
+
* @returns `{ run({ key, fn }) }` — a fresh, independent chain store.
|
|
18
|
+
* @complexity O(1) to construct.
|
|
19
|
+
*/
|
|
20
|
+
function createKeyedSerializer(_required, _optional = {}) {
|
|
21
|
+
const chains = new Map();
|
|
22
|
+
/**
|
|
23
|
+
* Run `fn` only after every previously-queued call for THIS key has settled — a prior call's
|
|
24
|
+
* failure never blocks the next one in line (`afterSettled` observes it before chaining `fn`
|
|
25
|
+
* on; `fn`'s own rejection still propagates to ITS caller via the returned promise).
|
|
26
|
+
*
|
|
27
|
+
* @returns `fn`'s own resolution or rejection.
|
|
28
|
+
* @complexity O(1) scheduling cost; `fn`'s own cost is the caller's.
|
|
29
|
+
*/
|
|
30
|
+
function run({ key, fn }, _optional = {}) {
|
|
31
|
+
const previous = chains.get(key) ?? Promise.resolve();
|
|
32
|
+
const next = afterSettled({ promise: previous }).then(fn);
|
|
33
|
+
chains.set(key, next);
|
|
34
|
+
const clearSlot = () => {
|
|
35
|
+
// Only clear the slot if nothing queued behind this call while it was running — otherwise a
|
|
36
|
+
// later `run()` for the same key already replaced it and clearing here would drop that entry.
|
|
37
|
+
if (chains.get(key) === next)
|
|
38
|
+
chains.delete(key);
|
|
39
|
+
};
|
|
40
|
+
// `.then(clearSlot, clearSlot)`, not `.finally()`: `.finally()`'s own returned promise re-throws
|
|
41
|
+
// `next`'s rejection and nothing observes THAT derived promise, which Node reports as an
|
|
42
|
+
// unhandled rejection even though `next` itself (what the caller awaits) is handled correctly.
|
|
43
|
+
// Passing `clearSlot` as both reactions produces a promise that always resolves instead.
|
|
44
|
+
next.then(clearSlot, clearSlot);
|
|
45
|
+
return next;
|
|
46
|
+
}
|
|
47
|
+
return { run };
|
|
48
|
+
}
|
|
49
|
+
export { createKeyedSerializer };
|
|
50
|
+
//# sourceMappingURL=keyed-serializer.js.map
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { Writable } from "node:stream";
|
|
2
2
|
import type { ChildProcess, SpawnOptions } from "node:child_process";
|
|
3
3
|
import type { Serializable } from "node:child_process";
|
|
4
|
-
import {
|
|
4
|
+
import { type ProcessControlPort, type RuntimePlatform } from "@jini-ai/core/contracts/runtime";
|
|
5
|
+
import type { JsonFileWriter } from "../json-file.js";
|
|
5
6
|
import type { LocalDaemonRegistryRecord } from "../daemon-registry.js";
|
|
6
7
|
import type { SpawnedDaemonProcess, SupervisorScheduler } from "./supervisor.js";
|
|
7
8
|
export interface SupervisorRegistry {
|
|
@@ -16,19 +17,29 @@ export interface SupervisorRegistry {
|
|
|
16
17
|
/**
|
|
17
18
|
* Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
|
|
18
19
|
* The child calls write only after it actually starts listening.
|
|
19
|
-
* @param required Host-owned registry path.
|
|
20
|
+
* @param required Host-owned registry path and the host's atomic JSON writer.
|
|
20
21
|
* @returns A registry port with object arguments at all data-bearing boundaries.
|
|
21
22
|
* @complexity O(1) operations, excluding filesystem I/O.
|
|
22
23
|
*/
|
|
23
|
-
export declare function createSupervisorRegistry({ registryPath }: {
|
|
24
|
+
export declare function createSupervisorRegistry({ registryPath, writer }: {
|
|
24
25
|
registryPath: string;
|
|
25
|
-
|
|
26
|
+
writer: JsonFileWriter;
|
|
27
|
+
}, _optional?: Record<string, never>): SupervisorRegistry;
|
|
26
28
|
export interface NodeDaemonProcessRequired {
|
|
27
29
|
command: string;
|
|
28
30
|
args: readonly string[];
|
|
29
31
|
cwd: string;
|
|
30
32
|
env: NodeJS.ProcessEnv;
|
|
31
33
|
registry: SupervisorRegistry;
|
|
34
|
+
/** The host's process control (snapshots, tree stop, exit wait); Node hosts pass `nodeProcessControl` of `@jini-ai/node-adapters/process`. */
|
|
35
|
+
process: ProcessControlPort;
|
|
36
|
+
/** The two host inputs of core's pure command planner: the platform and the `ComSpec` a Windows `.cmd` shim falls back to
|
|
37
|
+
* when the launch env has none. Node hosts pass `nodeCommandShell({ env: process.env })` of `@jini-ai/node-adapters/process`,
|
|
38
|
+
* which is what the platform builder read before. */
|
|
39
|
+
commandShell: {
|
|
40
|
+
readonly platform: RuntimePlatform;
|
|
41
|
+
readonly fallbackComSpec?: string | undefined;
|
|
42
|
+
};
|
|
32
43
|
}
|
|
33
44
|
export interface NodeDaemonProcessOptions {
|
|
34
45
|
/** Inherit a separate native control channel; stdin remains the Windows EOF shutdown pipe. */
|
|
@@ -44,18 +55,14 @@ export interface NodeDaemonProcessOptions {
|
|
|
44
55
|
args: string[];
|
|
45
56
|
options: SpawnOptions;
|
|
46
57
|
}, optional?: Record<string, never>) => ChildProcess;
|
|
47
|
-
/** Native effect ports retain their platform ABI so tests can supply DI fakes. */
|
|
48
|
-
listProcessSnapshots?: typeof listProcessSnapshots;
|
|
49
|
-
waitForProcessExit?: typeof waitForProcessExit;
|
|
50
|
-
stopProcesses?: typeof stopProcesses;
|
|
51
58
|
signalProcess?: typeof process.kill;
|
|
52
59
|
execFileSync?: (file: string, args: readonly string[], options: {
|
|
53
60
|
stdio: "ignore";
|
|
54
61
|
}) => unknown;
|
|
55
62
|
}
|
|
56
63
|
/**
|
|
57
|
-
* Node launch/tree-stop adapter
|
|
58
|
-
* @param required Complete host launch settings
|
|
64
|
+
* Node launch/tree-stop adapter: core's command planner, the host's process control port and signal escalation.
|
|
65
|
+
* @param required Complete host launch settings, the shared sidecar registry port, the process control port and the command shell.
|
|
59
66
|
* @param options Optional native spawn port and sinks; output is piped through the parent rather than inherited.
|
|
60
67
|
* @returns Supervisor process ports. Construction has no process or filesystem effects.
|
|
61
68
|
* @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
|
|
@@ -72,7 +79,7 @@ export declare function createNodeDaemonProcessAdapter(required: NodeDaemonProce
|
|
|
72
79
|
* @returns Scheduler using setTimeout and clearTimeout.
|
|
73
80
|
* @complexity O(1) per schedule/cancel.
|
|
74
81
|
*/
|
|
75
|
-
export declare function createNodeSupervisorScheduler(_required: Record<string, never>): SupervisorScheduler;
|
|
82
|
+
export declare function createNodeSupervisorScheduler(_required: Record<string, never>, _optional?: Record<string, never>): SupervisorScheduler;
|
|
76
83
|
/** A channel bound to one native child (or its process end), never an address supplied by a caller. */
|
|
77
84
|
export interface NodeIpcPeer {
|
|
78
85
|
readonly connected?: boolean;
|
|
@@ -146,4 +153,15 @@ export declare function receiveNodeStartupSecrets({ peer }: {
|
|
|
146
153
|
}, { timeoutMs, }?: {
|
|
147
154
|
timeoutMs?: number;
|
|
148
155
|
}): Promise<Record<string, string>>;
|
|
156
|
+
export { createChildRegistry } from "./child-registry.js";
|
|
157
|
+
export type { ChildRegistry, ChildRegistryRequired, ChildRegistryStorage, ChildRegistryRead, ChildRegistrySnapshot, ChildRegistryReport } from "./child-registry.js";
|
|
158
|
+
export type { ChildRegistryProcesses } from "./child-orphans.js";
|
|
159
|
+
export { createChildProcessInspection } from "./child-process-inspection.js";
|
|
160
|
+
export type { ChildProcessInspection, ChildProcessInspectionRequired } from "./child-process-inspection.js";
|
|
161
|
+
export { waitForChildReady } from "./child-readiness.js";
|
|
162
|
+
export type { ReadinessChild, ChildReadinessFailure, ChildReadinessOutputSink, ChildReadinessRequired } from "./child-readiness.js";
|
|
163
|
+
export { stopSpawnedChild } from "./child-stop.js";
|
|
164
|
+
export type { StoppableChild, ChildStopFailure, ChildStopRequired, ChildStopOptions } from "./child-stop.js";
|
|
165
|
+
export { createChildExitSignal } from "./child-exit-signal.js";
|
|
166
|
+
export type { ChildExitSignal, ChildExitOutcome, ExitSignalChild } from "./child-exit-signal.js";
|
|
149
167
|
//# sourceMappingURL=supervisor-node.d.ts.map
|