Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,13 @@ jobs:
- name: Typecheck
run: pnpm -r build

- name: Run Node tests
run: node --test "test/node/*.test.js"

- name: Install Playwright browsers
run: pnpm exec playwright install --with-deps chromium

- name: Run tests
- name: Run browser tests
run: pnpm test

- name: Upload test report
Expand Down
173 changes: 147 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

[![CI](https://github.com/fideus-labs/worker-pool/actions/workflows/ci.yml/badge.svg)](https://github.com/fideus-labs/worker-pool/actions/workflows/ci.yml)

A Web Worker pool with bounded concurrency, plus a companion
A worker pool with bounded concurrency, plus a companion
[@fideus-labs/fizarrita](#zarritajs-integration) package that accelerates
zarrita codec operations on Web Workers.
zarrita codec operations on workers. Runs on Web Workers in the browser and on
`node:worker_threads` in Node, behind one interface.

## Features

Expand All @@ -14,6 +15,8 @@ zarrita codec operations on Web Workers.
- **ChunkQueue interface** — `add()` + `onIdle()`, compatible with zarrita.js
and p-queue patterns.
- **Batch interface** — `runTasks()` with progress reporting and cancellation.
- **Browser and Node** — the same task code runs on Web Workers and on
`node:worker_threads`; see [Node.js](#nodejs).
- **Zero runtime dependencies.**

## Installation
Expand All @@ -26,28 +29,53 @@ npm add @fideus-labs/worker-pool

### Task function contract

Every task function receives an available `Worker` (or `null` when the pool
needs a new worker created) and **must** return an object with the worker to
recycle and the result:
Every task function receives an available worker (or `null` when the pool needs
a new worker created) and **must** return an object with the worker to recycle
and the result:

```typescript
type WorkerPoolTask<T> = (
worker: Worker | null
) => Promise<{ worker: Worker; result: T }>
worker: WorkerLike | null
) => Promise<{ worker: WorkerLike; result: T }>
```
`WorkerLike` is the slice of the `Worker` API the pool and its tasks use —
`postMessage`, `terminate`, `addEventListener`, `removeEventListener`. A browser
`Worker` satisfies it, and so does the `node:worker_threads` adapter, which is
what lets one task function serve both runtimes.
### ChunkQueue interface (`add` / `onIdle`)
```typescript
import { WorkerPool } from '@fideus-labs/worker-pool'

const workerUrl = new URL('./my-worker.js', import.meta.url).href
import type { WorkerLike } from '@fideus-labs/worker-pool'

function createTask(input: number) {
return (worker: Worker | null) => {
const w = worker ?? new Worker(workerUrl, { type: 'module' })
return new Promise<{ worker: Worker; result: number }>((resolve) => {
w.onmessage = (e) => resolve({ worker: w, result: e.data })
return (worker: WorkerLike | null) => {
// Two things worth copying here:
// - the literal `new Worker(new URL(...), ...)` form, which is the only
// shape bundlers recognise as a worker entry point;
// - annotating the local, because `WorkerLike | Worker` is a union
// TypeScript resolves to the wrong `postMessage` overload.
const w: WorkerLike =
worker ??
new Worker(new URL('./my-worker.js', import.meta.url), { type: 'module' })
return new Promise<{ worker: WorkerLike; result: number }>((resolve, reject) => {
// Handle 'error' too, or a failing worker leaves onIdle() pending forever.
const onMessage = (e: { data: number }) => {
detach()
resolve({ worker: w, result: e.data })
}
const onError = (e: { message: string }) => {
detach()
reject(new Error(e.message))
}
const detach = () => {
w.removeEventListener('message', onMessage)
w.removeEventListener('error', onError)
}
w.addEventListener('message', onMessage)
w.addEventListener('error', onError)
w.postMessage(input)
})
}
Expand All @@ -59,10 +87,12 @@ pool.add(createTask(1))
pool.add(createTask(2))
pool.add(createTask(3))

const results = await pool.onIdle<number>()
// results: [result1, result2, result3] — in add() order

pool.terminateWorkers()
try {
const results = await pool.onIdle<number>()
// results: [result1, result2, result3] — in add() order
} finally {
pool.terminateWorkers()
}
```

### Batch interface (`runTasks`)
Expand All @@ -82,8 +112,11 @@ const { promise, runId } = pool.runTasks(tasks, (completed, total) => {
// Cancel if needed:
// pool.cancel(runId)

const results = await promise
pool.terminateWorkers()
try {
const results = await promise
} finally {
pool.terminateWorkers()
}
```

## API
Expand Down Expand Up @@ -118,13 +151,98 @@ Cancel a pending `runTasks` batch. The promise rejects with
Terminate all idle workers. The pool can still be used after this — new
workers will be created as needed.

### `createWorker(url, options?): WorkerLike`

Create a worker for the current runtime: a module `Worker` where one exists
(browsers, Deno, Bun), a `NodeWorker` on Node. Throws if neither is available.

> **Bundled browser code:** bundlers only detect a worker entry point from the
> literal `new Worker(new URL('./w.js', import.meta.url), { type: 'module' })`
> form. A call through `createWorker` is opaque to them, so in a bundled browser
> app the worker script has to reach the output another way (a `?worker` import,
> a copied asset, or a literal `new Worker(...)` on the browser branch).
### `new NodeWorker(url, options?)`

A `node:worker_threads` worker behind the `WorkerLike` interface. The underlying
thread is created asynchronously — `node:worker_threads` is imported on demand so
browser bundles never try to resolve it — but the constructor is synchronous and
messages posted before the thread exists are queued in order.

`options` accepts `name` and `workerData`.

### `isNodeRuntime(): boolean`

Whether the current runtime reports itself as Node.

---

## Node.js

Plain Node has no global `Worker`, so `new Worker(...)` in a task throws
`ReferenceError: Worker is not defined`. Use `createWorker`, which picks the
right implementation for the runtime:

```typescript
import { createWorker, WorkerPool } from '@fideus-labs/worker-pool'
import type { WorkerLike } from '@fideus-labs/worker-pool'

const workerUrl = new URL('./my-worker.mjs', import.meta.url)

function createTask(input: number) {
return async (worker: WorkerLike | null) => {
const w = worker ?? createWorker(workerUrl)
const result = await new Promise<number>((resolve, reject) => {
const onMessage = (e: { data: number }) => { detach(); resolve(e.data) }
const onError = (e: { message: string }) => { detach(); reject(new Error(e.message)) }
const detach = () => {
w.removeEventListener('message', onMessage)
w.removeEventListener('error', onError)
}
w.addEventListener('message', onMessage)
w.addEventListener('error', onError)
w.postMessage(input)
})
return { worker: w, result }
}
}

const pool = new WorkerPool(4)
const { promise } = pool.runTasks(inputs.map(createTask))

try {
const results = await promise
} finally {
// Required, and in a finally: worker threads hold the event loop open, so a
// failed run would otherwise leave the process unable to exit.
pool.terminateWorkers()
}
```

The worker script itself is an ordinary `node:worker_threads` module:

```javascript
import { parentPort } from 'node:worker_threads'

parentPort.on('message', (input) => parentPort.postMessage(input * input))
```

Notes:

- **Always call `pool.terminateWorkers()`.** A live worker thread keeps the Node
event loop alive, so the process will not exit without it.
- **Event shape.** Node delivers a raw value to `on('message')` and an `Error` to
`on('error')`; the adapter wraps them as `{ data }` and `{ message, error }` so
listeners read the same in both runtimes.
- **`SharedArrayBuffer` and transfer lists** work as they do in the browser.

## zarrita.js Integration

The `@fideus-labs/fizarrita` package provides `getWorker` and `setWorker` as
drop-in replacements for zarrita's `get` and `set`, offloading codec
encode/decode to Web Workers via the worker pool.
encode/decode to workers via the worker pool. It ships a codec worker for each
runtime and picks between them automatically, so the examples below work
unchanged in Node.

### Installation

Expand All @@ -145,13 +263,15 @@ const pool = new WorkerPool(4)
const store = new zarr.FetchStore('https://example.com/data.zarr')
const arr = await zarr.open(store, { kind: 'array' })

// Read with codec decode offloaded to workers
const chunk = await getWorker(arr, null, { pool })
try {
// Read with codec decode offloaded to workers
const chunk = await getWorker(arr, null, { pool })

// Write with codec encode offloaded to workers
await setWorker(arr, null, chunk, { pool })

pool.terminateWorkers()
// Write with codec encode offloaded to workers
await setWorker(arr, null, chunk, { pool })
} finally {
pool.terminateWorkers()
}
```

### SharedArrayBuffer support
Expand Down Expand Up @@ -270,6 +390,7 @@ pnpm dev # Start test app dev server (port 5173)
pnpm bench # Start benchmark app (port 5174)
pnpm test # Run Playwright browser tests
pnpm test:ui # Interactive Playwright UI
pnpm test:node # Build both packages, then run the Node tests
```

## License
Expand Down
81 changes: 72 additions & 9 deletions fizarrita/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# @fideus-labs/fizarrita

Worker-pool-accelerated `get`/`set` for [zarrita.js](https://github.com/manzt/zarrita.js) — offloads codec encode/decode to Web Workers via [@fideus-labs/worker-pool](https://github.com/fideus-labs/worker-pool).
Worker-pool-accelerated `get`/`set` for [zarrita.js](https://github.com/manzt/zarrita.js) — offloads codec encode/decode to workers via [@fideus-labs/worker-pool](https://github.com/fideus-labs/worker-pool).

Runs in the browser on Web Workers and in Node on `node:worker_threads`; the
right codec worker is picked for you. See [Node.js](#nodejs).

## Installation

Expand All @@ -20,13 +23,15 @@ const pool = new WorkerPool(navigator.hardwareConcurrency ?? 4)
const store = new zarr.FetchStore('https://example.com/data.zarr')
const arr = await zarr.open(store, { kind: 'array' })

// Read — codec decode runs on workers
const chunk = await getWorker(arr, null, { pool })

// Write — codec encode runs on workers
await setWorker(arr, null, chunk, { pool })
try {
// Read — codec decode runs on workers
const chunk = await getWorker(arr, null, { pool })

pool.terminateWorkers()
// Write — codec encode runs on workers
await setWorker(arr, null, chunk, { pool })
} finally {
pool.terminateWorkers()
}
```

## API
Expand Down Expand Up @@ -179,6 +184,46 @@ interface ChunkCache {
}
```

## Node.js

`getWorker` and `setWorker` work in plain Node with no extra setup. The package
ships two codec worker entries — `codec-worker.js` for the browser and
`codec-worker-node.js` for `node:worker_threads` — and `createDefaultWorker`
selects between them at runtime.

```ts
import { WorkerPool } from '@fideus-labs/worker-pool'
import { getWorker, setWorker } from '@fideus-labs/fizarrita'
import * as zarr from 'zarrita'

const store = new Map()
const arr = await zarr.create(zarr.root(store).resolve('/data'), {
shape: [1024, 1024],
chunk_shape: [256, 256],
data_type: 'int32',
})

const pool = new WorkerPool(4)
try {
await setWorker(arr, null, 42, { pool })
const chunk = await getWorker(arr, null, { pool })
} finally {
// Required in Node: worker threads hold the event loop open.
pool.terminateWorkers()
}
```

Notes:

- **Always call `pool.terminateWorkers()`** — otherwise the Node process will
not exit.
- **`useSharedArrayBuffer` works in Node**, and needs no COOP/COEP headers there;
`SharedArrayBuffer` is available unconditionally.
- **Codec availability is zarrita's, not ours.** zarrita ships working `zstd`,
`blosc`, `lz4`, and `bytes` implementations; `gzip` and `crc32c` need a codec
registered from `numcodecs`, in the worker, via a
[custom codec worker](#custom-codec-worker).

## Worker message protocol

The built-in codec worker handles four message types:
Expand All @@ -204,12 +249,30 @@ await getWorker(arr, null, { pool, workerUrl })
await setWorker(arr, null, data, { pool, workerUrl })
```

The built-in worker is also available as a subpath export for direct reference:
To build a worker yourself instead of passing a `workerUrl`, use
`createDefaultWorker()`, which returns a ready worker for the current runtime:

```ts
import '@fideus-labs/fizarrita/codec-worker'
import { createDefaultWorker } from '@fideus-labs/fizarrita'

const worker = createDefaultWorker()
```

The two entries are also reachable as subpath exports, but they are **worker
entry modules, not importable helpers** — each one attaches a message handler to
the scope it is loaded in. Importing them on the main thread does not create a
worker: the browser entry would bind its handler to the page, and the Node entry
throws outright. Reference them as a worker script, not as an import:

```ts
// The specifier resolves to the worker file; it is never imported directly.
const url = import.meta.resolve('@fideus-labs/fizarrita/codec-worker')
await getWorker(arr, null, { pool, workerUrl: url })
```

Both are thin entry points over `handleCodecMessage`, which is exported so a
custom worker can extend the protocol without reimplementing it.

## License

[MIT](LICENSE.txt)
Loading
Loading