From c88b5e917e2ed7602bc80fe3da7dc9302cd94644 Mon Sep 17 00:00:00 2001 From: Devin Ivy Date: Tue, 14 Apr 2026 11:51:34 -0400 Subject: [PATCH] feat: add Balancer interface, thread and activeCount to WorkerHandle --- src/runner.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/runner.ts b/src/runner.ts index 1f167bd..59eb335 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -1,13 +1,26 @@ +import type { Worker } from 'node:worker_threads'; import type { Task } from './task.ts'; import type { StreamTask } from './stream-task.ts'; import type { ChannelOptions } from './channel.ts'; type TaskResults[]> = { [K in keyof T]: T[K] extends Task ? R : never }; +/** A load balancing strategy for choosing which worker runs a task. */ +export interface Balancer { + /** Choose a worker for the given task. Called synchronously on every dispatch. */ + select(workers: readonly WorkerHandle[], task: Task | StreamTask): WorkerHandle; + /** Optional cleanup on sync dispose. */ + [Symbol.dispose]?(): void; + /** Optional cleanup on async dispose. */ + [Symbol.asyncDispose]?(): Promise; +} + /** Options for configuring a worker pool. */ export interface WorkerOptions { /** Maximum time in ms to wait for in-flight tasks during async dispose. If exceeded, workers are force-terminated. */ shutdownTimeout?: number; + /** Load balancing strategy. Defaults to round-robin. */ + balance?: Balancer; } /** A handle to a specific worker in a pool. */ @@ -16,6 +29,10 @@ export interface WorkerHandle { exec(task: Task): Promise; /** Dispatches a streaming task pinned to this worker. */ exec(task: StreamTask, opts?: ChannelOptions): AsyncIterable; + /** The underlying worker thread. */ + readonly thread: Worker; + /** Number of currently in-flight tasks on this worker. */ + readonly activeCount: number; } /** -- 2.51.2