@onereach/state-machine-runtime-node-worker 0.0.0-stage → 1.0.0-framework.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/README.md CHANGED
@@ -1,3 +1,126 @@
1
- # Temporary Holding Version
1
+ # @onereach/state-machine-runtime-node-worker
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Opt-in Node `worker_threads` execution for trusted **pure state functions**.
4
+ Selected functions get fresh workers, finite deadlines, cloned JSON input/state,
5
+ and no host/Flow SDK context. Non-selected functions keep the ordinary trusted
6
+ runtime and its existing fail-closed lifetime behavior.
7
+
8
+ ## Explicit composition
9
+
10
+ ```ts
11
+ import { StateMachineRuntime } from '@onereach/state-machine-runtime';
12
+ import { WorkerImplementationCompiler } from '@onereach/state-machine-runtime-node-worker';
13
+
14
+ const compiler = new WorkerImplementationCompiler({
15
+ defaultTimeoutMs: 1000,
16
+ });
17
+ const runtime = new StateMachineRuntime({ implementationCompiler: compiler });
18
+ ```
19
+
20
+ Declare eligible functions in their templates:
21
+
22
+ ```ts
23
+ {
24
+ annotations: { pure: true },
25
+ implementation: {
26
+ runtime: 'javascript',
27
+ abi: 'state-machine-function-v1',
28
+ format: 'async-function-body',
29
+ capabilities: [],
30
+ code: 'state.counter++; return state.counter;',
31
+ },
32
+ }
33
+ ```
34
+
35
+ The compiler automatically selects `annotations.pure === true`,
36
+ independently of function/template names. `new WorkerImplementationCompiler()`
37
+ uses this policy with default limits. An optional `select(templateId, definition)`
38
+ filter can narrow eligible functions, but cannot opt undeclared functions into
39
+ workers. Existing custom selectors now require the declaration too.
40
+
41
+ The declaration is an author assertion, not a proof of purity.
42
+ Empty capability lists, `annotations.idempotent`, and arbitrary function metadata
43
+ do not select or prove purity. Omitted or false annotations retain trusted execution.
44
+ Selected definitions
45
+ requesting host capabilities are rejected; their context is a frozen empty object
46
+ and host `scopeContext` is skipped. No live context, SDK facade, function, signal,
47
+ or host capability is serialized into the worker.
48
+
49
+ The declaration is platform-neutral and does not enable workers on its own.
50
+ Core runtime without an injected compiler remains trusted; other platforms can
51
+ provide their own backend. Neither purity nor idempotency enables automatic retries.
52
+
53
+ For OneReach, configure the process system **before its first use**:
54
+
55
+ ```ts
56
+ getStateMachineSystem(process, { implementationCompiler: compiler });
57
+ ```
58
+
59
+ Omitted options on later retrieval inherit the established compiler. A different
60
+ explicit compiler object conflicts instead of changing a live process policy.
61
+ The step package does not import or enable this optional Node backend by default.
62
+
63
+ ## Deadlines and confirmed exit
64
+
65
+ The definition's `implementation.timeoutMs` takes precedence; otherwise every
66
+ selected worker uses `defaultTimeoutMs` (default 1,000 ms). Durations must be
67
+ positive safe integers no greater than 2,147,483,647 ms. The budget includes worker
68
+ startup, execution, and exit confirmation, not parent-side validation/serialization.
69
+ Expiry rejects with the existing runtime `FunctionTimeoutError` and requests
70
+ `worker.terminate()`.
71
+
72
+ The runtime's caller `result` can reject promptly, but actual `completion` fulfills
73
+ **only after the worker's `exit` event**. A resolved termination request, timeout,
74
+ worker error, or result message alone does not establish completion. Successful
75
+ results also wait for exit: after receiving a candidate the parent terminates the
76
+ worker, stopping timers/tasks in that worker, then accepts the candidate only on
77
+ exit. Late candidates cannot replace a timeout or be persisted.
78
+
79
+ This makes infinite loops, never-resolving promises, and ordinary worker crashes
80
+ recoverable without releasing ownership while worker code is known to run.
81
+ If termination fails and no exit is confirmed, completion stays pending and the
82
+ coordinator remains fail-closed. There is no unsafe force-unlock fallback.
83
+ Node/OS scheduling is not a real-time guarantee; host-process failure remains an
84
+ operational concern.
85
+
86
+ Cancellation is checked during startup before the parent dispatches the run
87
+ message. A cancelled startup rejects with the original signal reason, terminates
88
+ the worker, and still waits for exit before completion. After dispatch,
89
+ cancellation does not override results or imply rollback; the deadline still
90
+ applies.
91
+
92
+ ## Data and validation
93
+
94
+ Input/state must be finite plain JSON, with a record at the state root. Accessors,
95
+ hidden/symbol properties, sparse arrays, cycles, functions, undefined descendants,
96
+ non-finite numbers, host objects, and shared buffers are rejected before schema
97
+ validation or cloning can invoke accessors. Shared references are copied as JSON
98
+ trees. Top-level undefined output remains allowed when no output schema forbids
99
+ it. Returned state/output are checked again at the parent boundary.
100
+
101
+ Core input/output/state schema validation stays in the parent runtime. Queries
102
+ are refrozen **inside** the worker because structured cloning removes frozen
103
+ attributes. State replacement uses the same JavaScript function ABI as the
104
+ trusted runtime. Selected code is compiled only in the worker; syntax failures
105
+ therefore surface at execution, not parent preparation. Worker creation or
106
+ serialization failure never silently falls back to trusted execution.
107
+
108
+ ## Resources and diagnostics
109
+
110
+ Each call creates one worker; there is no shared global state or worker pool.
111
+ `maxOldGenerationSizeMb` defaults to 64 (integer range 8–4096); stack size is 4 MB.
112
+ These V8 limits do not bound all native allocations, parent memory, payload sizes,
113
+ or aggregate concurrency. Apply schema payload limits and host concurrency limits
114
+ appropriate to the deployment.
115
+
116
+ An optional second constructor argument supplies
117
+ `WorkerRuntimeDiagnostics.onLifecycle(event)` with function name, worker ID, and
118
+ `started`, `exited`, or `termination-failed` metadata. Exit events include the exit
119
+ code and termination failures include their cause. Reports are best-effort:
120
+ throws/rejections are contained and pending reports are not awaited.
121
+
122
+ **This is execution isolation, not an untrusted-code security sandbox.** Worker
123
+ JavaScript still has Node/OS privileges and can access files/network or spawn
124
+ other processes if trusted code chooses to do so. Do not select host-integrated
125
+ or externally effectful functions. Termination cannot undo remote effects, and
126
+ does not guarantee termination of processes/threads spawned by function code.
@@ -0,0 +1,55 @@
1
+ import { RuntimeImplementation, RuntimeImplementationCompiler } from "@onereach/state-machine-runtime";
2
+ import { ReadonlyStateMachineFunctionDefinition } from "@onereach/state-machine-contracts";
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Immutable composition policy for functions declaring annotations.pure: true.
6
+ * The declaration is not a proof or an untrusted-code security boundary.
7
+ */
8
+ interface WorkerImplementationCompilerOptions {
9
+ /**
10
+ * Optional additional filter; it cannot opt undeclared implementations into workers.
11
+ */
12
+ readonly select?: (templateId: string, definition: ReadonlyStateMachineFunctionDefinition) => boolean;
13
+ readonly defaultTimeoutMs?: number;
14
+ readonly maxOldGenerationSizeMb?: number;
15
+ }
16
+ /**
17
+ * Host-side metadata only. No worker or host context is exposed to functions.
18
+ */
19
+ interface WorkerLifecycleEvent {
20
+ readonly functionName: string;
21
+ readonly workerId: number;
22
+ readonly phase: 'started' | 'exited' | 'termination-failed';
23
+ readonly exitCode?: number;
24
+ readonly cause?: unknown;
25
+ }
26
+ /**
27
+ * Best-effort observability; throwing, rejected, or pending reports cannot
28
+ * change the execution result or delay termination/completion.
29
+ */
30
+ interface WorkerRuntimeDiagnostics {
31
+ readonly onLifecycle?: (event: WorkerLifecycleEvent) => void | Promise<void>;
32
+ }
33
+ //#endregion
34
+ //#region src/errors.d.ts
35
+ /**
36
+ * Worker policy, startup, protocol, crash, or serialization failure.
37
+ * Function deadlines retain the runtime's FunctionTimeoutError identity.
38
+ */
39
+ declare class WorkerExecutionError extends Error {
40
+ readonly functionName: string;
41
+ constructor(functionName: string, message: string, cause?: unknown);
42
+ }
43
+ //#endregion
44
+ //#region src/index.d.ts
45
+ declare class WorkerImplementationCompiler implements RuntimeImplementationCompiler {
46
+ private readonly select;
47
+ private readonly defaultTimeoutMs;
48
+ private readonly maxOldGenerationSizeMb;
49
+ private readonly diagnostics;
50
+ constructor(options?: WorkerImplementationCompilerOptions, diagnostics?: WorkerRuntimeDiagnostics);
51
+ compile<TContext>(templateId: string, definition: ReadonlyStateMachineFunctionDefinition): RuntimeImplementation<TContext>;
52
+ }
53
+ //#endregion
54
+ export { WorkerExecutionError, WorkerImplementationCompiler, type WorkerImplementationCompilerOptions, type WorkerLifecycleEvent, type WorkerRuntimeDiagnostics };
55
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/errors.ts","../src/index.ts"],"mappings":";;;;;;;UAMiB;;;;WAIN,UAAU,oBAAoB,YAAY;WAC1C;WACA;;;;;UAMM;WACN;WACA;WACA;WACA;WACA;;;;;;UAOM;WACN,eAAe,OAAO,gCAAgC;;;;;;;;cC3BpD,6BAA6B;WACxB;EAEJ,YAAA,sBAAsB,iBAAiB;;;;cCExC,wCAAwC;mBAClC;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS,qCAA0C,cAAa;EAuBrE,QAAQ,UACb,oBACA,YAAY,yCACX,sBAAsB"}
package/dist/index.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import{FunctionTimeoutError as e,compileTrustedJavaScriptImplementation as t}from"@onereach/state-machine-runtime";import{Worker as n}from"node:worker_threads";function r(e,t,n=new Set){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||!e||n.has(e))throw TypeError(`Worker data must be finite JSON at ${t}`);let i=Array.isArray(e),a=Object.getPrototypeOf(e);if(!i&&a!==null&&a!==Object.prototype)throw TypeError(`Worker data must be plain JSON at ${t}`);n.add(e);try{let a=Object.getOwnPropertyDescriptors(e),o=Reflect.ownKeys(a);if(i){if(o.length!==e.length+1)throw TypeError(`Worker data must be a dense JSON array at ${t}`);let i=[];for(let o=0;o<e.length;o++){let e=a[String(o)];if(!e?.enumerable||!(`value`in e))throw TypeError(`Worker data must be a dense JSON array at ${t}[${o}]`);i.push(r(e.value,`${t}[${o}]`,n))}return i}let s={};for(let e of o){if(typeof e!=`string`)throw TypeError(`Worker data cannot contain symbol keys at ${t}`);let i=a[e];if(!i.enumerable||!(`value`in i))throw TypeError(`Worker data cannot contain accessors or hidden values at ${t}.${e}`);Object.defineProperty(s,e,{value:r(i.value,`${t}.${e}`,n),enumerable:!0,configurable:!0,writable:!0})}return s}finally{n.delete(e)}}function i(e){let t=r(e,`state`);if(!t||typeof t!=`object`||Array.isArray(t))throw TypeError(`Worker state must be a plain JSON record`);return t}var a=class extends Error{functionName;constructor(e,t,n){super(`Worker function "${e}": ${t}`,{cause:n}),this.name=`WorkerExecutionError`,this.functionName=e}};const o=String.raw`
2
+ "use strict";
3
+ const { parentPort, workerData } = require("node:worker_threads");
4
+ const keepAlive = setInterval(() => {}, 1000000);
5
+ function freeze(value) {
6
+ if (value && typeof value === "object") {
7
+ for (const child of Object.values(value)) freeze(child);
8
+ Object.freeze(value);
9
+ }
10
+ return value;
11
+ }
12
+ function failure(error) {
13
+ parentPort.postMessage({
14
+ type: "error",
15
+ error: {
16
+ name: error && typeof error.name === "string" ? error.name : "Error",
17
+ message: error && typeof error.message === "string" ? error.message : String(error),
18
+ stack: error && typeof error.stack === "string" ? error.stack : undefined
19
+ }
20
+ });
21
+ }
22
+ parentPort.once("message", (message) => {
23
+ if (!message || message.type !== "run") return;
24
+ void (async () => {
25
+ try {
26
+ const source = '"use strict"; return async function(input, state, ctx) {' +
27
+ '"use strict"; return { output: await (async () => {\n' +
28
+ workerData.code + '\n})(), state }; }; \n//# sourceURL=' + workerData.sourceUrl;
29
+ const implementation = new Function(source)();
30
+ const state = workerData.kind === "query" ? freeze(workerData.state) : workerData.state;
31
+ parentPort.postMessage({ type: "running" });
32
+ const result = await implementation(workerData.input, state, Object.freeze(Object.create(null)));
33
+ parentPort.postMessage({ type: "result", result });
34
+ } catch (error) {
35
+ failure(error);
36
+ }
37
+ })().catch(failure);
38
+ });
39
+ parentPort.postMessage({ type: "ready" });
40
+ `;function s(t,s,c,l,u){let{signal:d}=l;d?.throwIfAborted();let f={code:t.code,kind:t.kind,sourceUrl:t.sourceUrl,input:r(s,`input`),state:i(c)},p=performance.now()+t.timeoutMs,m;try{m=new n(o,{eval:!0,workerData:f,env:{},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:t.maxOldGenerationSizeMb,stackSizeMb:4}})}catch(e){throw new a(t.name,`worker startup failed`,e)}let h=m.threadId,g,_,v=new Promise((e,t)=>{g=e,_=t}),y,b=new Promise(e=>{y=()=>e()}),x,S=!1,C=!1,w=!1,T=!1,E=(e,n={})=>{try{let r=u.onLifecycle?.({functionName:t.name,workerId:h,phase:e,...n});r&&r.catch(()=>{})}catch{}},D=()=>{w||T||(T=!0,m.terminate().catch(e=>{E(`termination-failed`,{cause:e})}))},O=e=>{_(e),D()},k=()=>{S||(d?.removeEventListener(`abort`,k),O(d?.reason))},A=setTimeout(()=>{d?.removeEventListener(`abort`,k),O(new e(t.name,t.timeoutMs))},Math.max(0,p-performance.now()));return m.on(`message`,e=>{if(!(w||T))try{if(!e||typeof e!=`object`||!(`type`in e))throw new a(t.name,`invalid response`);if(e.type===`ready`){if(S)throw new a(t.name,`duplicate readiness response`);d?.throwIfAborted(),S=!0,d?.removeEventListener(`abort`,k),m.postMessage({type:`run`})}else if(e.type===`running`){if(!S||C)throw new a(t.name,`invalid running response`);C=!0,E(`started`)}else if(e.type===`result`&&`result`in e){let n=e.result;if(!S||!n||typeof n!=`object`||!(`output`in n)||!(`state`in n))throw new a(t.name,`invalid result`);x={output:n.output===void 0?void 0:r(n.output,`output`),state:i(n.state)},D()}else if(e.type===`error`&&`error`in e){let n=e.error,r=n&&typeof n==`object`&&`message`in n&&typeof n.message==`string`?n.message:`implementation failed`;throw new a(t.name,r,n)}else throw new a(t.name,`unexpected response`)}catch(e){O(e)}}),m.on(`error`,e=>{O(new a(t.name,`worker failed`,e))}),m.once(`exit`,e=>{w=!0,clearTimeout(A),d?.removeEventListener(`abort`,k),x?g(x):_(new a(t.name,`exited without a result (code ${e})`)),m.removeAllListeners(`message`),m.removeAllListeners(`error`),E(`exited`,{exitCode:e}),y()}),d?.addEventListener(`abort`,k,{once:!0}),d?.aborted&&k(),Object.freeze({result:v,completion:b})}var c=class{select;defaultTimeoutMs;maxOldGenerationSizeMb;diagnostics;constructor(e={},t={}){if(e.select!==void 0&&typeof e.select!=`function`)throw TypeError(`Worker selection filter must be a function`);if(this.select=e.select,this.defaultTimeoutMs=e.defaultTimeoutMs??1e3,this.maxOldGenerationSizeMb=e.maxOldGenerationSizeMb??64,!Number.isSafeInteger(this.defaultTimeoutMs)||this.defaultTimeoutMs<1||this.defaultTimeoutMs>2147483647)throw RangeError(`Worker defaultTimeoutMs must be within the positive timer range`);if(!Number.isSafeInteger(this.maxOldGenerationSizeMb)||this.maxOldGenerationSizeMb<8||this.maxOldGenerationSizeMb>4096)throw RangeError(`Worker maxOldGenerationSizeMb must be an integer from 8 to 4096`);this.diagnostics=Object.freeze({onLifecycle:t.onLifecycle})}compile(e,n){let o=n.implementation;if(n.annotations?.pure!==!0||this.select&&!this.select(e,n))return t(e,n);if(o.runtime!==`javascript`||o.abi!==`state-machine-function-v1`||o.format!==`async-function-body`)throw new a(n.name,`unsupported implementation`);if(o.capabilities.length>0)throw new a(n.name,`pure functions cannot request host capabilities`);let c=o.timeoutMs??this.defaultTimeoutMs;if(!Number.isSafeInteger(c)||c<1||c>2147483647)throw new a(n.name,`timeoutMs must be within the positive timer range`);let l=Object.freeze({name:n.name,code:o.code,kind:n.kind,sourceUrl:`state-machine://${encodeURIComponent(e)}/${encodeURIComponent(n.name)}`,timeoutMs:c,maxOldGenerationSizeMb:this.maxOldGenerationSizeMb}),u=(e,t,n,r={})=>s(l,e,t,r,this.diagnostics);return Object.freeze(Object.assign((e,t,n)=>u(e,t,n).result,{startExecution:u,contextPolicy:`none`,validateData:(e,t)=>{r(e,`input`),i(t)}}))}};export{a as WorkerExecutionError,c as WorkerImplementationCompiler};
41
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/data.ts","../src/errors.ts","../src/runner.ts","../src/execution.ts","../src/index.ts"],"sourcesContent":["/**\n * Own finite JSON snapshots without invoking accessors, toJSON, or coercion.\n * Shared buffers, functions, host objects, cycles, and hidden data are rejected.\n */\nexport function clonePureData(value: unknown, path: string, seen = new Set<object>()): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value !== 'object' || value === null || seen.has(value)) {\n throw new TypeError(`Worker data must be finite JSON at ${path}`);\n }\n const isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value) as unknown;\n if (!isArray && prototype !== null && prototype !== Object.prototype) {\n throw new TypeError(`Worker data must be plain JSON at ${path}`);\n }\n seen.add(value);\n try {\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const keys = Reflect.ownKeys(descriptors);\n if (isArray) {\n if (keys.length !== value.length + 1) throw new TypeError(`Worker data must be a dense JSON array at ${path}`);\n const result: unknown[] = [];\n for (let index = 0; index < value.length; index++) {\n const descriptor = descriptors[String(index)];\n if (!descriptor?.enumerable || !('value' in descriptor)) {\n throw new TypeError(`Worker data must be a dense JSON array at ${path}[${index}]`);\n }\n result.push(clonePureData(descriptor.value, `${path}[${index}]`, seen));\n }\n return result;\n }\n const result: Record<string, unknown> = {};\n for (const key of keys) {\n if (typeof key !== 'string') throw new TypeError(`Worker data cannot contain symbol keys at ${path}`);\n const descriptor = descriptors[key]!;\n if (!descriptor.enumerable || !('value' in descriptor)) {\n throw new TypeError(`Worker data cannot contain accessors or hidden values at ${path}.${key}`);\n }\n Object.defineProperty(result, key, {\n value: clonePureData(descriptor.value, `${path}.${key}`, seen),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\nexport function clonePureState(value: unknown): Record<string, unknown> {\n const state = clonePureData(value, 'state');\n if (!state || typeof state !== 'object' || Array.isArray(state)) {\n throw new TypeError('Worker state must be a plain JSON record');\n }\n return state as Record<string, unknown>;\n}\n","/**\n * Worker policy, startup, protocol, crash, or serialization failure.\n * Function deadlines retain the runtime's FunctionTimeoutError identity.\n */\nexport class WorkerExecutionError extends Error {\n public readonly functionName: string;\n\n constructor(functionName: string, message: string, cause?: unknown) {\n super(`Worker function \"${functionName}\": ${message}`, { cause });\n this.name = 'WorkerExecutionError';\n this.functionName = functionName;\n }\n}\n","// Authored JavaScript passed to a CommonJS eval worker. No source is evaluated\n// in the parent, and no separate import-time worker entry needs publishing.\nexport const workerSource = String.raw`\n\"use strict\";\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nconst keepAlive = setInterval(() => {}, 1000000);\nfunction freeze(value) {\n if (value && typeof value === \"object\") {\n for (const child of Object.values(value)) freeze(child);\n Object.freeze(value);\n }\n return value;\n}\nfunction failure(error) {\n parentPort.postMessage({\n type: \"error\",\n error: {\n name: error && typeof error.name === \"string\" ? error.name : \"Error\",\n message: error && typeof error.message === \"string\" ? error.message : String(error),\n stack: error && typeof error.stack === \"string\" ? error.stack : undefined\n }\n });\n}\nparentPort.once(\"message\", (message) => {\n if (!message || message.type !== \"run\") return;\n void (async () => {\n try {\n const source = '\"use strict\"; return async function(input, state, ctx) {' +\n '\"use strict\"; return { output: await (async () => {\\n' +\n workerData.code + '\\n})(), state }; }; \\n//# sourceURL=' + workerData.sourceUrl;\n const implementation = new Function(source)();\n const state = workerData.kind === \"query\" ? freeze(workerData.state) : workerData.state;\n parentPort.postMessage({ type: \"running\" });\n const result = await implementation(workerData.input, state, Object.freeze(Object.create(null)));\n parentPort.postMessage({ type: \"result\", result });\n } catch (error) {\n failure(error);\n }\n })().catch(failure);\n});\nparentPort.postMessage({ type: \"ready\" });\n`;\n","import { FunctionTimeoutError } from '@onereach/state-machine-runtime';\nimport type { RuntimeExecutionOptions, RuntimeImplementationExecution } from '@onereach/state-machine-runtime';\nimport { Worker } from 'node:worker_threads';\n\nimport { clonePureData, clonePureState } from './data.ts';\nimport { WorkerExecutionError } from './errors.ts';\nimport { workerSource } from './runner.ts';\nimport type { WorkerRuntimeDiagnostics } from './types.ts';\n\ninterface Definition {\n name: string;\n code: string;\n kind: 'query' | 'mutation';\n sourceUrl: string;\n timeoutMs: number;\n maxOldGenerationSizeMb: number;\n}\n\nexport function startWorker(\n definition: Definition,\n input: unknown,\n state: unknown,\n options: RuntimeExecutionOptions,\n diagnostics: WorkerRuntimeDiagnostics,\n): RuntimeImplementationExecution {\n const { signal } = options;\n signal?.throwIfAborted();\n const data = {\n code: definition.code,\n kind: definition.kind,\n sourceUrl: definition.sourceUrl,\n input: clonePureData(input, 'input'),\n state: clonePureState(state),\n };\n const deadline = performance.now() + definition.timeoutMs;\n let worker: Worker;\n try {\n worker = new Worker(workerSource, {\n eval: true,\n workerData: data,\n env: {},\n execArgv: [],\n resourceLimits: { maxOldGenerationSizeMb: definition.maxOldGenerationSizeMb, stackSizeMb: 4 },\n });\n } catch (error) {\n throw new WorkerExecutionError(definition.name, 'worker startup failed', error);\n }\n const workerId = worker.threadId;\n let resolveResult!: (value: { output: unknown; state: Record<string, unknown> }) => void;\n let rejectResult!: (reason: unknown) => void;\n // eslint-disable-next-line unicorn/prefer-promise-with-resolvers -- Repository type libraries target ES2022.\n const result = new Promise<{ output: unknown; state: Record<string, unknown> }>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n let complete!: () => void;\n\n const completion = new Promise<void>((resolve) => {\n complete = () => resolve();\n });\n let candidate: { output: unknown; state: Record<string, unknown> } | undefined;\n let isStarted = false;\n let isRunning = false;\n let isExited = false;\n let isTerminationRequested = false;\n const report = (phase: 'started' | 'exited' | 'termination-failed', extra = {}) => {\n try {\n const reporting = diagnostics.onLifecycle?.({ functionName: definition.name, workerId, phase, ...extra });\n if (reporting) void reporting.catch(() => {});\n } catch {\n // Observability cannot change execution or prevent confirmed-exit cleanup.\n }\n };\n const terminate = () => {\n if (isExited || isTerminationRequested) return;\n isTerminationRequested = true;\n void worker.terminate().catch((error: unknown) => {\n report('termination-failed', { cause: error });\n // Completion deliberately remains pending unless the exit event arrives.\n });\n };\n const fail = (error: unknown) => {\n rejectResult(error);\n terminate();\n };\n const onAbort = () => {\n if (isStarted) return;\n signal?.removeEventListener('abort', onAbort);\n fail(signal?.reason);\n };\n const timer = setTimeout(\n () => {\n signal?.removeEventListener('abort', onAbort);\n fail(new FunctionTimeoutError(definition.name, definition.timeoutMs));\n },\n Math.max(0, deadline - performance.now()),\n );\n worker.on('message', (message: unknown) => {\n if (isExited || isTerminationRequested) return;\n try {\n if (!message || typeof message !== 'object' || !('type' in message)) {\n throw new WorkerExecutionError(definition.name, 'invalid response');\n }\n if (message.type === 'ready') {\n if (isStarted) throw new WorkerExecutionError(definition.name, 'duplicate readiness response');\n signal?.throwIfAborted();\n isStarted = true;\n signal?.removeEventListener('abort', onAbort);\n worker.postMessage({ type: 'run' });\n } else if (message.type === 'running') {\n if (!isStarted || isRunning) throw new WorkerExecutionError(definition.name, 'invalid running response');\n isRunning = true;\n report('started');\n } else if (message.type === 'result' && 'result' in message) {\n const value = message.result;\n if (!isStarted || !value || typeof value !== 'object' || !('output' in value) || !('state' in value)) {\n throw new WorkerExecutionError(definition.name, 'invalid result');\n }\n candidate = {\n output: value.output === undefined ? undefined : clonePureData(value.output, 'output'),\n state: clonePureState(value.state),\n };\n // Stop timers/tasks in this worker too; never accept a candidate before exit.\n terminate();\n } else if (message.type === 'error' && 'error' in message) {\n const remote = message.error;\n const detail =\n remote && typeof remote === 'object' && 'message' in remote && typeof remote.message === 'string'\n ? remote.message\n : 'implementation failed';\n throw new WorkerExecutionError(definition.name, detail, remote);\n } else {\n throw new WorkerExecutionError(definition.name, 'unexpected response');\n }\n } catch (error) {\n fail(error);\n }\n });\n worker.on('error', (error) => {\n fail(new WorkerExecutionError(definition.name, 'worker failed', error));\n });\n worker.once('exit', (exitCode) => {\n isExited = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n if (candidate) resolveResult(candidate);\n else rejectResult(new WorkerExecutionError(definition.name, `exited without a result (code ${exitCode})`));\n worker.removeAllListeners('message');\n worker.removeAllListeners('error');\n report('exited', { exitCode });\n complete();\n });\n signal?.addEventListener('abort', onAbort, { once: true });\n if (signal?.aborted) onAbort();\n return Object.freeze({ result, completion });\n}\n","import type { ReadonlyStateMachineFunctionDefinition } from '@onereach/state-machine-contracts';\nimport { compileTrustedJavaScriptImplementation } from '@onereach/state-machine-runtime';\nimport type { RuntimeImplementation, RuntimeImplementationCompiler } from '@onereach/state-machine-runtime';\n\nimport { clonePureData, clonePureState } from './data.ts';\nimport { WorkerExecutionError } from './errors.ts';\nimport { startWorker } from './execution.ts';\nimport type { WorkerImplementationCompilerOptions, WorkerRuntimeDiagnostics } from './types.ts';\n\nexport class WorkerImplementationCompiler implements RuntimeImplementationCompiler {\n private readonly select: WorkerImplementationCompilerOptions['select'];\n private readonly defaultTimeoutMs: number;\n private readonly maxOldGenerationSizeMb: number;\n private readonly diagnostics: WorkerRuntimeDiagnostics;\n\n constructor(options: WorkerImplementationCompilerOptions = {}, diagnostics: WorkerRuntimeDiagnostics = {}) {\n if (options.select !== undefined && typeof options.select !== 'function')\n throw new TypeError('Worker selection filter must be a function');\n this.select = options.select;\n this.defaultTimeoutMs = options.defaultTimeoutMs ?? 1000;\n this.maxOldGenerationSizeMb = options.maxOldGenerationSizeMb ?? 64;\n if (\n !Number.isSafeInteger(this.defaultTimeoutMs) ||\n this.defaultTimeoutMs < 1 ||\n this.defaultTimeoutMs > 2_147_483_647\n ) {\n throw new RangeError('Worker defaultTimeoutMs must be within the positive timer range');\n }\n if (\n !Number.isSafeInteger(this.maxOldGenerationSizeMb) ||\n this.maxOldGenerationSizeMb < 8 ||\n this.maxOldGenerationSizeMb > 4096\n ) {\n throw new RangeError('Worker maxOldGenerationSizeMb must be an integer from 8 to 4096');\n }\n this.diagnostics = Object.freeze({ onLifecycle: diagnostics.onLifecycle });\n }\n\n public compile<TContext>(\n templateId: string,\n definition: ReadonlyStateMachineFunctionDefinition,\n ): RuntimeImplementation<TContext> {\n const source = definition.implementation;\n if (definition.annotations?.pure !== true || (this.select && !this.select(templateId, definition)))\n return compileTrustedJavaScriptImplementation<TContext>(templateId, definition);\n if (\n source.runtime !== 'javascript' ||\n source.abi !== 'state-machine-function-v1' ||\n source.format !== 'async-function-body'\n ) {\n throw new WorkerExecutionError(definition.name, 'unsupported implementation');\n }\n if (source.capabilities.length > 0)\n throw new WorkerExecutionError(definition.name, 'pure functions cannot request host capabilities');\n const timeoutMs = source.timeoutMs ?? this.defaultTimeoutMs;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) {\n throw new WorkerExecutionError(definition.name, 'timeoutMs must be within the positive timer range');\n }\n const prepared = Object.freeze({\n name: definition.name,\n code: source.code,\n kind: definition.kind,\n sourceUrl: `state-machine://${encodeURIComponent(templateId)}/${encodeURIComponent(definition.name)}`,\n timeoutMs,\n maxOldGenerationSizeMb: this.maxOldGenerationSizeMb,\n });\n const start: NonNullable<RuntimeImplementation<TContext>['startExecution']> = (\n input,\n state,\n _context,\n options = {},\n ) => startWorker(prepared, input, state, options, this.diagnostics);\n const implementation = (input: Record<string, unknown>, state: Record<string, unknown>, context: TContext) =>\n start(input, state, context).result;\n return Object.freeze(\n Object.assign(implementation, {\n startExecution: start,\n contextPolicy: 'none' as const,\n validateData: (input: unknown, state: object) => {\n clonePureData(input, 'input');\n clonePureState(state);\n },\n }),\n );\n }\n}\n\nexport * from './errors.ts';\nexport type * from './types.ts';\n"],"mappings":"gKAIA,SAAgB,EAAc,EAAgB,EAAc,EAAO,IAAI,IAAwB,CAE7F,GADI,IAAU,MAAQ,OAAO,GAAU,UAAY,OAAO,GAAU,WAChE,OAAO,GAAU,UAAY,OAAO,SAAS,CAAK,EAAG,OAAO,EAChE,GAAI,OAAO,GAAU,WAAY,GAAkB,EAAK,IAAI,CAAK,EAC/D,MAAU,UAAU,sCAAsC,GAAM,EAElE,IAAM,EAAU,MAAM,QAAQ,CAAK,EAC7B,EAAY,OAAO,eAAe,CAAK,EAC7C,GAAI,CAAC,GAAW,IAAc,MAAQ,IAAc,OAAO,UACzD,MAAU,UAAU,qCAAqC,GAAM,EAEjE,EAAK,IAAI,CAAK,EACd,GAAI,CACF,IAAM,EAAc,OAAO,0BAA0B,CAAK,EACpD,EAAO,QAAQ,QAAQ,CAAW,EACxC,GAAI,EAAS,CACX,GAAI,EAAK,SAAW,EAAM,OAAS,EAAG,MAAU,UAAU,6CAA6C,GAAM,EAC7G,IAAM,EAAoB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AAY,CAAU,EAChF,GACE,EAAO,UAAY,cACnB,EAAO,MAAQ,6BACf,EAAO,SAAW,sBAElB,MAAM,IAAI,EAAqB,EAAW,KAAM,4BAA4B,EAE9E,GAAI,EAAO,aAAa,OAAS,EAC/B,MAAM,IAAI,EAAqB,EAAW,KAAM,iDAAiD,EACnG,IAAM,EAAY,EAAO,WAAa,KAAK,iBAC3C,GAAI,CAAC,OAAO,cAAc,CAAS,GAAK,EAAY,GAAK,EAAY,WACnE,MAAM,IAAI,EAAqB,EAAW,KAAM,mDAAmD,EAErG,IAAM,EAAW,OAAO,OAAO,CAC7B,KAAM,EAAW,KACjB,KAAM,EAAO,KACb,KAAM,EAAW,KACjB,UAAW,mBAAmB,mBAAmB,CAAU,EAAE,GAAG,mBAAmB,EAAW,IAAI,IAClG,YACA,uBAAwB,KAAK,sBAC/B,CAAC,EACK,GACJ,EACA,EACA,EACA,EAAU,CAAC,IACR,EAAY,EAAU,EAAO,EAAO,EAAS,KAAK,WAAW,EAGlE,OAAO,OAAO,OACZ,OAAO,QAHe,EAAgC,EAAgC,IACtF,EAAM,EAAO,EAAO,CAAO,CAAC,CAAC,OAEC,CAC5B,eAAgB,EAChB,cAAe,OACf,cAAe,EAAgB,IAAkB,CAC/C,EAAc,EAAO,OAAO,EAC5B,EAAe,CAAK,CACtB,CACF,CAAC,CACH,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@onereach/state-machine-runtime-node-worker",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-framework.2",
4
+ "description": "Opt-in terminable Node worker backend for pure State Machine functions",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "Apache-2.0",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "dependencies": {
15
+ "@onereach/state-machine-contracts": "1.0.0-framework.12",
16
+ "@onereach/state-machine-runtime": "1.0.0-framework.13"
17
+ },
18
+ "devDependencies": {
19
+ "@arethetypeswrong/core": "^0.18.5",
20
+ "@onereach/state-machine-driver-memory": "1.0.0-framework.12",
21
+ "@onereach/state-machine-json-schema-ajv": "1.0.0-framework.12",
22
+ "@onereach/state-machine-service": "1.0.0-framework.13",
23
+ "@onereach/state-machine-store": "1.0.0-framework.12",
24
+ "@onereach/state-machine-validation": "1.0.0-framework.2",
25
+ "@types/node": "^24.13.3",
26
+ "publint": "^0.3.24",
27
+ "tsdown": "^0.22.14",
28
+ "typescript": "^6.0.3",
29
+ "vitest": "^4.1.11"
30
+ },
31
+ "exports": {
32
+ ".": "./dist/index.mjs",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown --config tsdown.config.mts",
37
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile .cache/typecheck/source.tsbuildinfo && tsc --noEmit -p test/tsconfig.json --incremental --tsBuildInfoFile .cache/typecheck/test.tsbuildinfo",
38
+ "test": "pnpm run unit",
39
+ "unit": "vitest run",
40
+ "unit:coverage": "vitest run --coverage"
41
+ }
6
42
  }