Offload functions to worker threads with shared memory primitives for Node.js.
8
fork

Configure Feed

Select the types of activity you want to include in your feed.

docs: document isTask() and worker affinity in README

Add a paragraph under Load Balancing showing how isTask() narrows a
task to a specific moroutine's descriptor shape, with a keyAffinity
balancer example. Link to examples/worker-affinity for the full demo.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

+23
+23
README.md
··· 123 123 124 124 Each `WorkerHandle` exposes `activeCount` (in-flight tasks) and `thread` (the underlying `worker_threads.Worker`) for building custom strategies. 125 125 126 + `isTask(moroutine, task)` narrows a task to the descriptor type produced by a specific moroutine — useful inside a balancer to route by task kind or by a key in the args. For example, a worker-affinity balancer can hash a shard key out of the args so that every call for the same key hits the worker that already has its state loaded: 127 + 128 + ```ts 129 + import { isTask, roundRobin } from 'moroutine'; 130 + import type { Balancer } from 'moroutine'; 131 + import { increment, read } from './counter.ts'; 132 + 133 + export function keyAffinity(): Balancer { 134 + const fallback = roundRobin(); 135 + return { 136 + select(workers, task) { 137 + let key: string | undefined; 138 + if (isTask(increment, task)) key = task.args[0]; 139 + else if (isTask(read, task)) key = task.args[0]; 140 + if (key === undefined) return fallback.select(workers, task); 141 + return workers[hash(key) % workers.length]; 142 + }, 143 + }; 144 + } 145 + ``` 146 + 147 + Inside the `isTask` branch, `task.args` is typed as the moroutine's argument tuple (e.g. `[key: string, n: number]` for `increment`). See [`examples/worker-affinity`](examples/worker-affinity) for the full demo, including per-worker state that only stays consistent under affinity routing. 148 + 126 149 ### Dedicated Workers 127 150 128 151 Awaiting a task directly (without a pool) runs it on a dedicated worker thread, one per moroutine function.