@far-analytics/port-peer
v2.0.1
Published
A RPC-like facility for making inter-thread function calls.
Readme
Port Peer
An RPC-like facility for making inter-thread function calls.
Introduction
Port Peer provides a simple and intuitive interface that makes inter-thread function calls easy. Please see the Usage or Examples for instructions on how to use Port Peer in your application.
Features
- Bi-directional inter-thread function calls.
- Port Peer will marshal the return value or failure reason from the other thread back to the caller.
- The other thread may be the main thread or a worker thread.
- Registered functions (i.e.,
peer.register) persist until deregistered (i.e.,peer.deregister). - Late binding registrants will be called with previously awaited invocations.
Table of contents
Installation
npm install @far-analytics/port-peerConcepts
Peer
An instance of a Peer facilitates bi-directional communication between threads. The Peer can be used in order to register a function in one thread and call it from another thread. Calls may be made from the main thread to a worker thread, and conversely from a worker thread to the main thread.
Late binding registrants will be called with previously awaited invocations; thus preventing a race condition. This means that you may await a call to a function that has not yet been registered. Once the function is registered in the other thread it will be called and its return value or failure reason will be marshalled back to the caller.
Please see the Examples for variations on the Peer's usage.
Usage
How to create a Peer instance
Import the Peer class and relevant dependencies.
import { Worker, parentPort } from "node:worker_threads";
import { fileURLToPath } from "node:url";
import { Peer } from "@far-analytics/port-peer";You can create a new Peer by passing a MessagePort or Worker instance to the Peer constructor.
In the main thread,
const worker = new Worker(fileURLToPath(import.meta.url));
const peer = new Peer(worker);or, in a worker thread,
const peer = new Peer(parentPort);How to use a Peer instance
You can register a function in the main thread or in a worker thread using the peer.register method.
peer.register("hello_world", (value: string): string => `Hello, ${value} world!`);You can call a function registered in another thread (i.e., the main thread or a worker thread) using the peer.call method:
const greeting = await peer.call<string>("hello_world", "happy");
console.log(greeting); // Hello, happy world!Examples
A simple example </Node.js>
Please see the simple example for a working implementation.
A comprehensive example </TypeScript>
Please see the comprehensive example for a working implementation.
API
The Peer class
new Peer(port)
- port
<threads.MessagePort>or<threads.Worker>The message port.
public peer.call<T>(name, ...args)
- name
<string>The name of the registered function. - ...args
<Array<unknown>>Arguments to be passed to the registered function.
Returns: <Promise<T>>
Errors
- If the registered function in the other thread throws or rejects, the failure reason will be marshalled back from the other thread to this thread and the
Promisewill reject with that value as its failure reason. - Rejection reasons may be any value supported by the underlying
MessagePortstructured-clone operation, includingErrorobjects, strings, numbers,false,null, andundefined. Callers should not assume that a rejection reason is anError. - When an
Erroris marshalled, its standard error information is transferred according to the platform's structured-clone behavior. Error identity, custom prototypes, and custom properties are not guaranteed to be preserved. - If a failure reason cannot be structured-cloned,
peer.call()will reject with the cloning error raised while sending the result.
Worker lifecycle
- If a worker thread throws an unhandled exception, all pending
Promises will reject with the worker error. - If a worker exits, all pending
Promises will reject with the worker's exit code as their failure reason.
MessagePort lifecycle
- If a
MessagePortcloses while a call is awaited, thePromisewill reject with an error indicating that the port closed. - Calls made after the
MessagePortcloses will reject with the same error.
public peer.register(name, fn)
- name
<string>The name of the registered function. - fn
<(...args: Array<any>) => any>The registered function.
Returns: <void>
public peer.deregister(name)
- name
<string>The name of the registered function.
Returns: <void>
Versioning
The Port Peer package adheres to semantic versioning. Breaking changes to the public API will result in a bump of the major version. Minor and patch changes will always be backward compatible.
Excerpted from Semantic Versioning 2.0.0:
Given a version number MAJOR.MINOR.PATCH, increment the:
- MAJOR version when you make incompatible API changes
- MINOR version when you add functionality in a backward compatible manner
- PATCH version when you make backward compatible bug fixes
Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.
Tests
How to run the test suite
Clone the repository.
git clone https://github.com/adamjpatterson/port-peerChange directory into the root of the repository.
cd port-peerInstall Port Peer dependencies.
npm installRun the tests.
npm testRun linting and tests together.
npm run checkRun the optional peer soak test.
The normal test suite includes deterministic concurrency and registration tests. A longer peer soak test is available but skipped by default.
On POSIX shells:
PORT_PEER_SOAK=1 npm testOn PowerShell:
$env:PORT_PEER_SOAK = "1"; npm testNotes
Support for BroadcastChannel
Port Peer supports one to one communication over a MessagePort. BroadcastChannels are not presently supported.
Support for other communication channels
Port Peer is strictly focused on efficient communication over MessagePorts. Port Peer will not support communication over other communication channels e.g., Sockets, IPC, etc.
Support
If you have a feature request or run into any issues, feel free to submit an issue. You’re also welcome to reach out directly to one of the authors.
