@aztec-foundation/ipc-runtime 7.0.0-nightly.20261031 → 7.0.0-nightly.20261109
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/dest/backend_registry.d.ts +18 -0
- package/dest/backend_registry.js +25 -0
- package/dest/index.d.ts +2 -0
- package/dest/index.js +2 -0
- package/dest/service.d.ts +68 -0
- package/dest/service.js +146 -0
- package/dest/spawned_backend.d.ts +7 -11
- package/dest/spawned_backend.js +19 -8
- package/dest/wasm/backend.d.ts +93 -0
- package/dest/wasm/backend.js +367 -0
- package/dest/wasm/browser/index.d.ts +10 -0
- package/dest/wasm/browser/index.js +19 -0
- package/dest/wasm/browser/main.worker.d.ts +1 -0
- package/dest/wasm/browser/main.worker.js +8 -0
- package/dest/wasm/browser/platform.d.ts +6 -0
- package/dest/wasm/browser/platform.js +33 -0
- package/dest/wasm/browser/thread.worker.d.ts +1 -0
- package/dest/wasm/browser/thread.worker.js +4 -0
- package/dest/wasm/entry.d.ts +20 -0
- package/dest/wasm/entry.js +19 -0
- package/dest/wasm/host.d.ts +57 -0
- package/dest/wasm/host.js +206 -0
- package/dest/wasm/main_worker.d.ts +11 -0
- package/dest/wasm/main_worker.js +65 -0
- package/dest/wasm/module_source.d.ts +18 -0
- package/dest/wasm/module_source.js +84 -0
- package/dest/wasm/node/index.d.ts +7 -0
- package/dest/wasm/node/index.js +12 -0
- package/dest/wasm/node/main.worker.d.ts +1 -0
- package/dest/wasm/node/main.worker.js +6 -0
- package/dest/wasm/node/platform.d.ts +7 -0
- package/dest/wasm/node/platform.js +40 -0
- package/dest/wasm/node/thread.worker.d.ts +1 -0
- package/dest/wasm/node/thread.worker.js +4 -0
- package/dest/wasm/platform.d.ts +34 -0
- package/dest/wasm/platform.js +13 -0
- package/dest/wasm/service.d.ts +19 -0
- package/dest/wasm/service.js +42 -0
- package/dest/wasm/thread_worker.d.ts +8 -0
- package/dest/wasm/thread_worker.js +55 -0
- package/dest/wasm/wasi_shim.d.ts +26 -0
- package/dest/wasm/wasi_shim.js +132 -0
- package/dest/wasm_backend.test.d.ts +1 -0
- package/dest/wasm_backend.test.js +142 -0
- package/dest/wasm_engine.test.d.ts +1 -0
- package/dest/wasm_engine.test.js +309 -0
- package/dest/wasm_engine_stub.worker.d.ts +1 -0
- package/dest/wasm_engine_stub.worker.js +1 -0
- package/dest/wasm_module_source.test.d.ts +1 -0
- package/dest/wasm_module_source.test.js +36 -0
- package/dest/wasm_platform.test.d.ts +1 -0
- package/dest/wasm_platform.test.js +51 -0
- package/package.json +29 -3
- package/scripts/copy_cross.sh +38 -0
- package/scripts/prepare_arch_packages.mjs +73 -0
- package/src/backend_registry.ts +54 -0
- package/src/index.ts +15 -0
- package/src/service.ts +237 -0
- package/src/spawned_backend.ts +27 -19
- package/src/wasm/backend.ts +462 -0
- package/src/wasm/browser/index.ts +40 -0
- package/src/wasm/browser/main.worker.ts +16 -0
- package/src/wasm/browser/platform.ts +51 -0
- package/src/wasm/browser/thread.worker.ts +5 -0
- package/src/wasm/entry.ts +47 -0
- package/src/wasm/host.ts +274 -0
- package/src/wasm/main_worker.ts +77 -0
- package/src/wasm/module_source.ts +125 -0
- package/src/wasm/node/index.ts +33 -0
- package/src/wasm/node/main.worker.ts +10 -0
- package/src/wasm/node/platform.ts +57 -0
- package/src/wasm/node/thread.worker.ts +5 -0
- package/src/wasm/platform.ts +47 -0
- package/src/wasm/service.ts +57 -0
- package/src/wasm/thread_worker.ts +56 -0
- package/src/wasm/wasi_shim.ts +170 -0
- package/src/wasm_backend.test.ts +155 -0
- package/src/wasm_engine.test.ts +377 -0
- package/src/wasm_engine_stub.worker.ts +2 -0
- package/src/wasm_module_source.test.ts +54 -0
- package/src/wasm_platform.test.ts +60 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { IpcClientAsync, IpcClientSync } from "./types.js";
|
|
2
|
+
export type { IpcClientAsync, IpcClientSync };
|
|
3
|
+
/**
|
|
4
|
+
* Backends a native package registers for a service, so an app that installs it needs no wiring.
|
|
5
|
+
* This is how a host with no backend of its own is served — React Native, where Hermes has no
|
|
6
|
+
* WebAssembly and no workers, and the service is reached through a linked library instead.
|
|
7
|
+
*/
|
|
8
|
+
export interface RegisteredBackends {
|
|
9
|
+
async?: () => Promise<IpcClientAsync> | IpcClientAsync;
|
|
10
|
+
sync?: () => Promise<IpcClientSync> | IpcClientSync;
|
|
11
|
+
}
|
|
12
|
+
/** Make `factories` the backends for `service`; a native backend package calls this when imported. */
|
|
13
|
+
export declare function registerBackend(service: string, factories: RegisteredBackends): void;
|
|
14
|
+
/**
|
|
15
|
+
* The registered backend for a service, or a message naming what to install. `hint` is the
|
|
16
|
+
* package a caller should be told about.
|
|
17
|
+
*/
|
|
18
|
+
export declare function registeredBackend<K extends keyof RegisteredBackends>(service: string, kind: K, hint: string): NonNullable<RegisteredBackends[K]>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// A well-known global rather than an import in either direction, so a native backend package and
|
|
2
|
+
// the generated client package need not depend on each other, and two copies of this module in
|
|
3
|
+
// one app still agree.
|
|
4
|
+
const REGISTRY_KEY = Symbol.for("@aztec-foundation/ipc-runtime/backends");
|
|
5
|
+
function registry() {
|
|
6
|
+
const global = globalThis;
|
|
7
|
+
return (global[REGISTRY_KEY] ??= new Map());
|
|
8
|
+
}
|
|
9
|
+
/** Make `factories` the backends for `service`; a native backend package calls this when imported. */
|
|
10
|
+
export function registerBackend(service, factories) {
|
|
11
|
+
registry().set(service, factories);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The registered backend for a service, or a message naming what to install. `hint` is the
|
|
15
|
+
* package a caller should be told about.
|
|
16
|
+
*/
|
|
17
|
+
export function registeredBackend(service, kind, hint) {
|
|
18
|
+
const factory = registry().get(service)?.[kind];
|
|
19
|
+
if (!factory) {
|
|
20
|
+
throw new Error(`${hint}: no ${kind === "sync" ? "synchronous " : ""}backend registered for ${service}. ` +
|
|
21
|
+
"Install a native backend package for it (registering itself when imported), or pass one " +
|
|
22
|
+
"as options.backend.");
|
|
23
|
+
}
|
|
24
|
+
return factory;
|
|
25
|
+
}
|
package/dest/index.d.ts
CHANGED
|
@@ -6,3 +6,5 @@ export { UdsIpcClient, type UdsIpcClientConnectOptions } from "./uds_client.js";
|
|
|
6
6
|
export { UdsIpcServer, type IpcServerHandler } from "./uds_server.js";
|
|
7
7
|
export { NapiShmSyncClient, NapiShmAsyncClient, createNapiShmSyncClient, createNapiShmAsyncClient, type NapiMsgpackClientSync, type NapiMsgpackClientAsync, } from "./shm_client.js";
|
|
8
8
|
export { findIpcRuntimeNapi, loadIpcRuntimeNapi, type Platform, } from "./native_loader.js";
|
|
9
|
+
export { type ServiceBinary, type ServiceProcessOptions, findServiceBinary, pickServiceBackend, runServiceBinary, serviceProcessEnv, spawnServiceBackend, spawnServiceBackendSync, } from "./service.js";
|
|
10
|
+
export { type RegisteredBackends, registerBackend, registeredBackend, } from "./backend_registry.js";
|
package/dest/index.js
CHANGED
|
@@ -5,3 +5,5 @@ export { UdsIpcClient } from "./uds_client.js";
|
|
|
5
5
|
export { UdsIpcServer } from "./uds_server.js";
|
|
6
6
|
export { NapiShmSyncClient, NapiShmAsyncClient, createNapiShmSyncClient, createNapiShmAsyncClient, } from "./shm_client.js";
|
|
7
7
|
export { findIpcRuntimeNapi, loadIpcRuntimeNapi, } from "./native_loader.js";
|
|
8
|
+
export { findServiceBinary, pickServiceBackend, runServiceBinary, serviceProcessEnv, spawnServiceBackend, spawnServiceBackendSync, } from "./service.js";
|
|
9
|
+
export { registerBackend, registeredBackend, } from "./backend_registry.js";
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { SpawnedProcessBackend, SpawnedProcessBackendSync } from "./spawned_backend.js";
|
|
2
|
+
import type { IpcClientAsync, IpcClientSync } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* How a generated client package reaches its service as a spawned process. Everything here is
|
|
5
|
+
* fixed at generation time from the schema and the flags: the package supplies it, this module
|
|
6
|
+
* does the work, so the same logic is not regenerated into every package.
|
|
7
|
+
*/
|
|
8
|
+
export interface ServiceBinary {
|
|
9
|
+
/** Binary name, used for the arch-package lookup, log labels and errors. */
|
|
10
|
+
name: string;
|
|
11
|
+
/** Environment variable that overrides the binary's path. */
|
|
12
|
+
envVar: string;
|
|
13
|
+
/** npm package holding the binary, per platform (`process.arch`-`process.platform`). */
|
|
14
|
+
archPackages: Record<string, string>;
|
|
15
|
+
/** Argv template; each '{path}' is replaced with the backend's ipc path. */
|
|
16
|
+
ipcPathArgs: string[];
|
|
17
|
+
/** Prefix for the per-instance ipc path. */
|
|
18
|
+
instancePrefix: string;
|
|
19
|
+
/** Directory of the package that owns the arch packages, for the sibling fallback. */
|
|
20
|
+
packageDir: string;
|
|
21
|
+
}
|
|
22
|
+
/** Options a caller may give when the service runs as a spawned process. */
|
|
23
|
+
export interface ServiceProcessOptions {
|
|
24
|
+
binaryPath?: string;
|
|
25
|
+
transport?: "uds" | "shm";
|
|
26
|
+
/** Threads the service may use, exported to it as HARDWARE_CONCURRENCY and RAYON_NUM_THREADS. */
|
|
27
|
+
threads?: number;
|
|
28
|
+
logger?: (msg: string) => void;
|
|
29
|
+
connectTimeoutMs?: number;
|
|
30
|
+
env?: NodeJS.ProcessEnv;
|
|
31
|
+
extraArgs?: string[];
|
|
32
|
+
respawn?: boolean;
|
|
33
|
+
/** When true, an idle backend does not keep the process alive; see SpawnedProcessBackendOptions. */
|
|
34
|
+
unref?: boolean;
|
|
35
|
+
clientId?: number;
|
|
36
|
+
napiPath?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The binary to run: `customPath` if given, else the package's environment variable, else the
|
|
40
|
+
* installed arch package for this platform. Null when none of those yields an existing file.
|
|
41
|
+
*/
|
|
42
|
+
export declare function findServiceBinary(binary: ServiceBinary, customPath?: string): string | null;
|
|
43
|
+
/** The child's environment: the caller's, plus the thread count under both names services read. */
|
|
44
|
+
export declare function serviceProcessEnv(options: Pick<ServiceProcessOptions, "threads" | "env">): NodeJS.ProcessEnv | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Spawn the service and connect to it. Process lifecycle — connectivity, death detection,
|
|
47
|
+
* optional respawn, teardown — is owned by the backend and never leaks onto the caller's API.
|
|
48
|
+
*/
|
|
49
|
+
export declare function spawnServiceBackend(binary: ServiceBinary, defaultTransport: "uds" | "shm", options?: ServiceProcessOptions): Promise<SpawnedProcessBackend>;
|
|
50
|
+
/** The synchronous form: shared memory is the one transport with a synchronous client. */
|
|
51
|
+
export declare function spawnServiceBackendSync(binary: ServiceBinary, options?: ServiceProcessOptions): Promise<SpawnedProcessBackendSync>;
|
|
52
|
+
/** Run the service binary as a CLI, forwarding argv and exit status. Backs a package's `bin`. */
|
|
53
|
+
export declare function runServiceBinary(binary: ServiceBinary, packageName: string, argv: string[]): never;
|
|
54
|
+
/**
|
|
55
|
+
* Which backend to use, given what this host can offer. Unset: the process when its binary
|
|
56
|
+
* resolves, else wasm. A name forces one, with no fallback to the other.
|
|
57
|
+
*/
|
|
58
|
+
export declare function pickServiceBackend<T extends IpcClientAsync | IpcClientSync>(wanted: "process" | "wasm" | T | undefined, choices: {
|
|
59
|
+
label: string;
|
|
60
|
+
process?: {
|
|
61
|
+
available: () => boolean;
|
|
62
|
+
create: () => Promise<T>;
|
|
63
|
+
};
|
|
64
|
+
wasm?: {
|
|
65
|
+
create: () => Promise<T>;
|
|
66
|
+
};
|
|
67
|
+
logger?: (msg: string) => void;
|
|
68
|
+
}): Promise<T>;
|
package/dest/service.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { SpawnedProcessBackend, SpawnedProcessBackendSync, } from "./spawned_backend.js";
|
|
6
|
+
import { IpcSpawnError } from "./errors.js";
|
|
7
|
+
function platformKey() {
|
|
8
|
+
return `${process.arch}-${process.platform}`;
|
|
9
|
+
}
|
|
10
|
+
function archPackageDir(binary) {
|
|
11
|
+
const packageName = binary.archPackages[platformKey()];
|
|
12
|
+
if (!packageName) {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
const require = createRequire(import.meta.url);
|
|
17
|
+
return path.dirname(require.resolve(`${packageName}/package.json`));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// Not installed as a dependency: fall back to a copy prepared inside the owning package,
|
|
21
|
+
// which is how a repository checkout runs before anything is published.
|
|
22
|
+
const sibling = path.join(binary.packageDir, "packages", packageName.split("/").pop());
|
|
23
|
+
return fs.existsSync(path.join(sibling, "package.json")) ? sibling : null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The binary to run: `customPath` if given, else the package's environment variable, else the
|
|
28
|
+
* installed arch package for this platform. Null when none of those yields an existing file.
|
|
29
|
+
*/
|
|
30
|
+
export function findServiceBinary(binary, customPath) {
|
|
31
|
+
const explicit = customPath ?? process.env[binary.envVar];
|
|
32
|
+
if (explicit) {
|
|
33
|
+
return fs.existsSync(explicit) ? path.resolve(explicit) : null;
|
|
34
|
+
}
|
|
35
|
+
const dir = archPackageDir(binary);
|
|
36
|
+
if (dir) {
|
|
37
|
+
const candidate = path.join(dir, binary.name);
|
|
38
|
+
if (fs.existsSync(candidate)) {
|
|
39
|
+
return candidate;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
/** The child's environment: the caller's, plus the thread count under both names services read. */
|
|
45
|
+
export function serviceProcessEnv(options) {
|
|
46
|
+
if (options.threads === undefined) {
|
|
47
|
+
return options.env;
|
|
48
|
+
}
|
|
49
|
+
const threads = String(options.threads);
|
|
50
|
+
return {
|
|
51
|
+
HARDWARE_CONCURRENCY: threads,
|
|
52
|
+
RAYON_NUM_THREADS: threads,
|
|
53
|
+
...options.env,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function resolveOrThrow(binary, binaryPath) {
|
|
57
|
+
const resolved = findServiceBinary(binary, binaryPath);
|
|
58
|
+
if (!resolved) {
|
|
59
|
+
throw new IpcSpawnError(`${binary.name} binary not found`,
|
|
60
|
+
/*retry=*/ false);
|
|
61
|
+
}
|
|
62
|
+
return resolved;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Spawn the service and connect to it. Process lifecycle — connectivity, death detection,
|
|
66
|
+
* optional respawn, teardown — is owned by the backend and never leaks onto the caller's API.
|
|
67
|
+
*/
|
|
68
|
+
export function spawnServiceBackend(binary, defaultTransport, options = {}) {
|
|
69
|
+
return SpawnedProcessBackend.spawn({
|
|
70
|
+
binaryPath: resolveOrThrow(binary, options.binaryPath),
|
|
71
|
+
binaryName: binary.name,
|
|
72
|
+
instancePrefix: binary.instancePrefix,
|
|
73
|
+
ipcPathArgs: binary.ipcPathArgs,
|
|
74
|
+
transport: options.transport ?? defaultTransport,
|
|
75
|
+
logger: options.logger,
|
|
76
|
+
connectTimeoutMs: options.connectTimeoutMs,
|
|
77
|
+
env: serviceProcessEnv(options),
|
|
78
|
+
extraArgs: options.extraArgs,
|
|
79
|
+
respawn: options.respawn,
|
|
80
|
+
unref: options.unref,
|
|
81
|
+
clientId: options.clientId,
|
|
82
|
+
napiPath: options.napiPath,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/** The synchronous form: shared memory is the one transport with a synchronous client. */
|
|
86
|
+
export function spawnServiceBackendSync(binary, options = {}) {
|
|
87
|
+
if (options.transport !== undefined && options.transport !== "shm") {
|
|
88
|
+
throw new Error(`${binary.name}: the synchronous backend needs the shm transport`);
|
|
89
|
+
}
|
|
90
|
+
return SpawnedProcessBackendSync.spawn({
|
|
91
|
+
binaryPath: resolveOrThrow(binary, options.binaryPath),
|
|
92
|
+
binaryName: binary.name,
|
|
93
|
+
instancePrefix: `${binary.instancePrefix}-sync`,
|
|
94
|
+
ipcPathArgs: binary.ipcPathArgs,
|
|
95
|
+
transport: "shm",
|
|
96
|
+
logger: options.logger,
|
|
97
|
+
connectTimeoutMs: options.connectTimeoutMs,
|
|
98
|
+
env: serviceProcessEnv(options),
|
|
99
|
+
extraArgs: options.extraArgs,
|
|
100
|
+
unref: options.unref,
|
|
101
|
+
clientId: options.clientId ?? 0,
|
|
102
|
+
napiPath: options.napiPath,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/** Run the service binary as a CLI, forwarding argv and exit status. Backs a package's `bin`. */
|
|
106
|
+
export function runServiceBinary(binary, packageName, argv) {
|
|
107
|
+
const binaryPath = findServiceBinary(binary);
|
|
108
|
+
if (!binaryPath) {
|
|
109
|
+
console.error(`${binary.name}: native binary not found. Install the matching ` +
|
|
110
|
+
`'${packageName}-<platform>' package, set ${binary.envVar}, or pass its path.`);
|
|
111
|
+
process.exit(1);
|
|
112
|
+
}
|
|
113
|
+
const result = spawnSync(binaryPath, argv, { stdio: "inherit" });
|
|
114
|
+
if (result.error) {
|
|
115
|
+
console.error(result.error.message);
|
|
116
|
+
process.exit(1);
|
|
117
|
+
}
|
|
118
|
+
process.exit(result.status ?? 1);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Which backend to use, given what this host can offer. Unset: the process when its binary
|
|
122
|
+
* resolves, else wasm. A name forces one, with no fallback to the other.
|
|
123
|
+
*/
|
|
124
|
+
export async function pickServiceBackend(wanted, choices) {
|
|
125
|
+
if (typeof wanted === "object") {
|
|
126
|
+
return wanted;
|
|
127
|
+
}
|
|
128
|
+
const { process: proc, wasm } = choices;
|
|
129
|
+
if (proc &&
|
|
130
|
+
(wanted === "process" ||
|
|
131
|
+
(wanted === undefined && (!wasm || proc.available())))) {
|
|
132
|
+
try {
|
|
133
|
+
return await proc.create();
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
if (wanted === "process" || !wasm) {
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
choices.logger?.(`${choices.label} process unavailable (${err.message}); falling back to wasm`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (wasm && (wanted === undefined || wanted === "wasm")) {
|
|
143
|
+
return wasm.create();
|
|
144
|
+
}
|
|
145
|
+
throw new Error(`${choices.label}: no such backend here: ${String(wanted)}`);
|
|
146
|
+
}
|
|
@@ -24,19 +24,15 @@ export interface SpawnedProcessBackendOptions {
|
|
|
24
24
|
*/
|
|
25
25
|
respawn?: boolean;
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
27
|
+
* When true, an idle backend does not keep the caller's process alive: you never have to
|
|
28
|
+
* destroy() it for node to exit. Work in progress still holds the loop — the connect while
|
|
29
|
+
* the server starts, and each call until its response arrives — so nothing exits early.
|
|
30
|
+
*
|
|
31
|
+
* The one thing given up is trailing output: the child's stdout/stderr pipes, which exist
|
|
32
|
+
* only when `logger` is set, stop holding the loop too, so a process that exits while the
|
|
33
|
+
* child is mid-line loses it.
|
|
30
34
|
*/
|
|
31
35
|
unref?: boolean;
|
|
32
|
-
/**
|
|
33
|
-
* Also unref the child's stdout/stderr pipes, which exist only when
|
|
34
|
-
* `logger` is set. Separate from `unref` because those pipes are how the
|
|
35
|
-
* caller sees the child's output: unref'ing them lets the process exit with
|
|
36
|
-
* log lines still unread, so it is opt-in even when the child itself is
|
|
37
|
-
* unref'd.
|
|
38
|
-
*/
|
|
39
|
-
unrefStdio?: boolean;
|
|
40
36
|
/** SHM only: fixed client slot id. When unset the client self-allocates a free slot. */
|
|
41
37
|
clientId?: number;
|
|
42
38
|
/** SHM only: override the native addon path. */
|
package/dest/spawned_backend.js
CHANGED
|
@@ -50,6 +50,19 @@ async function removeStaleIpcPath(transport, ipcPath) {
|
|
|
50
50
|
* live logger when there is one and to `logFd` otherwise. Shared by the async
|
|
51
51
|
* and sync backends so process setup has exactly one implementation.
|
|
52
52
|
*/
|
|
53
|
+
/**
|
|
54
|
+
* Stop the child and its output pipes holding the caller's event loop. Called once the backend is
|
|
55
|
+
* connected, never before: until then the child is the only thing keeping the process alive while
|
|
56
|
+
* the server starts, and unref'ing it lets node exit mid-startup. After it, each transport refs
|
|
57
|
+
* itself for the duration of a call (see UdsIpcClient's idle unref and the shm client's TSFN
|
|
58
|
+
* acquire/release), so only a genuinely idle backend is invisible to the loop.
|
|
59
|
+
*/
|
|
60
|
+
function unrefWhenIdle(child) {
|
|
61
|
+
child.unref();
|
|
62
|
+
// The stdio pipes are net.Sockets at runtime but typed as Readable.
|
|
63
|
+
child.stdout?.unref?.();
|
|
64
|
+
child.stderr?.unref?.();
|
|
65
|
+
}
|
|
53
66
|
function spawnServerProcess(options, ipcPath, logFd) {
|
|
54
67
|
const child = spawn(options.binaryPath, [
|
|
55
68
|
...options.ipcPathArgs.map((arg) => (arg === "{path}" ? ipcPath : arg)),
|
|
@@ -66,14 +79,6 @@ function spawnServerProcess(options, ipcPath, logFd) {
|
|
|
66
79
|
child.stdout?.on("data", (data) => options.logger?.(`[${options.binaryName} stdout] ${data.toString().trimEnd()}`));
|
|
67
80
|
child.stderr?.on("data", (data) => options.logger?.(`[${options.binaryName} stderr] ${data.toString().trimEnd()}`));
|
|
68
81
|
}
|
|
69
|
-
if (options.unref) {
|
|
70
|
-
child.unref();
|
|
71
|
-
}
|
|
72
|
-
if (options.unrefStdio) {
|
|
73
|
-
// The stdio pipes are net.Sockets at runtime but typed as Readable.
|
|
74
|
-
child.stdout?.unref?.();
|
|
75
|
-
child.stderr?.unref?.();
|
|
76
|
-
}
|
|
77
82
|
return child;
|
|
78
83
|
}
|
|
79
84
|
/**
|
|
@@ -326,6 +331,9 @@ export class SpawnedProcessBackend {
|
|
|
326
331
|
await this.cleanupIpcPath();
|
|
327
332
|
throw this.asSpawnError(err);
|
|
328
333
|
}
|
|
334
|
+
if (options.unref) {
|
|
335
|
+
unrefWhenIdle(child);
|
|
336
|
+
}
|
|
329
337
|
return incarnation;
|
|
330
338
|
}
|
|
331
339
|
/** Handles an incarnation's death: reject/replace state so later calls behave per the respawn policy. */
|
|
@@ -448,6 +456,9 @@ export class SpawnedProcessBackendSync {
|
|
|
448
456
|
connectShmSyncClient(options, ipcPath, child.pid),
|
|
449
457
|
childReadyFailure,
|
|
450
458
|
]);
|
|
459
|
+
if (options.unref) {
|
|
460
|
+
unrefWhenIdle(child);
|
|
461
|
+
}
|
|
451
462
|
return new SpawnedProcessBackendSync(options, child, client, ipcPath, logPath);
|
|
452
463
|
}
|
|
453
464
|
catch (err) {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { IpcClientAsync, IpcClientSync } from "../types.js";
|
|
2
|
+
import { WasmInstanceHost } from "./host.js";
|
|
3
|
+
import { type WasmModuleSource } from "./module_source.js";
|
|
4
|
+
import type { WasmPlatform, WorkerHandle } from "./platform.js";
|
|
5
|
+
/** Options shared by every way of running an FFI-contract module. */
|
|
6
|
+
export interface WasmFfiOptions {
|
|
7
|
+
/** The module: a compiled `Module`, bytes (gzipped or not), a `Response`, or a URL/string. */
|
|
8
|
+
module: WasmModuleSource;
|
|
9
|
+
/** Threads to run with (1 = no worker threads). Default: the platform's parallelism, capped at 32. */
|
|
10
|
+
threads?: number;
|
|
11
|
+
/** Linear memory bounds in 64 KiB pages; `shared` defaults to `threads > 1`. */
|
|
12
|
+
memory?: {
|
|
13
|
+
initial?: number;
|
|
14
|
+
maximum?: number;
|
|
15
|
+
shared?: boolean;
|
|
16
|
+
};
|
|
17
|
+
/** WASI environ for the module. `HARDWARE_CONCURRENCY` and `RAYON_NUM_THREADS` default to `threads`. */
|
|
18
|
+
env?: Record<string, string>;
|
|
19
|
+
logger?: (msg: string) => void;
|
|
20
|
+
/** FFI entry export; default: the module's one `<service>_ipc_ffi_entry` export. */
|
|
21
|
+
entry?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* What a platform entry (`index.node.ts` / `index.browser.ts`) binds for the backend. Workers are
|
|
25
|
+
* created through factories rather than URLs: bundlers only bundle a worker's dependency graph when
|
|
26
|
+
* they see the literal `new Worker(new URL('./x.js', import.meta.url), { type: 'module' })`, so
|
|
27
|
+
* that expression has to live in the code that owns the worker script.
|
|
28
|
+
*/
|
|
29
|
+
export interface WasmFfiBinding {
|
|
30
|
+
platform: WasmPlatform;
|
|
31
|
+
/** Spawn a worker hosting one module instance per wasi thread. */
|
|
32
|
+
createThreadWorker: () => WorkerHandle;
|
|
33
|
+
/** Spawn the worker hosting the main instance when `worker: true`. */
|
|
34
|
+
createMainWorker: () => WorkerHandle;
|
|
35
|
+
}
|
|
36
|
+
export interface WasmFfiBackendOptions extends WasmFfiOptions {
|
|
37
|
+
/**
|
|
38
|
+
* Run the main instance in a dedicated worker (default true), so a long call never blocks the
|
|
39
|
+
* caller's event loop and, in browsers, the thread pool is spawned from a worker. With `false`
|
|
40
|
+
* the main instance runs on the calling thread and every call blocks it until it returns.
|
|
41
|
+
*/
|
|
42
|
+
worker?: boolean;
|
|
43
|
+
/** Override the worker factories the platform entry binds. */
|
|
44
|
+
createThreadWorker?: () => WorkerHandle;
|
|
45
|
+
createMainWorker?: () => WorkerHandle;
|
|
46
|
+
}
|
|
47
|
+
/** Above this, more wasi threads stop paying for themselves; the engine clamps to it. */
|
|
48
|
+
export declare const MAX_THREADS = 32;
|
|
49
|
+
/**
|
|
50
|
+
* The module running on the current thread: memory, main instance, and the workers serving its
|
|
51
|
+
* `thread-spawn` requests. `call` is synchronous and blocks until the module returns.
|
|
52
|
+
*/
|
|
53
|
+
export declare class WasmFfiEngine {
|
|
54
|
+
/** The module instance, for reaching exports of its own beyond the FFI entry. */
|
|
55
|
+
readonly host: WasmInstanceHost;
|
|
56
|
+
private readonly threadWorkers;
|
|
57
|
+
readonly memory: WebAssembly.Memory;
|
|
58
|
+
readonly threads: number;
|
|
59
|
+
private constructor();
|
|
60
|
+
static create(opts: WasmFfiOptions, binding: WasmFfiBinding): Promise<WasmFfiEngine>;
|
|
61
|
+
call(input: Uint8Array): Uint8Array;
|
|
62
|
+
unref(): void;
|
|
63
|
+
destroy(): Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Asynchronous FFI backend over a wasm module. Implements the runtime's `IpcClientAsync`, so the
|
|
67
|
+
* generated `AsyncApi` sits on it exactly as it sits on a spawned process.
|
|
68
|
+
*/
|
|
69
|
+
export declare class WasmFfiBackend implements IpcClientAsync {
|
|
70
|
+
private readonly engine;
|
|
71
|
+
private readonly worker;
|
|
72
|
+
private seq;
|
|
73
|
+
private readonly pending;
|
|
74
|
+
private constructor();
|
|
75
|
+
static create(opts: WasmFfiBackendOptions, binding: WasmFfiBinding): Promise<WasmFfiBackend>;
|
|
76
|
+
private onWorkerMessage;
|
|
77
|
+
call(input: Uint8Array): Promise<Uint8Array>;
|
|
78
|
+
/** Let the host process exit even while the module's workers are alive (node). */
|
|
79
|
+
unref(): void;
|
|
80
|
+
destroy(): Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Synchronous FFI backend: the module runs on the calling thread and every call blocks until it
|
|
84
|
+
* returns. Defaults to one thread, since a blocked caller cannot service anything else.
|
|
85
|
+
*/
|
|
86
|
+
export declare class WasmFfiBackendSync implements IpcClientSync {
|
|
87
|
+
private readonly engine;
|
|
88
|
+
private constructor();
|
|
89
|
+
static create(opts: WasmFfiOptions, binding: WasmFfiBinding): Promise<WasmFfiBackendSync>;
|
|
90
|
+
call(input: Uint8Array): Uint8Array;
|
|
91
|
+
unref(): void;
|
|
92
|
+
destroy(): void;
|
|
93
|
+
}
|