### Install worker-rpc with npm Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Install the worker-rpc package. Requires Node.js version 20.6 or later and has no runtime dependencies. ```sh npm install worker-rpc ``` -------------------------------- ### Expose and connect a typed worker API with worker-rpc Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Shows the worker and main-thread sides of a worker-rpc connection. The worker exports an api object and calls expose(api); the main thread connects with connect('./worker.js') to get fully typed methods. The type argument derives method signatures from the worker's own exported api, so renaming or changing a signature in the worker causes the caller to fail typechecking. ```ts // worker.ts import { expose } from 'worker-rpc'; export const api = { async resize(buf: Uint8Array, width: number): Promise { /* ... */ return buf; }, }; expose(api); ``` ```ts // main.ts import { connect } from 'worker-rpc'; const api = await connect('./worker.js'); const out = await api.resize(bytes, 800); // fully typed — from the worker's own signature await api.close(); ``` -------------------------------- ### Benchmark output: copy vs. transfer Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Measured with node examples/transfer-demo.ts: 20 round trips of a 64 MiB Uint8Array each way, worker just reads .byteLength and returns. Copying is ~3.5x slower here, and the gap widens with buffer size — copying is O(bytes), transferring is O(1). ```text 20 round trips, 64 MiB each, copy vs. transfer copy 20 round trips of 64 MiB: 107ms total, 5.3ms/round transfer 20 round trips of 64 MiB: 30ms total, 1.5ms/round ``` -------------------------------- ### Manual worker_threads RPC boilerplate (main.ts) Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Shows the manual RPC boilerplate that worker-rpc replaces. It lacks type safety, loses error details (only a string), and leaves pending promises hanging if the worker crashes. ```typescript // main.ts — the boilerplate this library replaces import { Worker } from 'node:worker_threads'; const worker = new Worker('./worker.js'); let nextId = 0; const pending = new Map(); worker.on('message', (msg) => { const p = pending.get(msg.id); if (!p) return; pending.delete(msg.id); msg.ok ? p.resolve(msg.value) : p.reject(new Error(msg.error)); // ← just a string }); function call(method, args) { const id = nextId++; return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, method, args }); }); } const result = await call('resize', [bytes, 800]); // ← no types, no autocomplete ``` -------------------------------- ### worker-rpc API Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md API documentation for the worker-rpc library, covering the main exported functions and methods. ```APIDOC ## [API] expose(api) ### Description Called once, in the worker, at module load. Registers `api`'s methods as callable and signals readiness. ### Method API ### Endpoint expose(api) ### Parameters - **api** (object) - Required - The object whose methods will be exposed as callable. ### Response No return value. ``` ```APIDOC ## [API] connect(specifier, options?) ### Description Starts the worker and resolves to a typed proxy for `T` once it calls `expose()`. `options` is passed straight through to `node:worker_threads`' `Worker`. ### Method API ### Endpoint connect(specifier, options?) ### Parameters - **specifier** (string) - Required - The worker module specifier. - **options** (object) - Optional - Options passed to `node:worker_threads`' `Worker`. ### Response Resolves to a typed proxy for `T`. ``` ```APIDOC ## [API] transfer(value, list?) ### Description Marks `value` (or the buffers in `list`) to be transferred, not copied, next time it crosses. ### Method API ### Endpoint transfer(value, list?) ### Parameters - **value** (any) - Required - The value to be transferred. - **list** (array) - Optional - List of buffers to be transferred. ### Response No return value. ``` ```APIDOC ## [API] api.method(...) ### Description Calls the exposed method; resolves/rejects like the worker's own `async` method would. ### Method API ### Endpoint api.method(...) ### Parameters - **...args** (any) - Required - Arguments to pass to the exposed method. ### Response Resolves with the method's return value or rejects with an error. ``` ```APIDOC ## [API] api.method.withSignal(signal)(...) ### Description Same call as `api.method(...)`, but cancellable via `AbortSignal`. See "Cancellation". ### Method API ### Endpoint api.method.withSignal(signal)(...) ### Parameters - **signal** (AbortSignal) - Required - The abort signal to cancel the call. - **...args** (any) - Required - Arguments to pass to the exposed method. ### Response Resolves with the method's return value or rejects with `CallAbortedError` if aborted. ``` ```APIDOC ## [API] api.close() ### Description Waits for in-flight calls to settle, then terminates the worker. No new calls accepted once called. ### Method API ### Endpoint api.close() ### Parameters None. ### Response Resolves when the worker is terminated. ``` ```APIDOC ## [API] api.terminate() ### Description Terminates the worker immediately; every in-flight call rejects with `WorkerExitedError`. ### Method API ### Endpoint api.terminate() ### Parameters None. ### Response Resolves when the worker is terminated. ``` -------------------------------- ### Transfer an ArrayBuffer with transfer() Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Use transfer() to move an ArrayBuffer across the worker boundary instead of copying it. This is opt-in and neuters the sender's buffer (byteLength becomes 0), so only call it on a buffer you're done with. It also works on return values and detects marked values inside plain arrays and objects up to two levels deep. ```typescript import { transfer } from 'worker-rpc'; const bytes = new Uint8Array(64 * 1024 * 1024); await api.resize(transfer(bytes), 800); bytes.byteLength; // 0 — the sender's copy is neutered, on purpose ``` -------------------------------- ### Worker method with cooperative cancellation Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Worker-side method that cooperatively checks for cancellation via the optional signal parameter. It throws if the signal has already fired, allowing the method to bail out early. ```ts async resize(buf: Uint8Array, width: number, opts?: { signal?: AbortSignal }) { opts?.signal?.throwIfAborted(); /* ... */ } ``` -------------------------------- ### Terminate worker immediately Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Immediately terminates the worker, causing every pending call to reject. This is the only remedy for stuck synchronous code, but it takes down the whole connection and requires a new connect() to continue. ```ts await api.terminate(); // kills the worker now; every pending call rejects ``` -------------------------------- ### Cancel an RPC call with AbortController Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Cancels an in-flight RPC call using an AbortController. Aborting rejects the call immediately with CallAbortedError without waiting for the worker, and sends the worker a message so a method accepting { signal } can bail out cooperatively. ```ts const controller = new AbortController(); const promise = api.resize.withSignal(controller.signal)(bytes, 800); controller.abort(); ``` -------------------------------- ### Propagate and inspect errors across worker-rpc Source: https://github.com/agentscope-ai-java/worker-rpc/blob/main/README.md Demonstrates error propagation across the worker boundary. A custom error class thrown in the worker arrives on the caller side as a RemoteError (an Error) with .name set to the original, and enumerable own properties like code and field are preserved. Note that err instanceof ValidationError is false; branch on err.name or err.code instead. The stack is stitched with a '--- worker boundary ---' line between worker frames and caller frames. ```ts // worker.ts class ValidationError extends Error { code = 'EVALIDATION'; constructor(public field: string) { super(`invalid field: ${field}`); this.name = 'ValidationError'; } } export const api = { async save() { throw new ValidationError('email'); }, }; ``` ```ts try { await api.save(); } catch (err) { err.message; // "invalid field: email" err.name; // "ValidationError" err.code; // "EVALIDATION" err.field; // "email" — other enumerable own properties come along too err.stack; // both sides, worker frames then caller frames, separated by a marker line } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.