spark.RpcHandler
export type RpcHandler = (params: unknown) => unknown | Promise<unknown>;Handler function for incoming RPC method calls.
Called when the remote side invokes this method via RPC. Handlers can:
- Return a value synchronously
- Return a Promise for async operations
- Throw errors (transmitted back to caller)
- Access the module's state and perform side effects
Errors thrown by handlers are automatically serialized and sent to the caller with the error message and stack trace preserved.
Examples
const rpc = new Rpc({ target: worker, origin: '*' });
// Simple handler
rpc.handle('add', (params) => {
const [a, b] = params as [number, number];
return a + b;
});
// Async handler
rpc.handle('load_model', async (params) => {
const model = await torch.load(params as string);
return { status: 'loaded', size: model.parameters().length };
});
// Handler that throws
rpc.handle('validate', (params) => {
if (!params) throw new Error('Missing parameters');
return { valid: true };
});