UNPKG

@xylabs/threads

Version:

Web workers & worker threads as simple as a function call

77 lines (73 loc) 2.68 kB
import { Observable } from 'observable-fns'; import { T as Thread$1, W as WorkerEvent } from './master-DBU-F6eB.js'; type Thread = Thread$1; /** Thread utility functions. Use them to manage or inspect a `spawn()`-ed thread. */ declare const Thread: { /** Return an observable that can be used to subscribe to all errors happening in the thread. */ errors<ThreadT extends Thread$1>(thread: ThreadT): Observable<Error>; /** Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. */ events<ThreadT extends Thread$1>(thread: ThreadT): Observable<WorkerEvent>; /** Terminate a thread. Remember to terminate every thread when you are done using it. */ terminate<ThreadT extends Thread$1>(thread: ThreadT): Promise<void>; }; /** Pool event type. Specifies the type of each `PoolEvent`. */ declare enum PoolEventType { initialized = "initialized", taskCanceled = "taskCanceled", taskCompleted = "taskCompleted", taskFailed = "taskFailed", taskQueued = "taskQueued", taskQueueDrained = "taskQueueDrained", taskStart = "taskStart", terminated = "terminated" } type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>; /** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */ type PoolEvent<ThreadType extends Thread> = { type: PoolEventType.initialized; size: number; } | { type: PoolEventType.taskQueued; taskID: number; } | { type: PoolEventType.taskQueueDrained; } | { type: PoolEventType.taskStart; taskID: number; workerID: number; } | { type: PoolEventType.taskCompleted; returnValue: any; taskID: number; workerID: number; } | { type: PoolEventType.taskFailed; error: Error; taskID: number; workerID: number; } | { type: PoolEventType.taskCanceled; taskID: number; } | { type: PoolEventType.terminated; remainingQueue: Array<QueuedTask<ThreadType, any>>; }; /** * Task that has been `pool.queued()`-ed. */ interface QueuedTask<ThreadType extends Thread, Return> { /** @private */ id: number; /** @private */ run: TaskRunFunction<ThreadType, Return>; /** * Queued tasks can be cancelled until the pool starts running them on a worker thread. */ cancel(): void; /** * `QueuedTask` is thenable, so you can `await` it. * Resolves when the task has successfully been executed. Rejects if the task fails. */ then: Promise<Return>['then']; } export { type PoolEvent as P, type QueuedTask as Q, Thread as T, PoolEventType as a, type TaskRunFunction as b };