import type { Worker } from 'node:worker_threads'; import type { ChannelOptions } from './channel.ts'; declare const resultBrand: unique symbol; /** An inert task descriptor. Carries the result type `T` and argument types `A` * at the type level, but is not itself a `PromiseLike` or `AsyncIterable`. * Dispatch via a {@link Runner} or `await` a live task returned by `mo()`. */ export type Task = { readonly uid: number; readonly id: string; readonly args: A; worker?: WorkerHandle; /** @internal Type brand for result type inference. Not present at runtime. */ readonly [resultBrand]?: T; }; /** Resolves the dispatch return type: `AsyncIterable` for streaming tasks, `Promise` otherwise. */ export type RunResult = T extends AsyncIterable ? AsyncIterable : Promise; 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): 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. */ export interface WorkerHandle { /** Dispatches a task pinned to this worker. Returns `AsyncIterable` for streaming tasks, `Promise` otherwise. */ exec(task: Task, opts?: ChannelOptions): RunResult; /** The underlying worker thread. */ readonly thread: Worker; /** Number of currently in-flight tasks on this worker. */ readonly activeCount: number; } /** * A callable that dispatches tasks to a worker pool. Disposable via `using` or `[Symbol.dispose]()`. * * @param task - A single {@link Task} to run on a worker. * @returns `Promise` for a single task, `Promise<[...results]>` for a batch, or `AsyncIterable` for a streaming task. */ export type Runner = { /** Dispatches a batch of tasks in parallel and returns all results. */ []>(tasks: [...T]): Promise>; /** Dispatches a task. Returns `AsyncIterable` for streaming tasks, `Promise` otherwise. */ (task: Task, opts?: ChannelOptions): RunResult; /** AbortSignal that fires when the pool starts disposing. */ readonly signal: AbortSignal; /** Read-only array of worker handles, one per pool worker. */ readonly workers: readonly WorkerHandle[]; /** Terminates all workers immediately. */ [Symbol.dispose](): void; /** Aborts signal, waits for in-flight tasks to settle, then terminates workers. */ [Symbol.asyncDispose](): Promise; };