@ariestools/threads 8.2.0 → 8.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/browser/index-browser.mjs +75 -35
- package/dist/browser/index-browser.mjs.map +4 -4
- package/dist/browser/master/index-browser.mjs +75 -35
- package/dist/browser/master/index-browser.mjs.map +4 -4
- package/dist/browser/master/pool-browser.d.ts +10 -1
- package/dist/browser/master/pool-browser.d.ts.map +1 -1
- package/dist/browser/master/pool-browser.mjs +34 -26
- package/dist/browser/master/pool-browser.mjs.map +3 -3
- package/dist/browser/master/pool-node.d.ts +10 -1
- package/dist/browser/master/pool-node.d.ts.map +1 -1
- package/dist/browser/master/pool-types.d.ts +21 -26
- package/dist/browser/master/pool-types.d.ts.map +1 -1
- package/dist/browser/types/master.d.ts +11 -11
- package/dist/browser/types/master.d.ts.map +1 -1
- package/dist/browser/types/messages.d.ts +23 -25
- package/dist/browser/types/messages.d.ts.map +1 -1
- package/dist/browser/worker/worker.browser.mjs +29 -8
- package/dist/browser/worker/worker.browser.mjs.map +3 -3
- package/dist/neutral/master/pool-browser.d.ts +10 -1
- package/dist/neutral/master/pool-browser.d.ts.map +1 -1
- package/dist/neutral/master/pool-node.d.ts +10 -1
- package/dist/neutral/master/pool-node.d.ts.map +1 -1
- package/dist/neutral/master/pool-types.d.ts +21 -26
- package/dist/neutral/master/pool-types.d.ts.map +1 -1
- package/dist/neutral/master/spawn.mjs +41 -9
- package/dist/neutral/master/spawn.mjs.map +4 -4
- package/dist/neutral/types/master.d.ts +11 -11
- package/dist/neutral/types/master.d.ts.map +1 -1
- package/dist/neutral/types/messages.d.ts +23 -25
- package/dist/neutral/types/messages.d.ts.map +1 -1
- package/dist/neutral/types/messages.mjs +19 -13
- package/dist/neutral/types/messages.mjs.map +3 -3
- package/dist/node/index-node.mjs +75 -35
- package/dist/node/index-node.mjs.map +4 -4
- package/dist/node/master/index-node.mjs +75 -35
- package/dist/node/master/index-node.mjs.map +4 -4
- package/dist/node/master/pool-browser.d.ts +10 -1
- package/dist/node/master/pool-browser.d.ts.map +1 -1
- package/dist/node/master/pool-node.d.ts +10 -1
- package/dist/node/master/pool-node.d.ts.map +1 -1
- package/dist/node/master/pool-node.mjs +34 -26
- package/dist/node/master/pool-node.mjs.map +3 -3
- package/dist/node/master/pool-types.d.ts +21 -26
- package/dist/node/master/pool-types.d.ts.map +1 -1
- package/dist/node/types/master.d.ts +11 -11
- package/dist/node/types/master.d.ts.map +1 -1
- package/dist/node/types/messages.d.ts +23 -25
- package/dist/node/types/messages.d.ts.map +1 -1
- package/dist/node/worker/worker.node.mjs +29 -8
- package/dist/node/worker/worker.node.mjs.map +3 -3
- package/package.json +8 -8
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/master/pool-browser.ts", "../../../src/master/implementation.browser.ts", "../../../src/master/pool-types.ts", "../../../src/symbols.ts", "../../../src/master/thread.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint-disable import-x/export */\n/* eslint-disable unicorn/no-thenable */\n\n/* eslint-disable @typescript-eslint/member-ordering */\n/* eslint-disable unicorn/no-array-reduce */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-namespace */\n\n/// <reference lib=\"esnext\" />\n\nimport DebugLogger from 'debug'\nimport {\n multicast, Observable, Subject,\n} from 'observable-fns'\n\nimport { defaultPoolSize } from './implementation.browser.ts'\nimport type {\n PoolEvent, QueuedTask, TaskRunFunction, WorkerDescriptor,\n} from './pool-types.ts'\nimport { PoolEventType } from './pool-types.ts'\nimport { Thread } from './thread.ts'\n\n/** Types and constants associated with browser worker pools. */\nexport declare namespace Pool {\n type Event<ThreadType extends Thread = any> = PoolEvent<ThreadType>\n type EventType = PoolEventType\n}\n\nlet nextPoolID = 1\n\nfunction createArray(size: number): number[] {\n const array: number[] = []\n for (let index = 0; index < size; index++) {\n array.push(index)\n }\n return array\n}\n\nfunction delay(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction flatMap<In, Out>(array: In[], mapper: (element: In) => Out[]): Out[] {\n return array.reduce<Out[]>((flattened, element) => [...flattened, ...mapper(element)], [])\n}\n\nfunction slugify(text: string) {\n return text.replaceAll(/\\W/g, ' ').trim().replaceAll(/\\s+/g, '-')\n}\n\nfunction spawnWorkers<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, count: number): WorkerDescriptor<ThreadType>[] {\n return createArray(count).map(\n (): WorkerDescriptor<ThreadType> => ({\n init: spawnWorker(),\n runningTasks: [],\n }),\n )\n}\n\n/**\n * Thread pool managing a set of worker threads.\n * Use it to queue tasks that are run on those threads with limited\n * concurrency.\n */\nexport interface Pool<ThreadType extends Thread> {\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Promise will be rejected if any task fails.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n completed(allowResolvingImmediately?: boolean): Promise<any>\n\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Failing tasks will not cause the promise to be rejected.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n settled(allowResolvingImmediately?: boolean): Promise<Error[]>\n\n /**\n * Returns an observable that yields pool events.\n */\n events(): Observable<PoolEvent<ThreadType>>\n\n /**\n * Queue a task and return a promise that resolves once the task has been dequeued,\n * started and finished.\n *\n * @param task An async function that takes a thread instance and invokes it.\n */\n queue<Return>(task: TaskRunFunction<ThreadType, Return>): QueuedTask<ThreadType, Return>\n\n /**\n * Terminate all pool threads.\n *\n * @param force Set to `true` to kill the thread even if it cannot be stopped gracefully.\n */\n terminate(force?: boolean): Promise<void>\n}\n\ninterface PoolOptions {\n /** Maximum no. of tasks to run on one worker thread at a time. Defaults to one. */\n concurrency?: number\n\n /** Maximum no. of jobs to be queued for execution before throwing an error. */\n maxQueuedJobs?: number\n\n /** Gives that pool a name to be used for debug logging, letting you distinguish between log output of different pools. */\n name?: string\n\n /** No. of worker threads to spawn and to be managed by the pool. */\n size?: number\n}\n\nclass WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {\n static EventType = PoolEventType\n\n private readonly debug: DebugLogger.Debugger\n private readonly eventObservable: Observable<PoolEvent<ThreadType>>\n private readonly options: PoolOptions\n private readonly workers: WorkerDescriptor<ThreadType>[]\n\n private readonly eventSubject = new Subject<PoolEvent<ThreadType>>()\n private initErrors: Error[] = []\n private isClosing = false\n private nextTaskID = 1\n private taskQueue: QueuedTask<ThreadType, any>[] = []\n\n constructor(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n const options: PoolOptions = typeof optionsOrSize === 'number' ? { size: optionsOrSize } : optionsOrSize || {}\n\n const { size = defaultPoolSize } = options\n\n this.debug = DebugLogger(`threads:pool:${slugify(options.name ?? String(nextPoolID++))}`)\n this.options = options\n this.workers = spawnWorkers(spawnWorker, size)\n\n this.eventObservable = multicast(Observable.from(this.eventSubject))\n\n const debug = this.debug\n const workers = this.workers\n void (async () => {\n try {\n await Promise.all(workers.map(worker => worker.init))\n this.eventSubject.next({\n size: workers.length,\n type: PoolEventType.initialized,\n })\n } catch (error) {\n const initError = error instanceof Error ? error : new Error(String(error))\n debug('Error while initializing pool worker:', initError)\n this.eventSubject.error(initError)\n this.initErrors.push(initError)\n }\n })()\n }\n\n private findIdlingWorker(): WorkerDescriptor<ThreadType> | undefined {\n const { concurrency = 1 } = this.options\n return this.workers.find(worker => worker.runningTasks.length < concurrency)\n }\n\n private async runPoolTask(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const workerID = this.workers.indexOf(worker) + 1\n\n this.debug(`Running task #${task.id} on worker #${workerID}...`)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskStart,\n workerID,\n })\n\n try {\n const returnValue = await task.run(await worker.init)\n\n this.debug(`Task #${task.id} completed successfully`)\n this.eventSubject.next({\n returnValue,\n taskID: task.id,\n type: PoolEventType.taskCompleted,\n workerID,\n })\n } catch (ex) {\n const error = ex as Error\n this.debug(`Task #${task.id} failed`)\n this.eventSubject.next({\n error,\n taskID: task.id,\n type: PoolEventType.taskFailed,\n workerID,\n })\n }\n }\n\n private run(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const runPromise = (async () => {\n const removeTaskFromWorkersRunningTasks = () => {\n worker.runningTasks = worker.runningTasks.filter(someRunPromise => someRunPromise !== runPromise)\n }\n\n // Defer task execution by one tick to give handlers time to subscribe\n await delay(0)\n\n try {\n await this.runPoolTask(worker, task)\n } finally {\n removeTaskFromWorkersRunningTasks()\n\n if (!this.isClosing) {\n this.scheduleWork()\n }\n }\n })()\n\n worker.runningTasks.push(runPromise)\n }\n\n private scheduleWork() {\n this.debug('Attempt de-queueing a task in order to run it...')\n\n const availableWorker = this.findIdlingWorker()\n if (!availableWorker) return\n\n const nextTask = this.taskQueue.shift()\n if (!nextTask) {\n this.debug('Task queue is empty')\n this.eventSubject.next({ type: PoolEventType.taskQueueDrained })\n return\n }\n\n this.run(availableWorker, nextTask)\n }\n\n private taskCompletion(taskID: number) {\n return new Promise<any>((resolve, reject) => {\n const eventSubscription = this.events().subscribe((event) => {\n if (event.type === PoolEventType.taskCompleted && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n resolve(event.returnValue)\n } else if (event.type === PoolEventType.taskFailed && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n reject(event.error)\n } else if (event.type === PoolEventType.terminated) {\n eventSubscription.unsubscribe()\n reject(new Error('Pool has been terminated before task was run.'))\n }\n })\n })\n }\n\n async settled(allowResolvingImmediately = false): Promise<Error[]> {\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n if (allowResolvingImmediately && this.taskQueue.length === 0) {\n await Promise.allSettled(flatMap(this.workers, worker => worker.runningTasks))\n return []\n }\n\n const getCurrentlyRunningTasks = () => flatMap(this.workers, worker => worker.runningTasks)\n const taskFailures: Error[] = []\n\n const failureSubscription = this.eventObservable.subscribe((event) => {\n if (event.type === PoolEventType.taskFailed) {\n taskFailures.push(event.error)\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type !== PoolEventType.taskQueueDrained) {\n return\n }\n\n subscription.unsubscribe()\n resolve(void 0)\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n await Promise.allSettled(getCurrentlyRunningTasks())\n failureSubscription.unsubscribe()\n\n return taskFailures\n }\n\n async completed(allowResolvingImmediately = false) {\n const settlementPromise = this.settled(allowResolvingImmediately)\n\n const earlyExitPromise = new Promise<Error[]>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type === PoolEventType.taskQueueDrained) {\n subscription.unsubscribe()\n resolve(settlementPromise)\n } else if (event.type === PoolEventType.taskFailed) {\n subscription.unsubscribe()\n reject(event.error)\n }\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n const errors = await Promise.race([settlementPromise, earlyExitPromise])\n\n if (errors.length > 0) {\n throw errors[0]\n }\n }\n\n events() {\n return this.eventObservable\n }\n\n queue(taskFunction: TaskRunFunction<ThreadType, any>) {\n const { maxQueuedJobs = Infinity } = this.options\n\n if (this.isClosing) {\n throw new Error('Cannot schedule pool tasks after terminate() has been called.')\n }\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n\n const taskID = this.nextTaskID++\n const taskCompletion = this.taskCompletion(taskID)\n\n void (async () => {\n try {\n await taskCompletion\n } catch (error) {\n // Prevent unhandled rejections here as we assume the user will use\n // `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors\n this.debug(`Task #${taskID} errored:`, error)\n }\n })()\n\n const task: QueuedTask<ThreadType, any> = {\n cancel: () => {\n if (!this.taskQueue.includes(task)) return\n this.taskQueue = this.taskQueue.filter(someTask => someTask !== task)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskCanceled,\n })\n },\n id: taskID,\n run: taskFunction,\n then: taskCompletion.then.bind(taskCompletion),\n }\n\n if (this.taskQueue.length >= maxQueuedJobs) {\n throw new Error(\n 'Maximum number of pool tasks queued. Refusing to queue another one.\\n'\n + 'This usually happens for one of two reasons: We are either at peak '\n + \"workload right now or some tasks just won't finish, thus blocking the pool.\",\n )\n }\n\n this.debug(`Queueing task #${task.id}...`)\n this.taskQueue.push(task)\n\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskQueued,\n })\n\n this.scheduleWork()\n return task\n }\n\n async terminate(force?: boolean) {\n this.isClosing = true\n if (force !== true) {\n await this.completed(true)\n }\n this.eventSubject.next({\n remainingQueue: [...this.taskQueue],\n type: PoolEventType.terminated,\n })\n this.eventSubject.complete()\n await Promise.all(this.workers.map(async worker => Thread.terminate(await worker.init)))\n }\n}\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nfunction PoolConstructor<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n // The function exists only so we don't need to use `new` to create a pool (we still can, though).\n // If the Pool is a class or not is an implementation detail that should not concern the user.\n return new WorkerPool(spawnWorker, optionsOrSize)\n}\n\n;(PoolConstructor as any).EventType = PoolEventType\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nexport const Pool = PoolConstructor as typeof PoolConstructor & { EventType: typeof PoolEventType }\n\nexport type { PoolEvent, QueuedTask } from './pool-types.ts'\nexport { PoolEventType } from './pool-types.ts'\nexport { Thread } from './thread.ts'\n", "import type { ImplementationExport, ThreadsWorkerOptions } from '../types/master.ts'\nimport { getBundleURL } from './get-bundle-url.browser.ts'\n\n/** Default thread pool size based on available hardware concurrency, falling back to 4. */\nexport const defaultPoolSize = typeof navigator !== 'undefined' && navigator.hardwareConcurrency !== 0 ? navigator.hardwareConcurrency : 4\n\nconst isAbsoluteURL = (value: string) => /^[A-Za-z][\\d+.A-Za-z\\-]*:/.test(value)\n\nfunction createSourceBlobURL(code: string): string {\n const blob = new Blob([code], { type: 'application/javascript' })\n return URL.createObjectURL(blob)\n}\n\nfunction selectWorkerImplementation(): ImplementationExport {\n if (typeof Worker === 'undefined') {\n // Might happen on Safari, for instance\n // The idea is to only fail if the constructor is actually used\n return class NoWebWorker {\n constructor() {\n throw new Error(\n \"No web worker implementation available. You might have tried to spawn a worker within a worker in a browser that doesn't support workers in workers.\",\n )\n }\n } as unknown as ImplementationExport\n }\n\n class WebWorker extends Worker {\n constructor(url: string | URL, options?: ThreadsWorkerOptions) {\n if (typeof url === 'string' && options?._baseURL !== undefined && options._baseURL !== '') {\n url = new URL(url, options._baseURL)\n } else if (typeof url === 'string' && !isAbsoluteURL(url) && /^file:\\/\\//i.test(getBundleURL())) {\n url = new URL(url, getBundleURL().replace(/\\/[^/]+$/, '/'))\n if (options?.CORSWorkaround ?? true) {\n url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`)\n }\n }\n if (\n typeof url === 'string'\n && isAbsoluteURL(url) // Create source code blob loading JS file via `importScripts()`\n // to circumvent worker CORS restrictions\n && (options?.CORSWorkaround ?? true)\n ) {\n url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`)\n }\n super(url, options)\n }\n }\n\n class BlobWorker extends WebWorker {\n constructor(blob: Blob, options?: ThreadsWorkerOptions) {\n const url = globalThis.URL.createObjectURL(blob)\n super(url, options)\n }\n\n static fromText(source: string, options?: ThreadsWorkerOptions): WebWorker {\n const blob = new globalThis.Blob([source], { type: 'text/javascript' })\n return new BlobWorker(blob, options)\n }\n }\n\n return {\n blob: BlobWorker,\n default: WebWorker,\n }\n}\n\nlet implementation: ImplementationExport\n\n/**\n * Get the browser-specific worker implementation, lazily initializing it on first call.\n * @returns The platform-specific worker implementation export.\n */\nexport function getWorkerImplementation(): ImplementationExport {\n if (implementation === undefined) {\n implementation = selectWorkerImplementation()\n }\n return implementation\n}\n\n/**\n * Check whether the current code is running inside a web worker context.\n * @returns True if running in a worker, false otherwise.\n */\nexport function isWorkerRuntime() {\n const isWindowContext = typeof globalThis !== 'undefined' && typeof Window !== 'undefined' && globalThis instanceof Window\n const workerGlobal = globalThis as typeof globalThis & { postMessage?: unknown }\n return typeof globalThis !== 'undefined' && typeof workerGlobal.postMessage === 'function' && !isWindowContext\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/member-ordering */\nimport type { Thread } from './thread.ts'\n\n/** Pool event type. Specifies the type of each `PoolEvent`. */\nexport enum PoolEventType {\n /** All workers in the pool have initialized. */\n initialized = 'initialized',\n /** A queued task was canceled before execution. */\n taskCanceled = 'taskCanceled',\n /** A task completed successfully. */\n taskCompleted = 'taskCompleted',\n /** A task failed during execution. */\n taskFailed = 'taskFailed',\n /** A task was added to the queue. */\n taskQueued = 'taskQueued',\n /** The pool has no remaining queued tasks. */\n taskQueueDrained = 'taskQueueDrained',\n /** A worker started executing a task. */\n taskStart = 'taskStart',\n /** The pool and its workers were terminated. */\n terminated = 'terminated',\n}\n\n/** A function that runs a task on a worker thread and returns a promise of the result. */\nexport type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>\n\n/** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */\nexport type PoolEvent<ThreadType extends Thread>\n = | {\n type: PoolEventType.initialized\n size: number\n }\n | {\n type: PoolEventType.taskQueued\n taskID: number\n }\n | {\n type: PoolEventType.taskQueueDrained\n }\n | {\n type: PoolEventType.taskStart\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskCompleted\n returnValue: any\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskFailed\n error: Error\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskCanceled\n taskID: number\n }\n | {\n type: PoolEventType.terminated\n remainingQueue: QueuedTask<ThreadType, any>[]\n }\n\n/** Descriptor for a worker in a pool, tracking its initialization and running tasks. */\nexport interface WorkerDescriptor<ThreadType extends Thread> {\n /** Promise resolving to the initialized thread. */\n init: Promise<ThreadType>\n /** Tasks currently executing on the worker. */\n runningTasks: Promise<any>[]\n}\n\n/**\n * Task that has been `pool.queued()`-ed.\n */\nexport interface QueuedTask<ThreadType extends Thread, Return> {\n /** @private */\n id: number\n\n /** @private */\n run: TaskRunFunction<ThreadType, Return>\n\n /**\n * Queued tasks can be cancelled until the pool starts running them on a worker thread.\n */\n cancel(): void\n\n /**\n * `QueuedTask` is thenable, so you can `await` it.\n * Resolves when the task has successfully been executed. Rejects if the task fails.\n */\n then: Promise<Return>['then']\n}\n", "/** Symbol key for accessing a thread's error observable. */\nexport const $errors = Symbol('thread.errors')\n/** Symbol key for accessing a thread's event observable. */\nexport const $events = Symbol('thread.events')\n/** Symbol key for accessing a thread's terminate function. */\nexport const $terminate = Symbol('thread.terminate')\n/** Symbol key for marking an object as a transferable descriptor. */\nexport const $transferable = Symbol('thread.transferable')\n/** Symbol key for accessing the underlying worker instance of a thread. */\nexport const $worker = Symbol('thread.worker')\n", "import type { Observable } from 'observable-fns'\n\nimport {\n $errors, $events, $terminate,\n} from '../symbols.ts'\nimport type {\n PrivateThreadProps, Thread as ThreadType, WorkerEvent,\n} from '../types/master.ts'\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n\nfunction readPrivateThreadProp<K extends keyof PrivateThreadProps>(\n thread: ThreadType,\n key: K,\n): PrivateThreadProps[K] | undefined {\n return Reflect.get(thread, key)\n}\n\n/** Re-exported Thread type from the master types module. */\nexport type Thread = ThreadType\n\n/** Thread utility functions. Use them to manage or inspect a `spawn()`-ed thread. */\nexport const Thread = {\n /** Return an observable that can be used to subscribe to all errors happening in the thread. */\n errors: <ThreadT extends ThreadType>(thread: ThreadT): Observable<Error> =>\n readPrivateThreadProp(thread, $errors) ?? fail('Error observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. */\n events: <ThreadT extends ThreadType>(thread: ThreadT): Observable<WorkerEvent> =>\n readPrivateThreadProp(thread, $events) ?? fail('Events observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Terminate a thread. Remember to terminate every thread when you are done using it. */\n terminate: <ThreadT extends ThreadType>(thread: ThreadT) =>\n readPrivateThreadProp(thread, $terminate)?.() ?? fail('Terminate function not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n}\n"],
|
|
5
|
-
"mappings": ";AAUA,OAAO,iBAAiB;AACxB;AAAA,EACE;AAAA,EAAW;AAAA,EAAY;AAAA,OAClB;;;ACTA,IAAM,kBAAkB,OAAO,cAAc,eAAe,UAAU,wBAAwB,IAAI,UAAU,sBAAsB;;;
|
|
6
|
-
"names": [
|
|
4
|
+
"sourcesContent": ["/* eslint-disable import-x/export */\n/* eslint-disable unicorn/no-thenable */\n\n/* eslint-disable @typescript-eslint/member-ordering */\n/* eslint-disable unicorn/no-array-reduce */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-namespace */\n\n/// <reference lib=\"esnext\" />\n\nimport DebugLogger from 'debug'\nimport {\n multicast, Observable, Subject,\n} from 'observable-fns'\n\nimport { defaultPoolSize } from './implementation.browser.ts'\nimport type {\n PoolEvent, QueuedTask, TaskRunFunction, WorkerDescriptor,\n} from './pool-types.ts'\nimport { PoolEventType } from './pool-types.ts'\nimport { Thread } from './thread.ts'\n\n/** Types and constants associated with browser worker pools. */\nexport declare namespace Pool {\n type Event<ThreadType extends Thread = any> = PoolEvent<ThreadType>\n type EventType = PoolEventType\n}\n\nlet nextPoolID = 1\n\nfunction createArray(size: number): number[] {\n const array: number[] = []\n for (let index = 0; index < size; index++) {\n array.push(index)\n }\n return array\n}\n\nfunction delay(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction flatMap<In, Out>(array: In[], mapper: (element: In) => Out[]): Out[] {\n return array.reduce<Out[]>((flattened, element) => [...flattened, ...mapper(element)], [])\n}\n\nfunction slugify(text: string) {\n return text.replaceAll(/\\W/g, ' ').trim().replaceAll(/\\s+/g, '-')\n}\n\nfunction spawnWorkers<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, count: number): WorkerDescriptor<ThreadType>[] {\n return createArray(count).map(\n (): WorkerDescriptor<ThreadType> => ({\n init: spawnWorker(),\n runningTasks: [],\n }),\n )\n}\n\n/**\n * Thread pool managing a set of worker threads.\n * Use it to queue tasks that are run on those threads with limited\n * concurrency.\n */\nexport interface Pool<ThreadType extends Thread> {\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Promise will be rejected if any task fails.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n completed(allowResolvingImmediately?: boolean): Promise<any>\n\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Failing tasks will not cause the promise to be rejected.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n settled(allowResolvingImmediately?: boolean): Promise<Error[]>\n\n /**\n * Returns an observable that yields pool events.\n */\n events(): Observable<PoolEvent<ThreadType>>\n\n /**\n * Queue a task and return a promise that resolves once the task has been dequeued,\n * started and finished.\n *\n * @param task An async function that takes a thread instance and invokes it.\n */\n queue<Return>(task: TaskRunFunction<ThreadType, Return>): QueuedTask<ThreadType, Return>\n\n /**\n * Terminate all pool threads.\n *\n * @param force Set to `true` to kill the thread even if it cannot be stopped gracefully.\n */\n terminate(force?: boolean): Promise<void>\n}\n\ninterface PoolOptions {\n /** Maximum no. of tasks to run on one worker thread at a time. Defaults to one. */\n concurrency?: number\n\n /** Maximum no. of jobs to be queued for execution before throwing an error. */\n maxQueuedJobs?: number\n\n /** Gives that pool a name to be used for debug logging, letting you distinguish between log output of different pools. */\n name?: string\n\n /** No. of worker threads to spawn and to be managed by the pool. */\n size?: number\n}\n\nclass WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {\n static EventType = PoolEventType\n\n private readonly debug: DebugLogger.Debugger\n private readonly eventObservable: Observable<PoolEvent<ThreadType>>\n private readonly options: PoolOptions\n private readonly workers: WorkerDescriptor<ThreadType>[]\n\n private readonly eventSubject = new Subject<PoolEvent<ThreadType>>()\n private initErrors: Error[] = []\n private isClosing = false\n private nextTaskID = 1\n private taskQueue: QueuedTask<ThreadType, any>[] = []\n\n constructor(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n const options: PoolOptions = typeof optionsOrSize === 'number' ? { size: optionsOrSize } : optionsOrSize || {}\n\n const { size = defaultPoolSize } = options\n\n this.debug = DebugLogger(`threads:pool:${slugify(options.name ?? String(nextPoolID++))}`)\n this.options = options\n this.workers = spawnWorkers(spawnWorker, size)\n\n this.eventObservable = multicast(Observable.from(this.eventSubject))\n\n const debug = this.debug\n const workers = this.workers\n void (async () => {\n try {\n await Promise.all(workers.map(worker => worker.init))\n this.eventSubject.next({\n size: workers.length,\n type: PoolEventType.initialized,\n })\n } catch (error) {\n const initError = error instanceof Error ? error : new Error(String(error))\n debug('Error while initializing pool worker:', initError)\n this.eventSubject.error(initError)\n this.initErrors.push(initError)\n }\n })()\n }\n\n private findIdlingWorker(): WorkerDescriptor<ThreadType> | undefined {\n const { concurrency = 1 } = this.options\n return this.workers.find(worker => worker.runningTasks.length < concurrency)\n }\n\n private async runPoolTask(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const workerID = this.workers.indexOf(worker) + 1\n\n this.debug(`Running task #${task.id} on worker #${workerID}...`)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskStart,\n workerID,\n })\n\n try {\n const returnValue = await task.run(await worker.init)\n\n this.debug(`Task #${task.id} completed successfully`)\n this.eventSubject.next({\n returnValue,\n taskID: task.id,\n type: PoolEventType.taskCompleted,\n workerID,\n })\n } catch (ex) {\n const error = ex as Error\n this.debug(`Task #${task.id} failed`)\n this.eventSubject.next({\n error,\n taskID: task.id,\n type: PoolEventType.taskFailed,\n workerID,\n })\n }\n }\n\n private run(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const runPromise = (async () => {\n const removeTaskFromWorkersRunningTasks = () => {\n worker.runningTasks = worker.runningTasks.filter(someRunPromise => someRunPromise !== runPromise)\n }\n\n // Defer task execution by one tick to give handlers time to subscribe\n await delay(0)\n\n try {\n await this.runPoolTask(worker, task)\n } finally {\n removeTaskFromWorkersRunningTasks()\n\n if (!this.isClosing) {\n this.scheduleWork()\n }\n }\n })()\n\n worker.runningTasks.push(runPromise)\n }\n\n private scheduleWork() {\n this.debug('Attempt de-queueing a task in order to run it...')\n\n const availableWorker = this.findIdlingWorker()\n if (!availableWorker) return\n\n const nextTask = this.taskQueue.shift()\n if (!nextTask) {\n this.debug('Task queue is empty')\n this.eventSubject.next({ type: PoolEventType.taskQueueDrained })\n return\n }\n\n this.run(availableWorker, nextTask)\n }\n\n private taskCompletion(taskID: number) {\n return new Promise<any>((resolve, reject) => {\n const eventSubscription = this.events().subscribe((event) => {\n if (event.type === PoolEventType.taskCompleted && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n resolve(event.returnValue)\n } else if (event.type === PoolEventType.taskFailed && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n reject(event.error)\n } else if (event.type === PoolEventType.terminated) {\n eventSubscription.unsubscribe()\n reject(new Error('Pool has been terminated before task was run.'))\n }\n })\n })\n }\n\n async settled(allowResolvingImmediately = false): Promise<Error[]> {\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n if (allowResolvingImmediately && this.taskQueue.length === 0) {\n await Promise.allSettled(flatMap(this.workers, worker => worker.runningTasks))\n return []\n }\n\n const getCurrentlyRunningTasks = () => flatMap(this.workers, worker => worker.runningTasks)\n const taskFailures: Error[] = []\n\n const failureSubscription = this.eventObservable.subscribe((event) => {\n if (event.type === PoolEventType.taskFailed) {\n taskFailures.push(event.error)\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type !== PoolEventType.taskQueueDrained) {\n return\n }\n\n subscription.unsubscribe()\n resolve(void 0)\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n await Promise.allSettled(getCurrentlyRunningTasks())\n failureSubscription.unsubscribe()\n\n return taskFailures\n }\n\n async completed(allowResolvingImmediately = false) {\n const settlementPromise = this.settled(allowResolvingImmediately)\n\n const earlyExitPromise = new Promise<Error[]>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type === PoolEventType.taskQueueDrained) {\n subscription.unsubscribe()\n resolve(settlementPromise)\n } else if (event.type === PoolEventType.taskFailed) {\n subscription.unsubscribe()\n reject(event.error)\n }\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n const errors = await Promise.race([settlementPromise, earlyExitPromise])\n\n if (errors.length > 0) {\n throw errors[0]\n }\n }\n\n events() {\n return this.eventObservable\n }\n\n queue(taskFunction: TaskRunFunction<ThreadType, any>) {\n const { maxQueuedJobs = Infinity } = this.options\n\n if (this.isClosing) {\n throw new Error('Cannot schedule pool tasks after terminate() has been called.')\n }\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n\n const taskID = this.nextTaskID++\n const taskCompletion = this.taskCompletion(taskID)\n\n void (async () => {\n try {\n await taskCompletion\n } catch (error) {\n // Prevent unhandled rejections here as we assume the user will use\n // `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors\n this.debug(`Task #${taskID} errored:`, error)\n }\n })()\n\n const task: QueuedTask<ThreadType, any> = {\n cancel: () => {\n if (!this.taskQueue.includes(task)) return\n this.taskQueue = this.taskQueue.filter(someTask => someTask !== task)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskCanceled,\n })\n },\n id: taskID,\n run: taskFunction,\n then: taskCompletion.then.bind(taskCompletion),\n }\n\n if (this.taskQueue.length >= maxQueuedJobs) {\n throw new Error(\n 'Maximum number of pool tasks queued. Refusing to queue another one.\\n'\n + 'This usually happens for one of two reasons: We are either at peak '\n + \"workload right now or some tasks just won't finish, thus blocking the pool.\",\n )\n }\n\n this.debug(`Queueing task #${task.id}...`)\n this.taskQueue.push(task)\n\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskQueued,\n })\n\n this.scheduleWork()\n return task\n }\n\n async terminate(force?: boolean) {\n this.isClosing = true\n if (force !== true) {\n await this.completed(true)\n }\n this.eventSubject.next({\n remainingQueue: [...this.taskQueue],\n type: PoolEventType.terminated,\n })\n this.eventSubject.complete()\n await Promise.all(this.workers.map(async worker => Thread.terminate(await worker.init)))\n }\n}\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nfunction PoolConstructor<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n // The function exists only so we don't need to use `new` to create a pool (we still can, though).\n // If the Pool is a class or not is an implementation detail that should not concern the user.\n return new WorkerPool(spawnWorker, optionsOrSize)\n}\n\n;(PoolConstructor as any).EventType = PoolEventType\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nexport const Pool = PoolConstructor as typeof PoolConstructor & { EventType: typeof PoolEventType }\n\nexport type { PoolEvent, QueuedTask } from './pool-types.ts'\nexport { PoolEventType } from './pool-types.ts'\nexport { Thread } from './thread.ts'\n", "import type { ImplementationExport, ThreadsWorkerOptions } from '../types/master.ts'\nimport { getBundleURL } from './get-bundle-url.browser.ts'\n\n/** Default thread pool size based on available hardware concurrency, falling back to 4. */\nexport const defaultPoolSize = typeof navigator !== 'undefined' && navigator.hardwareConcurrency !== 0 ? navigator.hardwareConcurrency : 4\n\nconst isAbsoluteURL = (value: string) => /^[A-Za-z][\\d+.A-Za-z\\-]*:/.test(value)\n\nfunction createSourceBlobURL(code: string): string {\n const blob = new Blob([code], { type: 'application/javascript' })\n return URL.createObjectURL(blob)\n}\n\nfunction selectWorkerImplementation(): ImplementationExport {\n if (typeof Worker === 'undefined') {\n // Might happen on Safari, for instance\n // The idea is to only fail if the constructor is actually used\n return class NoWebWorker {\n constructor() {\n throw new Error(\n \"No web worker implementation available. You might have tried to spawn a worker within a worker in a browser that doesn't support workers in workers.\",\n )\n }\n } as unknown as ImplementationExport\n }\n\n class WebWorker extends Worker {\n constructor(url: string | URL, options?: ThreadsWorkerOptions) {\n if (typeof url === 'string' && options?._baseURL !== undefined && options._baseURL !== '') {\n url = new URL(url, options._baseURL)\n } else if (typeof url === 'string' && !isAbsoluteURL(url) && /^file:\\/\\//i.test(getBundleURL())) {\n url = new URL(url, getBundleURL().replace(/\\/[^/]+$/, '/'))\n if (options?.CORSWorkaround ?? true) {\n url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`)\n }\n }\n if (\n typeof url === 'string'\n && isAbsoluteURL(url) // Create source code blob loading JS file via `importScripts()`\n // to circumvent worker CORS restrictions\n && (options?.CORSWorkaround ?? true)\n ) {\n url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`)\n }\n super(url, options)\n }\n }\n\n class BlobWorker extends WebWorker {\n constructor(blob: Blob, options?: ThreadsWorkerOptions) {\n const url = globalThis.URL.createObjectURL(blob)\n super(url, options)\n }\n\n static fromText(source: string, options?: ThreadsWorkerOptions): WebWorker {\n const blob = new globalThis.Blob([source], { type: 'text/javascript' })\n return new BlobWorker(blob, options)\n }\n }\n\n return {\n blob: BlobWorker,\n default: WebWorker,\n }\n}\n\nlet implementation: ImplementationExport\n\n/**\n * Get the browser-specific worker implementation, lazily initializing it on first call.\n * @returns The platform-specific worker implementation export.\n */\nexport function getWorkerImplementation(): ImplementationExport {\n if (implementation === undefined) {\n implementation = selectWorkerImplementation()\n }\n return implementation\n}\n\n/**\n * Check whether the current code is running inside a web worker context.\n * @returns True if running in a worker, false otherwise.\n */\nexport function isWorkerRuntime() {\n const isWindowContext = typeof globalThis !== 'undefined' && typeof Window !== 'undefined' && globalThis instanceof Window\n const workerGlobal = globalThis as typeof globalThis & { postMessage?: unknown }\n return typeof globalThis !== 'undefined' && typeof workerGlobal.postMessage === 'function' && !isWindowContext\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/member-ordering */\nimport { Enum, type EnumValue } from '@ariestools/sdk/enum'\n\nimport type { Thread } from './thread.ts'\n\n/** Pool event type. Specifies the type of each `PoolEvent`. */\nexport const PoolEventType = Enum({\n /** All workers in the pool have initialized. */\n initialized: 'initialized',\n /** A queued task was canceled before execution. */\n taskCanceled: 'taskCanceled',\n /** A task completed successfully. */\n taskCompleted: 'taskCompleted',\n /** A task failed during execution. */\n taskFailed: 'taskFailed',\n /** A task was added to the queue. */\n taskQueued: 'taskQueued',\n /** The pool has no remaining queued tasks. */\n taskQueueDrained: 'taskQueueDrained',\n /** A worker started executing a task. */\n taskStart: 'taskStart',\n /** The pool and its workers were terminated. */\n terminated: 'terminated',\n} as const)\n/** Pool event type. Specifies the type of each `PoolEvent`. */\nexport type PoolEventType = EnumValue<typeof PoolEventType>\n\n/** A function that runs a task on a worker thread and returns a promise of the result. */\nexport type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>\n\n/** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */\nexport type PoolEvent<ThreadType extends Thread>\n = | {\n type: (typeof PoolEventType)['initialized']\n size: number\n }\n | {\n type: (typeof PoolEventType)['taskQueued']\n taskID: number\n }\n | {\n type: (typeof PoolEventType)['taskQueueDrained']\n }\n | {\n type: (typeof PoolEventType)['taskStart']\n taskID: number\n workerID: number\n }\n | {\n type: (typeof PoolEventType)['taskCompleted']\n returnValue: any\n taskID: number\n workerID: number\n }\n | {\n type: (typeof PoolEventType)['taskFailed']\n error: Error\n taskID: number\n workerID: number\n }\n | {\n type: (typeof PoolEventType)['taskCanceled']\n taskID: number\n }\n | {\n type: (typeof PoolEventType)['terminated']\n remainingQueue: QueuedTask<ThreadType, any>[]\n }\n\n/** Descriptor for a worker in a pool, tracking its initialization and running tasks. */\nexport interface WorkerDescriptor<ThreadType extends Thread> {\n /** Promise resolving to the initialized thread. */\n init: Promise<ThreadType>\n /** Tasks currently executing on the worker. */\n runningTasks: Promise<any>[]\n}\n\n/**\n * Task that has been `pool.queued()`-ed.\n */\nexport interface QueuedTask<ThreadType extends Thread, Return> {\n /** @private */\n id: number\n\n /** @private */\n run: TaskRunFunction<ThreadType, Return>\n\n /**\n * Queued tasks can be cancelled until the pool starts running them on a worker thread.\n */\n cancel(): void\n\n /**\n * `QueuedTask` is thenable, so you can `await` it.\n * Resolves when the task has successfully been executed. Rejects if the task fails.\n */\n then: Promise<Return>['then']\n}\n", "/** Symbol key for accessing a thread's error observable. */\nexport const $errors = Symbol('thread.errors')\n/** Symbol key for accessing a thread's event observable. */\nexport const $events = Symbol('thread.events')\n/** Symbol key for accessing a thread's terminate function. */\nexport const $terminate = Symbol('thread.terminate')\n/** Symbol key for marking an object as a transferable descriptor. */\nexport const $transferable = Symbol('thread.transferable')\n/** Symbol key for accessing the underlying worker instance of a thread. */\nexport const $worker = Symbol('thread.worker')\n", "import type { Observable } from 'observable-fns'\n\nimport {\n $errors, $events, $terminate,\n} from '../symbols.ts'\nimport type {\n PrivateThreadProps, Thread as ThreadType, WorkerEvent,\n} from '../types/master.ts'\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n\nfunction readPrivateThreadProp<K extends keyof PrivateThreadProps>(\n thread: ThreadType,\n key: K,\n): PrivateThreadProps[K] | undefined {\n return Reflect.get(thread, key)\n}\n\n/** Re-exported Thread type from the master types module. */\nexport type Thread = ThreadType\n\n/** Thread utility functions. Use them to manage or inspect a `spawn()`-ed thread. */\nexport const Thread = {\n /** Return an observable that can be used to subscribe to all errors happening in the thread. */\n errors: <ThreadT extends ThreadType>(thread: ThreadT): Observable<Error> =>\n readPrivateThreadProp(thread, $errors) ?? fail('Error observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. */\n events: <ThreadT extends ThreadType>(thread: ThreadT): Observable<WorkerEvent> =>\n readPrivateThreadProp(thread, $events) ?? fail('Events observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Terminate a thread. Remember to terminate every thread when you are done using it. */\n terminate: <ThreadT extends ThreadType>(thread: ThreadT) =>\n readPrivateThreadProp(thread, $terminate)?.() ?? fail('Terminate function not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n}\n"],
|
|
5
|
+
"mappings": ";AAUA,OAAO,iBAAiB;AACxB;AAAA,EACE;AAAA,EAAW;AAAA,EAAY;AAAA,OAClB;;;ACTA,IAAM,kBAAkB,OAAO,cAAc,eAAe,UAAU,wBAAwB,IAAI,UAAU,sBAAsB;;;ACFzI,SAAS,YAA4B;AAK9B,IAAM,gBAAgB,KAAK;AAAA;AAAA,EAEhC,aAAa;AAAA;AAAA,EAEb,cAAc;AAAA;AAAA,EAEd,eAAe;AAAA;AAAA,EAEf,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA,EAEZ,kBAAkB;AAAA;AAAA,EAElB,WAAW;AAAA;AAAA,EAEX,YAAY;AACd,CAAU;;;ACvBH,IAAM,UAAU,uBAAO,eAAe;AAEtC,IAAM,UAAU,uBAAO,eAAe;AAEtC,IAAM,aAAa,uBAAO,kBAAkB;;;ACInD,SAAS,KAAK,SAAwB;AACpC,QAAM,IAAI,MAAM,OAAO;AACzB;AAEA,SAAS,sBACP,QACA,KACmC;AACnC,SAAO,QAAQ,IAAI,QAAQ,GAAG;AAChC;AAMO,IAAM,SAAS;AAAA;AAAA,EAEpB,QAAQ,CAA6B,WACnC,sBAAsB,QAAQ,OAAO,KAAK,KAAK,qGAAqG;AAAA;AAAA,EAEtJ,QAAQ,CAA6B,WACnC,sBAAsB,QAAQ,OAAO,KAAK,KAAK,sGAAsG;AAAA;AAAA,EAEvJ,WAAW,CAA6B,WACtC,sBAAsB,QAAQ,UAAU,IAAI,KAAK,KAAK,uGAAuG;AACjK;;;AJNA,IAAI,aAAa;AAEjB,SAAS,YAAY,MAAwB;AAC3C,QAAM,QAAkB,CAAC;AACzB,WAAS,QAAQ,GAAG,QAAQ,MAAM,SAAS;AACzC,U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/B,SAAK,YAAY;AACjB,QAAI,UAAU,MAAM;AAClB,YAAM,KAAK,UAAU,IAAI;AAAA,IAC3B;AACA,SAAK,aAAa,KAAK;AAAA,MACrB,gBAAgB,CAAC,GAAG,KAAK,SAAS;AAAA,MAClC,MAAM,cAAc;AAAA,IACtB,CAAC;AACD,SAAK,aAAa,SAAS;AAC3B,UAAM,QAAQ,IAAI,KAAK,QAAQ,IAAI,OAAM,WAAU,OAAO,UAAU,MAAM,OAAO,IAAI,CAAC,CAAC;AAAA,EACzF;AACF;AAKA,SAAS,gBAA2C,aAAwC,eAAsC;AAGhI,SAAO,IAAI,WAAW,aAAa,aAAa;AAClD;AAEE,gBAAwB,YAAY;AAK/B,IAAM,OAAO;",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
|
@@ -56,7 +56,16 @@ interface PoolOptions {
|
|
|
56
56
|
size?: number;
|
|
57
57
|
}
|
|
58
58
|
declare class WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {
|
|
59
|
-
static EventType:
|
|
59
|
+
static EventType: import("@ariestools/sdk/enum").Enum<{
|
|
60
|
+
initialized: 'initialized';
|
|
61
|
+
taskCanceled: 'taskCanceled';
|
|
62
|
+
taskCompleted: 'taskCompleted';
|
|
63
|
+
taskFailed: 'taskFailed';
|
|
64
|
+
taskQueued: 'taskQueued';
|
|
65
|
+
taskQueueDrained: 'taskQueueDrained';
|
|
66
|
+
taskStart: 'taskStart';
|
|
67
|
+
terminated: 'terminated';
|
|
68
|
+
}>;
|
|
60
69
|
private readonly debug;
|
|
61
70
|
private readonly eventObservable;
|
|
62
71
|
private readonly options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool-node.d.ts","sourceRoot":"","sources":["../../../src/master/pool-node.ts"],"names":[],"mappings":"AAWA,OAAO,EACM,UAAU,EACtB,MAAM,gBAAgB,CAAA;AAGvB,OAAO,KAAK,EACV,SAAS,EAAE,UAAU,EAAE,eAAe,EACvC,MAAM,iBAAiB,CAA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,GAAG;IAAE,SAAS,EAAE,OAAO,aAAa,CAAA;CAAE,CAAA;AAEnG,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA"}
|
|
@@ -1,53 +1,48 @@
|
|
|
1
|
+
import { Enum, type EnumValue } from '@ariestools/sdk/enum';
|
|
1
2
|
import type { Thread } from './thread.ts';
|
|
2
3
|
/** Pool event type. Specifies the type of each `PoolEvent`. */
|
|
3
|
-
export declare
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
taskQueueDrained = "taskQueueDrained",
|
|
16
|
-
/** A worker started executing a task. */
|
|
17
|
-
taskStart = "taskStart",
|
|
18
|
-
/** The pool and its workers were terminated. */
|
|
19
|
-
terminated = "terminated"
|
|
20
|
-
}
|
|
4
|
+
export declare const PoolEventType: Enum<{
|
|
5
|
+
initialized: 'initialized';
|
|
6
|
+
taskCanceled: 'taskCanceled';
|
|
7
|
+
taskCompleted: 'taskCompleted';
|
|
8
|
+
taskFailed: 'taskFailed';
|
|
9
|
+
taskQueued: 'taskQueued';
|
|
10
|
+
taskQueueDrained: 'taskQueueDrained';
|
|
11
|
+
taskStart: 'taskStart';
|
|
12
|
+
terminated: 'terminated';
|
|
13
|
+
}>;
|
|
14
|
+
/** Pool event type. Specifies the type of each `PoolEvent`. */
|
|
15
|
+
export type PoolEventType = EnumValue<typeof PoolEventType>;
|
|
21
16
|
/** A function that runs a task on a worker thread and returns a promise of the result. */
|
|
22
17
|
export type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>;
|
|
23
18
|
/** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */
|
|
24
19
|
export type PoolEvent<ThreadType extends Thread> = {
|
|
25
|
-
type: PoolEventType
|
|
20
|
+
type: (typeof PoolEventType)['initialized'];
|
|
26
21
|
size: number;
|
|
27
22
|
} | {
|
|
28
|
-
type: PoolEventType
|
|
23
|
+
type: (typeof PoolEventType)['taskQueued'];
|
|
29
24
|
taskID: number;
|
|
30
25
|
} | {
|
|
31
|
-
type: PoolEventType
|
|
26
|
+
type: (typeof PoolEventType)['taskQueueDrained'];
|
|
32
27
|
} | {
|
|
33
|
-
type: PoolEventType
|
|
28
|
+
type: (typeof PoolEventType)['taskStart'];
|
|
34
29
|
taskID: number;
|
|
35
30
|
workerID: number;
|
|
36
31
|
} | {
|
|
37
|
-
type: PoolEventType
|
|
32
|
+
type: (typeof PoolEventType)['taskCompleted'];
|
|
38
33
|
returnValue: any;
|
|
39
34
|
taskID: number;
|
|
40
35
|
workerID: number;
|
|
41
36
|
} | {
|
|
42
|
-
type: PoolEventType
|
|
37
|
+
type: (typeof PoolEventType)['taskFailed'];
|
|
43
38
|
error: Error;
|
|
44
39
|
taskID: number;
|
|
45
40
|
workerID: number;
|
|
46
41
|
} | {
|
|
47
|
-
type: PoolEventType
|
|
42
|
+
type: (typeof PoolEventType)['taskCanceled'];
|
|
48
43
|
taskID: number;
|
|
49
44
|
} | {
|
|
50
|
-
type: PoolEventType
|
|
45
|
+
type: (typeof PoolEventType)['terminated'];
|
|
51
46
|
remainingQueue: QueuedTask<ThreadType, any>[];
|
|
52
47
|
};
|
|
53
48
|
/** Descriptor for a worker in a pool, tracking its initialization and running tasks. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool-types.d.ts","sourceRoot":"","sources":["../../../src/master/pool-types.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEzC,+DAA+D;AAC/D,
|
|
1
|
+
{"version":3,"file":"pool-types.d.ts","sourceRoot":"","sources":["../../../src/master/pool-types.ts"],"names":[],"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AAC,CAAA;IAC1C,KAAK,EAAE,KAAK,CAAA;IACZ,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;CACjB,GACC;IACA,IAAI,EAAE,CAAC,OAAO,aAAa,CAAC,CAAC,cAAc,CAAC,CAAA;IAC5C,MAAM,EAAE,MAAM,CAAA;CACf,GACC;IACA,IAAI,EAAE,CAAC,OAAO,aAAa,CAAC,CAAC,YAAY,CAAC,CAAA;IAC1C,cAAc,EAAE,UAAU,CAAC,UAAU,EAAE,GAAG,CAAC,EAAE,CAAA;CAC9C,CAAA;AAEH,wFAAwF;AACxF,MAAM,WAAW,gBAAgB,CAAC,UAAU,SAAS,MAAM;IACzD,mDAAmD;IACnD,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,CAAA;IACzB,+CAA+C;IAC/C,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAA;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,UAAU,CAAC,UAAU,SAAS,MAAM,EAAE,MAAM;IAC3D,eAAe;IACf,EAAE,EAAE,MAAM,CAAA;IAEV,eAAe;IACf,GAAG,EAAE,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;IAExC;;OAEG;IACH,MAAM,IAAI,IAAI,CAAA;IAEd;;;OAGG;IACH,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;CAC9B"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Enum, type EnumValue } from '@ariestools/sdk/enum';
|
|
1
2
|
import type { Observable } from 'observable-fns';
|
|
2
3
|
import type { ObservablePromise } from '../observable-promise.ts';
|
|
3
4
|
import type { $errors, $events, $terminate, $worker } from '../symbols.ts';
|
|
@@ -98,32 +99,31 @@ export interface ImplementationExport {
|
|
|
98
99
|
default: typeof WorkerImplementation;
|
|
99
100
|
}
|
|
100
101
|
/** Event as emitted by worker thread. Subscribe to using `Thread.events(thread)`. */
|
|
101
|
-
export declare
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
}
|
|
102
|
+
export declare const WorkerEventType: Enum<{
|
|
103
|
+
internalError: 'internalError';
|
|
104
|
+
message: 'message';
|
|
105
|
+
termination: 'termination';
|
|
106
|
+
}>;
|
|
107
|
+
/** Event as emitted by worker thread. Subscribe to using `Thread.events(thread)`. */
|
|
108
|
+
export type WorkerEventType = EnumValue<typeof WorkerEventType>;
|
|
109
109
|
/** Event indicating an internal error occurred in the worker. */
|
|
110
110
|
export interface WorkerInternalErrorEvent {
|
|
111
111
|
/** Error raised by the worker implementation. */
|
|
112
112
|
error: Error;
|
|
113
113
|
/** Event discriminant. */
|
|
114
|
-
type: WorkerEventType
|
|
114
|
+
type: (typeof WorkerEventType)['internalError'];
|
|
115
115
|
}
|
|
116
116
|
/** Event containing a message received from the worker. */
|
|
117
117
|
export interface WorkerMessageEvent<Data> {
|
|
118
118
|
/** Message data received from the worker. */
|
|
119
119
|
data: Data;
|
|
120
120
|
/** Event discriminant. */
|
|
121
|
-
type: WorkerEventType
|
|
121
|
+
type: (typeof WorkerEventType)['message'];
|
|
122
122
|
}
|
|
123
123
|
/** Event indicating the worker has been terminated. */
|
|
124
124
|
export interface WorkerTerminationEvent {
|
|
125
125
|
/** Event discriminant. */
|
|
126
|
-
type: WorkerEventType
|
|
126
|
+
type: (typeof WorkerEventType)['termination'];
|
|
127
127
|
}
|
|
128
128
|
/** Union of all possible worker event types. */
|
|
129
129
|
export type WorkerEvent = WorkerInternalErrorEvent | WorkerMessageEvent<any> | WorkerTerminationEvent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"master.d.ts","sourceRoot":"","sources":["../../../src/types/master.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAEhD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AACj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1C,YAAY,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,oBAAoB,EAAC;IACvD,mDAAmD;IACnD,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,oBAAoB,CAAA;CACtF;AAED,iEAAiE;AACjE,MAAM,WAAW,oBAAoB;IACnC,gDAAgD;IAChD,IAAI,EAAE,OAAO,UAAU,CAAA;IACvB,wDAAwD;IACxD,OAAO,EAAE,OAAO,oBAAoB,CAAA;CACrC;AAED,qFAAqF;AACrF,eAAO,MAAM,eAAe;mBAEX,eAAe;aAErB,SAAS;iBAEL,aAAa;EACjB,CAAA;AACX,qFAAqF;AACrF,MAAM,MAAM,eAAe,GAAG,SAAS,CAAC,OAAO,eAAe,CAAC,CAAA;AAE/D,iEAAiE;AACjE,MAAM,WAAW,wBAAwB;IACvC,iDAAiD;IACjD,KAAK,EAAE,KAAK,CAAA;IACZ,0BAA0B;IAC1B,IAAI,EAAE,CAAC,OAAO,eAAe,CAAC,CAAC,eAAe,CAAC,CAAA;CAChD;AAED,2DAA2D;AAC3D,MAAM,WAAW,kBAAkB,CAAC,IAAI;IACtC,6CAA6C;IAC7C,IAAI,EAAE,IAAI,CAAA;IACV,0BAA0B;IAC1B,IAAI,EAAE,CAAC,OAAO,eAAe,CAAC,CAAC,SAAS,CAAC,CAAA;CAC1C;AAED,uDAAuD;AACvD,MAAM,WAAW,sBAAsB;IACrC,0BAA0B;IAC1B,IAAI,EAAE,CAAC,OAAO,eAAe,CAAC,CAAC,aAAa,CAAC,CAAA;CAC9C;AAED,gDAAgD;AAChD,MAAM,MAAM,WAAW,GAAG,wBAAwB,GAAG,kBAAkB,CAAC,GAAG,CAAC,GAAG,sBAAsB,CAAA"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Enum, type EnumValue } from '@ariestools/sdk/enum';
|
|
1
2
|
/** Serialized representation of an Error for transmission between threads. */
|
|
2
3
|
export interface SerializedError {
|
|
3
4
|
/** Marker distinguishing serialized errors from ordinary values. */
|
|
@@ -10,23 +11,23 @@ export interface SerializedError {
|
|
|
10
11
|
stack?: string;
|
|
11
12
|
}
|
|
12
13
|
/** Types of messages that the master thread can send to a worker. */
|
|
13
|
-
export declare
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
export declare const MasterMessageType: Enum<{
|
|
15
|
+
cancel: 'cancel';
|
|
16
|
+
run: 'run';
|
|
17
|
+
}>;
|
|
18
|
+
/** Types of messages that the master thread can send to a worker. */
|
|
19
|
+
export type MasterMessageType = EnumValue<typeof MasterMessageType>;
|
|
19
20
|
/** Message sent by the master to cancel a running job. */
|
|
20
21
|
export type MasterJobCancelMessage = {
|
|
21
22
|
/** Message discriminant. */
|
|
22
|
-
type: MasterMessageType
|
|
23
|
+
type: (typeof MasterMessageType)['cancel'];
|
|
23
24
|
/** Unique identifier of the job to cancel. */
|
|
24
25
|
uid: number;
|
|
25
26
|
};
|
|
26
27
|
/** Message sent by the master to run a function in the worker. */
|
|
27
28
|
export type MasterJobRunMessage = {
|
|
28
29
|
/** Message discriminant. */
|
|
29
|
-
type: MasterMessageType
|
|
30
|
+
type: (typeof MasterMessageType)['run'];
|
|
30
31
|
/** Unique identifier assigned to the job. */
|
|
31
32
|
uid: number;
|
|
32
33
|
/** Exposed module method to invoke, or omitted for an exposed function. */
|
|
@@ -35,22 +36,19 @@ export type MasterJobRunMessage = {
|
|
|
35
36
|
args: any[];
|
|
36
37
|
};
|
|
37
38
|
/** Types of messages that a worker thread can send to the master. */
|
|
38
|
-
export declare
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
/** An error escaped the worker job handler. */
|
|
48
|
-
uncaughtError = "uncaughtError"
|
|
49
|
-
}
|
|
39
|
+
export declare const WorkerMessageType: Enum<{
|
|
40
|
+
error: 'error';
|
|
41
|
+
init: 'init';
|
|
42
|
+
result: 'result';
|
|
43
|
+
running: 'running';
|
|
44
|
+
uncaughtError: 'uncaughtError';
|
|
45
|
+
}>;
|
|
46
|
+
/** Types of messages that a worker thread can send to the master. */
|
|
47
|
+
export type WorkerMessageType = EnumValue<typeof WorkerMessageType>;
|
|
50
48
|
/** Message sent by a worker when an uncaught error occurs. */
|
|
51
49
|
export type WorkerUncaughtErrorMessage = {
|
|
52
50
|
/** Message discriminant. */
|
|
53
|
-
type: WorkerMessageType
|
|
51
|
+
type: (typeof WorkerMessageType)['uncaughtError'];
|
|
54
52
|
/** Uncaught error details. */
|
|
55
53
|
error: {
|
|
56
54
|
message: string;
|
|
@@ -61,7 +59,7 @@ export type WorkerUncaughtErrorMessage = {
|
|
|
61
59
|
/** Message sent by a worker after calling `expose()` to signal its API to the master. */
|
|
62
60
|
export type WorkerInitMessage = {
|
|
63
61
|
/** Message discriminant. */
|
|
64
|
-
type: WorkerMessageType
|
|
62
|
+
type: (typeof WorkerMessageType)['init'];
|
|
65
63
|
/** Shape of the function or module exposed by the worker. */
|
|
66
64
|
exposed: {
|
|
67
65
|
type: 'function';
|
|
@@ -73,7 +71,7 @@ export type WorkerInitMessage = {
|
|
|
73
71
|
/** Message sent by a worker when a job encounters an error. */
|
|
74
72
|
export type WorkerJobErrorMessage = {
|
|
75
73
|
/** Message discriminant. */
|
|
76
|
-
type: WorkerMessageType
|
|
74
|
+
type: (typeof WorkerMessageType)['error'];
|
|
77
75
|
/** Unique identifier of the failed job. */
|
|
78
76
|
uid: number;
|
|
79
77
|
/** Serialized failure raised by the job. */
|
|
@@ -82,7 +80,7 @@ export type WorkerJobErrorMessage = {
|
|
|
82
80
|
/** Message sent by a worker containing a job's result value. */
|
|
83
81
|
export type WorkerJobResultMessage = {
|
|
84
82
|
/** Message discriminant. */
|
|
85
|
-
type: WorkerMessageType
|
|
83
|
+
type: (typeof WorkerMessageType)['result'];
|
|
86
84
|
/** Unique identifier of the completed or updated job. */
|
|
87
85
|
uid: number;
|
|
88
86
|
/** Whether an observable job has finished emitting values. */
|
|
@@ -93,7 +91,7 @@ export type WorkerJobResultMessage = {
|
|
|
93
91
|
/** Message sent by a worker when a job starts executing. */
|
|
94
92
|
export type WorkerJobStartMessage = {
|
|
95
93
|
/** Message discriminant. */
|
|
96
|
-
type: WorkerMessageType
|
|
94
|
+
type: (typeof WorkerMessageType)['running'];
|
|
97
95
|
/** Unique identifier of the started job. */
|
|
98
96
|
uid: number;
|
|
99
97
|
/** Asynchronous result protocol used by the job. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../../src/types/messages.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../../src/types/messages.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,KAAK,SAAS,EAAE,MAAM,sBAAsB,CAAA;AAE3D,8EAA8E;AAC9E,MAAM,WAAW,eAAe;IAC9B,oEAAoE;IACpE,cAAc,EAAE,SAAS,CAAA;IACzB,qBAAqB;IACrB,OAAO,EAAE,MAAM,CAAA;IACf,wBAAwB;IACxB,IAAI,EAAE,MAAM,CAAA;IACZ,4CAA4C;IAC5C,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAKD,qEAAqE;AACrE,eAAO,MAAM,iBAAiB;YAEpB,QAAQ;SAEX,KAAK;EACD,CAAA;AACX,qEAAqE;AACrE,MAAM,MAAM,iBAAiB,GAAG,SAAS,CAAC,OAAO,iBAAiB,CAAC,CAAA;AAEnE,0DAA0D;AAC1D,MAAM,MAAM,sBAAsB,GAAG;IACnC,4BAA4B;IAC5B,IAAI,EAAE,CAAC,OAAO,iBAAiB,CAAC,CAAC,QAAQ,CAAC,CAAA;IAC1C,8CAA8C;IAC9C,GAAG,EAAE,MAAM,CAAA;CACZ,CAAA;AAED,kEAAkE;AAClE,MAAM,MAAM,mBAAmB,GAAG;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,eAAe,CAAA;CACvB,CAAA;AAED,gEAAgE;AAChE,MAAM,MAAM,sBAAsB,GAAG;IACnC,4BAA4B;IAC5B,IAAI,EAAE,CAAC,OAAO,iBAAiB,CAAC,CAAC,QAAQ,CAAC,CAAA;IAC1C,yDAAyD;IACzD,GAAG,EAAE,MAAM,CAAA;IACX,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,IAAI,CAAA;IACf,2CAA2C;IAC3C,OAAO,CAAC,EAAE,GAAG,CAAA;CACd,CAAA;AAED,4DAA4D;AAC5D,MAAM,MAAM,qBAAqB,GAAG;IAClC,4BAA4B;IAC5B,IAAI,EAAE,CAAC,OAAO,iBAAiB,CAAC,CAAC,SAAS,CAAC,CAAA;IAC3C,4CAA4C;IAC5C,GAAG,EAAE,MAAM,CAAA;IACX,oDAAoD;IACpD,UAAU,EAAE,YAAY,GAAG,SAAS,CAAA;CACrC,CAAA"}
|
|
@@ -79,13 +79,34 @@ function Transfer(payload, transferables) {
|
|
|
79
79
|
return descriptor;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
// src/types/messages.ts
|
|
83
|
+
import { Enum } from "@ariestools/sdk/enum";
|
|
84
|
+
var MasterMessageType = Enum({
|
|
85
|
+
/** Cancel a previously submitted job. */
|
|
86
|
+
cancel: "cancel",
|
|
87
|
+
/** Run a job in the worker. */
|
|
88
|
+
run: "run"
|
|
89
|
+
});
|
|
90
|
+
var WorkerMessageType = Enum({
|
|
91
|
+
/** A job failed. */
|
|
92
|
+
error: "error",
|
|
93
|
+
/** The worker exposed its callable API. */
|
|
94
|
+
init: "init",
|
|
95
|
+
/** A job produced a result. */
|
|
96
|
+
result: "result",
|
|
97
|
+
/** A job started running. */
|
|
98
|
+
running: "running",
|
|
99
|
+
/** An error escaped the worker job handler. */
|
|
100
|
+
uncaughtError: "uncaughtError"
|
|
101
|
+
});
|
|
102
|
+
|
|
82
103
|
// src/worker/expose.ts
|
|
83
104
|
var isErrorEvent = (value) => value !== void 0 && value.error !== void 0;
|
|
84
105
|
function createExpose(implementation, self2) {
|
|
85
106
|
let exposeCalled = false;
|
|
86
107
|
const activeSubscriptions = /* @__PURE__ */ new Map();
|
|
87
|
-
const isMasterJobCancelMessage = (thing) => thing?.type ===
|
|
88
|
-
const isMasterJobRunMessage = (thing) => thing?.type ===
|
|
108
|
+
const isMasterJobCancelMessage = (thing) => thing?.type === MasterMessageType.cancel;
|
|
109
|
+
const isMasterJobRunMessage = (thing) => thing?.type === MasterMessageType.run;
|
|
89
110
|
const isObservable = (thing) => isSomeObservable(thing) || isZenObservable(thing);
|
|
90
111
|
function isZenObservable(thing) {
|
|
91
112
|
return thing != null && typeof thing === "object" && typeof thing.subscribe === "function";
|
|
@@ -96,7 +117,7 @@ function createExpose(implementation, self2) {
|
|
|
96
117
|
function postFunctionInitMessage() {
|
|
97
118
|
const initMessage = {
|
|
98
119
|
exposed: { type: "function" },
|
|
99
|
-
type:
|
|
120
|
+
type: WorkerMessageType.init
|
|
100
121
|
};
|
|
101
122
|
implementation.postMessageToMaster(initMessage);
|
|
102
123
|
}
|
|
@@ -106,7 +127,7 @@ function createExpose(implementation, self2) {
|
|
|
106
127
|
methods: methodNames,
|
|
107
128
|
type: "module"
|
|
108
129
|
},
|
|
109
|
-
type:
|
|
130
|
+
type: WorkerMessageType.init
|
|
110
131
|
};
|
|
111
132
|
implementation.postMessageToMaster(initMessage);
|
|
112
133
|
}
|
|
@@ -114,7 +135,7 @@ function createExpose(implementation, self2) {
|
|
|
114
135
|
const { payload: error, transferables } = deconstructTransfer(rawError);
|
|
115
136
|
const errorMessage = {
|
|
116
137
|
error: serialize(error),
|
|
117
|
-
type:
|
|
138
|
+
type: WorkerMessageType.error,
|
|
118
139
|
uid
|
|
119
140
|
};
|
|
120
141
|
implementation.postMessageToMaster(errorMessage, transferables);
|
|
@@ -124,7 +145,7 @@ function createExpose(implementation, self2) {
|
|
|
124
145
|
const resultMessage = {
|
|
125
146
|
complete: completed ? true : void 0,
|
|
126
147
|
payload,
|
|
127
|
-
type:
|
|
148
|
+
type: WorkerMessageType.result,
|
|
128
149
|
uid
|
|
129
150
|
};
|
|
130
151
|
implementation.postMessageToMaster(resultMessage, transferables);
|
|
@@ -132,7 +153,7 @@ function createExpose(implementation, self2) {
|
|
|
132
153
|
function postJobStartMessage(uid, resultType) {
|
|
133
154
|
const startMessage = {
|
|
134
155
|
resultType,
|
|
135
|
-
type:
|
|
156
|
+
type: WorkerMessageType.running,
|
|
136
157
|
uid
|
|
137
158
|
};
|
|
138
159
|
implementation.postMessageToMaster(startMessage);
|
|
@@ -141,7 +162,7 @@ function createExpose(implementation, self2) {
|
|
|
141
162
|
try {
|
|
142
163
|
const errorMessage = {
|
|
143
164
|
error: serialize(error),
|
|
144
|
-
type:
|
|
165
|
+
type: WorkerMessageType.uncaughtError
|
|
145
166
|
};
|
|
146
167
|
implementation.postMessageToMaster(errorMessage);
|
|
147
168
|
} catch (subError) {
|