@jini-ai/sidecar 0.1.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/README.md +132 -0
- package/dist/bootstrap.d.ts +6 -3
- package/dist/bootstrap.js +9 -14
- package/dist/daemon-registry.d.ts +20 -6
- package/dist/daemon-registry.js +38 -12
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/ipc-path.d.ts +6 -2
- package/dist/ipc-path.js +3 -3
- package/dist/json-file.d.ts +17 -6
- package/dist/json-file.js +16 -14
- package/dist/json-ipc.d.ts +12 -4
- package/dist/json-ipc.js +15 -15
- package/dist/paths.d.ts +10 -7
- package/dist/paths.js +15 -15
- package/dist/port.d.ts +10 -2
- package/dist/port.js +5 -5
- package/dist/respawn-policy.d.ts +51 -0
- package/dist/respawn-policy.js +46 -0
- package/dist/supervisor-node.d.ts +55 -0
- package/dist/supervisor-node.js +95 -0
- package/dist/supervisor.d.ts +106 -0
- package/dist/supervisor.js +178 -0
- package/dist/types.d.ts +32 -12
- package/package.json +32 -5
- package/dist/bootstrap.d.ts.map +0 -1
- package/dist/bootstrap.js.map +0 -1
- package/dist/daemon-registry.d.ts.map +0 -1
- package/dist/daemon-registry.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/ipc-path.d.ts.map +0 -1
- package/dist/ipc-path.js.map +0 -1
- package/dist/json-file.d.ts.map +0 -1
- package/dist/json-file.js.map +0 -1
- package/dist/json-ipc.d.ts.map +0 -1
- package/dist/json-ipc.js.map +0 -1
- package/dist/net.d.ts.map +0 -1
- package/dist/net.js.map +0 -1
- package/dist/paths.d.ts.map +0 -1
- package/dist/paths.js.map +0 -1
- package/dist/port.d.ts.map +0 -1
- package/dist/port.js.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
package/dist/json-ipc.d.ts
CHANGED
|
@@ -22,7 +22,9 @@ import type { JsonIpcHandler, JsonIpcServerHandle } from "./types.js";
|
|
|
22
22
|
* hand today — matching this repo's "extract into a directly-testable pure
|
|
23
23
|
* function" convention rather than narrowing the type away.
|
|
24
24
|
*/
|
|
25
|
-
export declare function jsonIpcError(error
|
|
25
|
+
export declare function jsonIpcError({ error }: {
|
|
26
|
+
error: unknown;
|
|
27
|
+
}): {
|
|
26
28
|
code?: string;
|
|
27
29
|
message: string;
|
|
28
30
|
};
|
|
@@ -38,16 +40,19 @@ export declare function jsonIpcError(error: unknown): {
|
|
|
38
40
|
* Windows. Testing this function directly (asserting no filesystem call
|
|
39
41
|
* happens) verifies the real behavior on every platform this runs on.
|
|
40
42
|
*/
|
|
41
|
-
export declare function prepareIpcPath(socketPath
|
|
43
|
+
export declare function prepareIpcPath({ socketPath }: {
|
|
44
|
+
socketPath: string;
|
|
45
|
+
}): Promise<void>;
|
|
42
46
|
/**
|
|
43
47
|
* Start a newline-delimited JSON IPC server on a unix socket / named pipe: each
|
|
44
48
|
* connection carries one JSON request, the handler's result is written back as
|
|
45
49
|
* `{ok:true,result}` (or `{ok:false,error}` on parse/handler failure).
|
|
46
50
|
* @returns A handle whose `close()` stops the server and unlinks the socket.
|
|
47
51
|
*/
|
|
48
|
-
export declare function createJsonIpcServer({ handler, socketPath,
|
|
52
|
+
export declare function createJsonIpcServer({ handler, socketPath, }: {
|
|
49
53
|
handler: JsonIpcHandler;
|
|
50
54
|
socketPath: string;
|
|
55
|
+
}, { maxFrameBytes, idleTimeoutMs }?: {
|
|
51
56
|
/** Reject a connection whose single frame exceeds this many bytes before a newline arrives (SEC-004). @default 1_000_000 */
|
|
52
57
|
maxFrameBytes?: number;
|
|
53
58
|
/** Drop a connection that has not delivered one complete frame within this many ms (SEC-004). @default 30_000 */
|
|
@@ -58,7 +63,10 @@ export declare function createJsonIpcServer({ handler, socketPath, maxFrameBytes
|
|
|
58
63
|
* resolve with the server's `result`, rejecting on error response or timeout.
|
|
59
64
|
* @returns The server's `result` payload.
|
|
60
65
|
*/
|
|
61
|
-
export declare function requestJsonIpc<T = any>(socketPath
|
|
66
|
+
export declare function requestJsonIpc<T = any>({ socketPath, payload }: {
|
|
67
|
+
socketPath: string;
|
|
68
|
+
payload: unknown;
|
|
69
|
+
}, { timeoutMs }?: {
|
|
62
70
|
timeoutMs?: number;
|
|
63
71
|
}): Promise<T>;
|
|
64
72
|
//# sourceMappingURL=json-ipc.d.ts.map
|
package/dist/json-ipc.js
CHANGED
|
@@ -99,7 +99,7 @@ function errorMessage(error) {
|
|
|
99
99
|
* hand today — matching this repo's "extract into a directly-testable pure
|
|
100
100
|
* function" convention rather than narrowing the type away.
|
|
101
101
|
*/
|
|
102
|
-
export function jsonIpcError(error) {
|
|
102
|
+
export function jsonIpcError({ error }) {
|
|
103
103
|
return {
|
|
104
104
|
...(errorCode(error) == null ? {} : { code: errorCode(error) }),
|
|
105
105
|
message: errorMessage(error),
|
|
@@ -130,7 +130,7 @@ async function staleUnixSocketExists(socketPath) {
|
|
|
130
130
|
// was provably unreachable (verified empirically this session: forcing
|
|
131
131
|
// a second event through a fake socket finds zero listeners and crashes
|
|
132
132
|
// the process outright, rather than reaching that guard — see
|
|
133
|
-
//
|
|
133
|
+
// archived provenance ledger's 2026-07-22 entry) — removed as a real refactor rather
|
|
134
134
|
// than padded with a test that can't exercise real behavior.
|
|
135
135
|
const settle = (callback) => {
|
|
136
136
|
socket.removeAllListeners();
|
|
@@ -160,8 +160,8 @@ async function staleUnixSocketExists(socketPath) {
|
|
|
160
160
|
* Windows. Testing this function directly (asserting no filesystem call
|
|
161
161
|
* happens) verifies the real behavior on every platform this runs on.
|
|
162
162
|
*/
|
|
163
|
-
export async function prepareIpcPath(socketPath) {
|
|
164
|
-
if (isWindowsNamedPipePath(socketPath))
|
|
163
|
+
export async function prepareIpcPath({ socketPath }) {
|
|
164
|
+
if (isWindowsNamedPipePath({ value: socketPath }))
|
|
165
165
|
return;
|
|
166
166
|
await mkdir(dirname(socketPath), { recursive: true });
|
|
167
167
|
if (await staleUnixSocketExists(socketPath))
|
|
@@ -173,8 +173,8 @@ export async function prepareIpcPath(socketPath) {
|
|
|
173
173
|
* `{ok:true,result}` (or `{ok:false,error}` on parse/handler failure).
|
|
174
174
|
* @returns A handle whose `close()` stops the server and unlinks the socket.
|
|
175
175
|
*/
|
|
176
|
-
export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes = DEFAULT_MAX_FRAME_BYTES, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS
|
|
177
|
-
await prepareIpcPath(socketPath);
|
|
176
|
+
export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBytes = DEFAULT_MAX_FRAME_BYTES, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
|
|
177
|
+
await prepareIpcPath({ socketPath });
|
|
178
178
|
const server = createNetServer((socket) => {
|
|
179
179
|
let buffer = "";
|
|
180
180
|
let receivedBytes = 0;
|
|
@@ -206,7 +206,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
206
206
|
// execution model means no other callback (including this one) can
|
|
207
207
|
// run in between that assignment and the `clearTimeout` call. Kept as
|
|
208
208
|
// a real fail-safe (in case a future edit reorders that sequence)
|
|
209
|
-
// rather than asserted away — see
|
|
209
|
+
// rather than asserted away — see archived provenance ledger's 2026-07-22 entry.
|
|
210
210
|
if (handled)
|
|
211
211
|
return;
|
|
212
212
|
handled = true;
|
|
@@ -228,7 +228,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
228
228
|
// the installed `@types/node`'s `net.d.ts` this session; not asserted
|
|
229
229
|
// away since a test would have to manually `.emit()` a fabricated
|
|
230
230
|
// non-Error value to reach the other side, which isn't real socket
|
|
231
|
-
// behavior (see
|
|
231
|
+
// behavior (see archived provenance ledger's 2026-07-22 entry).
|
|
232
232
|
traceJsonIpc("server.socket_error", {
|
|
233
233
|
durationMs: jsonIpcTraceDurationMs(startedAt),
|
|
234
234
|
error: error instanceof Error ? error.message : String(error),
|
|
@@ -288,7 +288,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
288
288
|
// genuine `SyntaxError` (an `Error` instance) for any string input
|
|
289
289
|
// — never a non-Error value — matching the same reasoning as the
|
|
290
290
|
// socket-error `instanceof Error` checks above (see
|
|
291
|
-
//
|
|
291
|
+
// archived provenance ledger's 2026-07-22 entry).
|
|
292
292
|
traceJsonIpc("server.frame_parse_failed", {
|
|
293
293
|
durationMs: jsonIpcTraceDurationMs(startedAt),
|
|
294
294
|
error: error instanceof Error ? error.message : String(error),
|
|
@@ -298,7 +298,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
298
298
|
});
|
|
299
299
|
socket.end(`${JSON.stringify({
|
|
300
300
|
ok: false,
|
|
301
|
-
error: jsonIpcError(error),
|
|
301
|
+
error: jsonIpcError({ error }),
|
|
302
302
|
})}\n`);
|
|
303
303
|
return;
|
|
304
304
|
}
|
|
@@ -317,7 +317,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
317
317
|
socketPath,
|
|
318
318
|
traceId,
|
|
319
319
|
});
|
|
320
|
-
const result = await handler(message);
|
|
320
|
+
const result = await handler({ message });
|
|
321
321
|
traceJsonIpc("server.handler_success", {
|
|
322
322
|
durationMs: jsonIpcTraceDurationMs(startedAt),
|
|
323
323
|
message: messageSummary,
|
|
@@ -331,7 +331,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
331
331
|
// same trust-boundary concern as SEC-005's HTTP fix). The peer gets a stable code plus
|
|
332
332
|
// the traceId as a correlation handle; the real detail is redacted and logged
|
|
333
333
|
// server-side only, unconditionally (not gated behind JINI_JSON_IPC_TRACE).
|
|
334
|
-
const redactedDetail = redactSecrets(error instanceof Error ? error.message : String(error));
|
|
334
|
+
const redactedDetail = redactSecrets({ input: error instanceof Error ? error.message : String(error) });
|
|
335
335
|
// eslint-disable-next-line no-console
|
|
336
336
|
console.error(`[@jini-ai/sidecar] json-ipc handler failed (traceId=${traceId})`, redactedDetail);
|
|
337
337
|
traceJsonIpc("server.handler_failed", {
|
|
@@ -358,7 +358,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
358
358
|
return {
|
|
359
359
|
async close() {
|
|
360
360
|
await closeServer(server);
|
|
361
|
-
if (!isWindowsNamedPipePath(socketPath))
|
|
361
|
+
if (!isWindowsNamedPipePath({ value: socketPath }))
|
|
362
362
|
await rm(socketPath, { force: true });
|
|
363
363
|
},
|
|
364
364
|
};
|
|
@@ -368,7 +368,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
|
|
|
368
368
|
* resolve with the server's `result`, rejecting on error response or timeout.
|
|
369
369
|
* @returns The server's `result` payload.
|
|
370
370
|
*/
|
|
371
|
-
export async function requestJsonIpc(socketPath, payload, { timeoutMs = 1500 } = {}) {
|
|
371
|
+
export async function requestJsonIpc({ socketPath, payload }, { timeoutMs = 1500 } = {}) {
|
|
372
372
|
return await new Promise((resolveRequest, rejectRequest) => {
|
|
373
373
|
const socket = createConnection(socketPath);
|
|
374
374
|
const traceId = nextJsonIpcTraceId();
|
|
@@ -475,7 +475,7 @@ export async function requestJsonIpc(socketPath, payload, { timeoutMs = 1500 } =
|
|
|
475
475
|
socket.on("error", (error) => {
|
|
476
476
|
// Same defense-in-depth, not-reachable-through-real-usage reasoning as
|
|
477
477
|
// the server-side `error instanceof Error` check above (see that
|
|
478
|
-
// comment +
|
|
478
|
+
// comment + archived provenance ledger's 2026-07-22 entry).
|
|
479
479
|
traceJsonIpc("client.socket_error", {
|
|
480
480
|
durationMs: jsonIpcTraceDurationMs(startedAt),
|
|
481
481
|
error: error instanceof Error ? error.message : String(error),
|
package/dist/paths.d.ts
CHANGED
|
@@ -8,18 +8,20 @@
|
|
|
8
8
|
* product-specific strings are hardcoded here. Depends on `node:path` and the
|
|
9
9
|
* public types.
|
|
10
10
|
*/
|
|
11
|
-
import type { AppIpcPathRequest, AppRuntimePathRequest, BaseResolutionOptions, NamespaceResolutionOptions, ProjectRuntimePathRequest, RuntimePathRequest, RuntimeRootRequest, SidecarContractDescriptor, SidecarRuntimeContext, SidecarStampShape } from "./types.js";
|
|
11
|
+
import type { AppIpcPathRequest, AppRuntimePathRequest, BaseResolutionOptions, BaseResolutionOptionsOptionalArgs, AppIpcPathRequestOptionalArgs, NamespaceResolutionOptions, NamespaceOptionalArgs, ProjectRuntimePathRequest, RuntimePathRequest, RuntimeRootRequest, SidecarContractDescriptor, SidecarRuntimeContext, SidecarStampShape } from "./types.js";
|
|
12
12
|
/**
|
|
13
13
|
* Resolve the effective namespace from an explicit value, the env var named by
|
|
14
14
|
* the contract, or the contract default — then normalize it.
|
|
15
15
|
* @returns The normalized namespace.
|
|
16
16
|
*/
|
|
17
|
-
export declare function resolveNamespace<TStamp extends SidecarStampShape>(
|
|
17
|
+
export declare function resolveNamespace<TStamp extends SidecarStampShape>({ contract }: Pick<NamespaceResolutionOptions<TStamp>, "contract">, options?: NamespaceOptionalArgs): string;
|
|
18
18
|
/**
|
|
19
19
|
* Validate and resolve a project root to an absolute path.
|
|
20
20
|
* @returns The resolved absolute project root.
|
|
21
21
|
*/
|
|
22
|
-
export declare function resolveProjectRoot(projectRoot
|
|
22
|
+
export declare function resolveProjectRoot({ projectRoot }: {
|
|
23
|
+
projectRoot: string;
|
|
24
|
+
}): string;
|
|
23
25
|
/**
|
|
24
26
|
* Resolve the project's tmp root (`<projectRoot>/<projectTmpDirName>`).
|
|
25
27
|
* @returns The resolved tmp root path.
|
|
@@ -38,7 +40,7 @@ export declare function resolveSourceRuntimeRoot<TStamp extends SidecarStampShap
|
|
|
38
40
|
* contract, or the source runtime root.
|
|
39
41
|
* @returns The resolved absolute base path.
|
|
40
42
|
*/
|
|
41
|
-
export declare function resolveSidecarBase<TStamp extends SidecarStampShape>({
|
|
43
|
+
export declare function resolveSidecarBase<TStamp extends SidecarStampShape>({ contract, source, }: BaseResolutionOptions<TStamp>, { base, env, projectRoot }?: BaseResolutionOptionsOptionalArgs): string;
|
|
42
44
|
/**
|
|
43
45
|
* Resolve the namespace root (`<base>/<namespace>`).
|
|
44
46
|
* @returns The resolved namespace root path.
|
|
@@ -103,11 +105,12 @@ export declare function resolveLogsDir<TStamp extends SidecarStampShape>({ app,
|
|
|
103
105
|
* Resolve an app's log file (`<logsDir>/<fileName>`, default `latest.log`).
|
|
104
106
|
* @returns The resolved log file path.
|
|
105
107
|
*/
|
|
106
|
-
export declare function resolveLogFilePath<TStamp extends SidecarStampShape>({ app, contract,
|
|
108
|
+
export declare function resolveLogFilePath<TStamp extends SidecarStampShape>({ app, contract, runtimeRoot, }: {
|
|
107
109
|
app: TStamp["app"] | string;
|
|
108
110
|
contract: SidecarContractDescriptor<TStamp>;
|
|
109
|
-
fileName?: string;
|
|
110
111
|
runtimeRoot: string;
|
|
112
|
+
}, { fileName }?: {
|
|
113
|
+
fileName?: string;
|
|
111
114
|
}): string;
|
|
112
115
|
/**
|
|
113
116
|
* Resolve an app's runtime dir under a namespace root (`<namespaceRoot>/<app>`).
|
|
@@ -126,5 +129,5 @@ export declare function resolveAppRuntimePath<TStamp extends SidecarStampShape>(
|
|
|
126
129
|
* `<ipcBase>/<namespace>/<app>.sock`.
|
|
127
130
|
* @returns The resolved IPC socket/pipe path.
|
|
128
131
|
*/
|
|
129
|
-
export declare function resolveAppIpcPath<TStamp extends SidecarStampShape>({ app, contract,
|
|
132
|
+
export declare function resolveAppIpcPath<TStamp extends SidecarStampShape>({ app, contract, namespace, }: AppIpcPathRequest<TStamp>, { env }?: AppIpcPathRequestOptionalArgs): string;
|
|
130
133
|
//# sourceMappingURL=paths.d.ts.map
|
package/dist/paths.js
CHANGED
|
@@ -14,16 +14,16 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
|
14
14
|
* the contract, or the contract default — then normalize it.
|
|
15
15
|
* @returns The normalized namespace.
|
|
16
16
|
*/
|
|
17
|
-
export function resolveNamespace(options) {
|
|
18
|
-
return
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
export function resolveNamespace({ contract }, options = {}) {
|
|
18
|
+
return contract.normalizeNamespace({ namespace: options.namespace ??
|
|
19
|
+
options.env?.[contract.env.namespace] ??
|
|
20
|
+
contract.defaults.namespace });
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
23
|
* Validate and resolve a project root to an absolute path.
|
|
24
24
|
* @returns The resolved absolute project root.
|
|
25
25
|
*/
|
|
26
|
-
export function resolveProjectRoot(projectRoot) {
|
|
26
|
+
export function resolveProjectRoot({ projectRoot }) {
|
|
27
27
|
if (typeof projectRoot !== "string" || projectRoot.trim().length === 0) {
|
|
28
28
|
throw new Error("projectRoot must be a non-empty string");
|
|
29
29
|
}
|
|
@@ -34,21 +34,21 @@ export function resolveProjectRoot(projectRoot) {
|
|
|
34
34
|
* @returns The resolved tmp root path.
|
|
35
35
|
*/
|
|
36
36
|
export function resolveProjectTmpRoot({ contract, projectRoot, }) {
|
|
37
|
-
return join(resolveProjectRoot(projectRoot), contract.defaults.projectTmpDirName);
|
|
37
|
+
return join(resolveProjectRoot({ projectRoot }), contract.defaults.projectTmpDirName);
|
|
38
38
|
}
|
|
39
39
|
/**
|
|
40
40
|
* Resolve the source-scoped runtime root (`<projectTmpRoot>/<source>`).
|
|
41
41
|
* @returns The resolved source runtime root path.
|
|
42
42
|
*/
|
|
43
43
|
export function resolveSourceRuntimeRoot({ contract, projectRoot, source, }) {
|
|
44
|
-
return join(resolveProjectTmpRoot({ contract, projectRoot }), contract.normalizeSource(source));
|
|
44
|
+
return join(resolveProjectTmpRoot({ contract, projectRoot }), contract.normalizeSource({ source }));
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
47
|
* Resolve the sidecar base from an explicit value, the env var named by the
|
|
48
48
|
* contract, or the source runtime root.
|
|
49
49
|
* @returns The resolved absolute base path.
|
|
50
50
|
*/
|
|
51
|
-
export function resolveSidecarBase({
|
|
51
|
+
export function resolveSidecarBase({ contract, source, }, { base, env = process.env, projectRoot = process.cwd() } = {}) {
|
|
52
52
|
return resolve(base ?? env[contract.env.base] ?? resolveSourceRuntimeRoot({ contract, projectRoot, source }));
|
|
53
53
|
}
|
|
54
54
|
/**
|
|
@@ -56,7 +56,7 @@ export function resolveSidecarBase({ base, contract, env = process.env, projectR
|
|
|
56
56
|
* @returns The resolved namespace root path.
|
|
57
57
|
*/
|
|
58
58
|
export function resolveNamespaceRoot({ base, contract, namespace, }) {
|
|
59
|
-
return join(resolve(base), contract.normalizeNamespace(namespace));
|
|
59
|
+
return join(resolve(base), contract.normalizeNamespace({ namespace }));
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
62
|
* Resolve the namespace root (the directory that holds `logs/`, `runs/`,
|
|
@@ -117,13 +117,13 @@ export function resolveManifestPath({ runtimeRoot }) {
|
|
|
117
117
|
* @returns The resolved logs directory path.
|
|
118
118
|
*/
|
|
119
119
|
export function resolveLogsDir({ app, contract, runtimeRoot, }) {
|
|
120
|
-
return join(runtimeRoot, "logs", contract.normalizeApp(app));
|
|
120
|
+
return join(runtimeRoot, "logs", contract.normalizeApp({ app }));
|
|
121
121
|
}
|
|
122
122
|
/**
|
|
123
123
|
* Resolve an app's log file (`<logsDir>/<fileName>`, default `latest.log`).
|
|
124
124
|
* @returns The resolved log file path.
|
|
125
125
|
*/
|
|
126
|
-
export function resolveLogFilePath({ app, contract, fileName = "latest.log"
|
|
126
|
+
export function resolveLogFilePath({ app, contract, runtimeRoot, }, { fileName = "latest.log" } = {}) {
|
|
127
127
|
return join(resolveLogsDir({ app, contract, runtimeRoot }), fileName);
|
|
128
128
|
}
|
|
129
129
|
/**
|
|
@@ -131,7 +131,7 @@ export function resolveLogFilePath({ app, contract, fileName = "latest.log", run
|
|
|
131
131
|
* @returns The resolved app runtime directory path.
|
|
132
132
|
*/
|
|
133
133
|
export function resolveAppRuntimeDir({ app, contract, namespaceRoot, }) {
|
|
134
|
-
return join(namespaceRoot, contract.normalizeApp(app));
|
|
134
|
+
return join(namespaceRoot, contract.normalizeApp({ app }));
|
|
135
135
|
}
|
|
136
136
|
/**
|
|
137
137
|
* Resolve a file inside an app's runtime dir, rejecting non-simple file names.
|
|
@@ -148,9 +148,9 @@ export function resolveAppRuntimePath({ app, contract, fileName, namespaceRoot,
|
|
|
148
148
|
* `<ipcBase>/<namespace>/<app>.sock`.
|
|
149
149
|
* @returns The resolved IPC socket/pipe path.
|
|
150
150
|
*/
|
|
151
|
-
export function resolveAppIpcPath({ app, contract, env = process.env
|
|
152
|
-
const normalizedApp = contract.normalizeApp(app);
|
|
153
|
-
const normalizedNamespace = contract.normalizeNamespace(namespace);
|
|
151
|
+
export function resolveAppIpcPath({ app, contract, namespace, }, { env = process.env } = {}) {
|
|
152
|
+
const normalizedApp = contract.normalizeApp({ app });
|
|
153
|
+
const normalizedNamespace = contract.normalizeNamespace({ namespace });
|
|
154
154
|
if (process.platform === "win32") {
|
|
155
155
|
return `\\\\.\\pipe\\${contract.defaults.windowsPipePrefix}-${normalizedNamespace}-${normalizedApp}`;
|
|
156
156
|
}
|
package/dist/port.d.ts
CHANGED
|
@@ -14,11 +14,19 @@ import type { PortAllocation, PortRequest } from "./types.js";
|
|
|
14
14
|
* platform-specific and not something a test should depend on for a hard-coded 20-reserved-port
|
|
15
15
|
* scenario. `allocatePort` always calls this with the real {@link probeEphemeralPort}.
|
|
16
16
|
*/
|
|
17
|
-
export declare function allocateDynamicPort(label
|
|
17
|
+
export declare function allocateDynamicPort({ label, host, reserved }: {
|
|
18
|
+
label: string;
|
|
19
|
+
host: string;
|
|
20
|
+
reserved: Set<number>;
|
|
21
|
+
}, { probe }?: {
|
|
22
|
+
probe?: (requiredArgs: {
|
|
23
|
+
host: string;
|
|
24
|
+
}) => Promise<number>;
|
|
25
|
+
}): Promise<PortAllocation>;
|
|
18
26
|
/**
|
|
19
27
|
* Allocate a port: a forced port when one is supplied, otherwise a dynamic one,
|
|
20
28
|
* recording it in the `reserved` set to avoid double-allocation.
|
|
21
29
|
* @returns The port allocation (port + how it was chosen).
|
|
22
30
|
*/
|
|
23
|
-
export declare function allocatePort({ host, label, port, reserved, }?: PortRequest): Promise<PortAllocation>;
|
|
31
|
+
export declare function allocatePort(_requiredArgs: Record<string, never>, { host, label, port, reserved, }?: PortRequest): Promise<PortAllocation>;
|
|
24
32
|
//# sourceMappingURL=port.d.ts.map
|
package/dist/port.js
CHANGED
|
@@ -59,7 +59,7 @@ async function allocateForcedPort(port, label, host, reserved) {
|
|
|
59
59
|
* @internal Probes one ephemeral port via a real bind(0)-listen-then-close cycle — the OS
|
|
60
60
|
* hands back whatever port it currently considers free.
|
|
61
61
|
*/
|
|
62
|
-
async function probeEphemeralPort(host) {
|
|
62
|
+
async function probeEphemeralPort({ host }) {
|
|
63
63
|
const server = await listenOnPort(0, host);
|
|
64
64
|
const address = server.address();
|
|
65
65
|
await closeServer(server);
|
|
@@ -76,9 +76,9 @@ async function probeEphemeralPort(host) {
|
|
|
76
76
|
* platform-specific and not something a test should depend on for a hard-coded 20-reserved-port
|
|
77
77
|
* scenario. `allocatePort` always calls this with the real {@link probeEphemeralPort}.
|
|
78
78
|
*/
|
|
79
|
-
export async function allocateDynamicPort(label, host, reserved, probe = probeEphemeralPort) {
|
|
79
|
+
export async function allocateDynamicPort({ label, host, reserved }, { probe = probeEphemeralPort } = {}) {
|
|
80
80
|
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
81
|
-
const port = await probe(host);
|
|
81
|
+
const port = await probe({ host });
|
|
82
82
|
if (!reserved.has(port)) {
|
|
83
83
|
reserved.add(port);
|
|
84
84
|
return { port, source: "dynamic" };
|
|
@@ -91,10 +91,10 @@ export async function allocateDynamicPort(label, host, reserved, probe = probeEp
|
|
|
91
91
|
* recording it in the `reserved` set to avoid double-allocation.
|
|
92
92
|
* @returns The port allocation (port + how it was chosen).
|
|
93
93
|
*/
|
|
94
|
-
export async function allocatePort({ host = "127.0.0.1", label = "runtime", port, reserved = new Set(), } = {}) {
|
|
94
|
+
export async function allocatePort(_requiredArgs, { host = "127.0.0.1", label = "runtime", port, reserved = new Set(), } = {}) {
|
|
95
95
|
const forcedPort = parsePort(port, label);
|
|
96
96
|
return forcedPort == null
|
|
97
|
-
? await allocateDynamicPort(label, host, reserved)
|
|
97
|
+
? await allocateDynamicPort({ label, host, reserved })
|
|
98
98
|
: await allocateForcedPort(forcedPort, label, host, reserved);
|
|
99
99
|
}
|
|
100
100
|
//# sourceMappingURL=port.js.map
|
|
@@ -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,55 @@
|
|
|
1
|
+
import type { Writable } from "node:stream";
|
|
2
|
+
import type { LocalDaemonRegistryRecord } from "./daemon-registry.js";
|
|
3
|
+
import type { SpawnedDaemonProcess, SupervisorScheduler } from "./supervisor.js";
|
|
4
|
+
export interface SupervisorRegistry {
|
|
5
|
+
readLive(): Promise<LocalDaemonRegistryRecord | null>;
|
|
6
|
+
write(input: {
|
|
7
|
+
record: LocalDaemonRegistryRecord;
|
|
8
|
+
}): Promise<void>;
|
|
9
|
+
removeIfCurrent(input: {
|
|
10
|
+
pid: number;
|
|
11
|
+
}): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
|
|
15
|
+
* The child calls write only after it actually starts listening.
|
|
16
|
+
* @param required Host-owned registry path.
|
|
17
|
+
* @returns A registry port with object arguments at all data-bearing boundaries.
|
|
18
|
+
* @complexity O(1) operations, excluding filesystem I/O.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createSupervisorRegistry({ registryPath }: {
|
|
21
|
+
registryPath: string;
|
|
22
|
+
}): SupervisorRegistry;
|
|
23
|
+
export interface NodeDaemonProcessRequired {
|
|
24
|
+
command: string;
|
|
25
|
+
args: readonly string[];
|
|
26
|
+
cwd: string;
|
|
27
|
+
env: NodeJS.ProcessEnv;
|
|
28
|
+
registry: SupervisorRegistry;
|
|
29
|
+
}
|
|
30
|
+
export interface NodeDaemonProcessOptions {
|
|
31
|
+
stdout?: Writable;
|
|
32
|
+
stderr?: Writable;
|
|
33
|
+
platform?: NodeJS.Platform;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
|
|
37
|
+
* @param required Complete host launch settings and the shared sidecar registry port.
|
|
38
|
+
* @param options Optional sinks; output is piped through the parent rather than inherited.
|
|
39
|
+
* @returns Supervisor process ports. Construction has no process or filesystem effects.
|
|
40
|
+
* @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
|
|
41
|
+
*/
|
|
42
|
+
export declare function createNodeDaemonProcessAdapter(required: NodeDaemonProcessRequired, options?: NodeDaemonProcessOptions): {
|
|
43
|
+
spawnDaemonProcess(): SpawnedDaemonProcess;
|
|
44
|
+
terminateProcess(input: {
|
|
45
|
+
child: SpawnedDaemonProcess;
|
|
46
|
+
}): Promise<void>;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Node timer adapter; importing/constructing it schedules no work.
|
|
50
|
+
* @param required Empty required arguments object.
|
|
51
|
+
* @returns Scheduler using setTimeout and clearTimeout.
|
|
52
|
+
* @complexity O(1) per schedule/cancel.
|
|
53
|
+
*/
|
|
54
|
+
export declare function createNodeSupervisorScheduler(_required: Record<string, never>): SupervisorScheduler;
|
|
55
|
+
//# sourceMappingURL=supervisor-node.d.ts.map
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import { collectProcessTreePids, createCommandInvocation, listProcessSnapshots, stopProcesses } from "@jini-ai/platform";
|
|
3
|
+
import { readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, writeDaemonRegistryRecord } from "./daemon-registry.js";
|
|
4
|
+
/**
|
|
5
|
+
* Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
|
|
6
|
+
* The child calls write only after it actually starts listening.
|
|
7
|
+
* @param required Host-owned registry path.
|
|
8
|
+
* @returns A registry port with object arguments at all data-bearing boundaries.
|
|
9
|
+
* @complexity O(1) operations, excluding filesystem I/O.
|
|
10
|
+
*/
|
|
11
|
+
export function createSupervisorRegistry({ registryPath }) {
|
|
12
|
+
return {
|
|
13
|
+
readLive: () => readLiveDaemonRegistryRecord({ registryPath }),
|
|
14
|
+
write: ({ record }) => writeDaemonRegistryRecord({ registryPath, record }),
|
|
15
|
+
removeIfCurrent: ({ pid }) => removeDaemonRegistryRecordIfCurrent({ registryPath, pid }),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
|
|
20
|
+
* @param required Complete host launch settings and the shared sidecar registry port.
|
|
21
|
+
* @param options Optional sinks; output is piped through the parent rather than inherited.
|
|
22
|
+
* @returns Supervisor process ports. Construction has no process or filesystem effects.
|
|
23
|
+
* @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
|
|
24
|
+
*/
|
|
25
|
+
export function createNodeDaemonProcessAdapter(required, options = {}) {
|
|
26
|
+
return {
|
|
27
|
+
spawnDaemonProcess() {
|
|
28
|
+
const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env: required.env });
|
|
29
|
+
// detached creates a POSIX process group so teardown reaches the daemon below a
|
|
30
|
+
// launcher hop; windowsHide avoids an otherwise visible detached Windows console.
|
|
31
|
+
// Pipe output through the parent instead of inheriting its descriptors: an orphan
|
|
32
|
+
// retaining those descriptors previously kept parent/test teardown waiting forever.
|
|
33
|
+
const child = spawn(invocation.command, invocation.args, {
|
|
34
|
+
cwd: required.cwd, env: { ...required.env }, detached: true, windowsHide: true,
|
|
35
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
36
|
+
...(invocation.windowsVerbatimArguments === undefined ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments }),
|
|
37
|
+
});
|
|
38
|
+
if (options.stdout !== undefined)
|
|
39
|
+
child.stdout?.pipe(options.stdout);
|
|
40
|
+
else
|
|
41
|
+
child.stdout?.resume();
|
|
42
|
+
if (options.stderr !== undefined)
|
|
43
|
+
child.stderr?.pipe(options.stderr);
|
|
44
|
+
else
|
|
45
|
+
child.stderr?.resume();
|
|
46
|
+
return {
|
|
47
|
+
get pid() { return child.pid; },
|
|
48
|
+
on(input) {
|
|
49
|
+
if (input.event === "exit")
|
|
50
|
+
child.on("exit", (code, signal) => input.listener({ code, signal }));
|
|
51
|
+
else
|
|
52
|
+
child.on("error", (error) => input.listener({ error }));
|
|
53
|
+
},
|
|
54
|
+
kill(_required, { signal } = {}) { return child.kill(signal); },
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
async terminateProcess({ child }) {
|
|
58
|
+
if (child.pid === undefined)
|
|
59
|
+
return;
|
|
60
|
+
const pid = child.pid;
|
|
61
|
+
const snapshotRequest = listProcessSnapshots();
|
|
62
|
+
// Signal before the first await: even a parent exiting immediately after shutdown reaps its tree.
|
|
63
|
+
// Windows has no group signal, so taskkill supplies the synchronous tree-stop equivalent.
|
|
64
|
+
// Windows has no POSIX group signal. Killing only the immediate launcher would
|
|
65
|
+
// orphan its daemon; taskkill /T walks the entire descendant tree instead.
|
|
66
|
+
try {
|
|
67
|
+
if ((options.platform ?? process.platform) === "win32") {
|
|
68
|
+
execFileSync("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
process.kill(-pid, "SIGTERM");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
child.kill({}, { signal: "SIGTERM" });
|
|
76
|
+
}
|
|
77
|
+
const snapshots = await snapshotRequest;
|
|
78
|
+
const pids = collectProcessTreePids(snapshots, [pid]);
|
|
79
|
+
const result = await stopProcesses(pids);
|
|
80
|
+
if (result.remainingPids.length > 0)
|
|
81
|
+
throw new Error(`daemon processes still running: ${result.remainingPids.join(", ")}`);
|
|
82
|
+
await required.registry.removeIfCurrent({ pid });
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Node timer adapter; importing/constructing it schedules no work.
|
|
88
|
+
* @param required Empty required arguments object.
|
|
89
|
+
* @returns Scheduler using setTimeout and clearTimeout.
|
|
90
|
+
* @complexity O(1) per schedule/cancel.
|
|
91
|
+
*/
|
|
92
|
+
export function createNodeSupervisorScheduler(_required) {
|
|
93
|
+
return { schedule: ({ delayMs, run }) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); } };
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=supervisor-node.js.map
|