|
| 1 | +import type { WorkerFactory, WorkerTask } from './types'; |
| 2 | +import type { Worker } from 'node:worker_threads'; |
| 3 | +import type { Subscription } from 'rxjs'; |
| 4 | +import { Subject } from 'rxjs'; |
| 5 | + |
| 6 | +const taskInfoSymbol = Symbol('Task Info Symbol'); |
| 7 | +type TaskCallback = (result: any | undefined, error: Error | undefined) => void; |
| 8 | +type PoolStatus = 'idle' | 'working' | 'queued'; |
| 9 | + |
| 10 | +class WorkerPool { |
| 11 | + protected workerFactory: WorkerFactory; |
| 12 | + protected workers: Set<Worker> = new Set(); |
| 13 | + protected freeWorkers: Array<Worker> = []; |
| 14 | + protected queue: Array<{ task: WorkerTask; callback: TaskCallback }> = []; |
| 15 | + protected terminating: boolean = false; |
| 16 | + protected handleDestroySubscription: Subscription; |
| 17 | + |
| 18 | + public $workerCreated = new Subject<void>(); |
| 19 | + public $workerDestroyed = new Subject<void>(); |
| 20 | + public $workerFreed = new Subject<void>(); |
| 21 | + public $workerError = new Subject<Error>(); |
| 22 | + public $poolStatus = new Subject<PoolStatus>(); |
| 23 | + public poolStatus: PoolStatus = 'idle'; |
| 24 | + |
| 25 | + constructor(workerNum: number, workerFactory: WorkerFactory) { |
| 26 | + if (workerNum < 1) throw Error('TMP IMP must be at least 1 worker'); |
| 27 | + this.workerFactory = workerFactory; |
| 28 | + for (let i = 0; i < workerNum; i++) { |
| 29 | + this.addWorker(); |
| 30 | + } |
| 31 | + |
| 32 | + this.$workerFreed.subscribe(() => { |
| 33 | + if (this.queue.length > 0) { |
| 34 | + const queuedTask = this.queue.shift()!; |
| 35 | + this.runTask(queuedTask.task, queuedTask.callback); |
| 36 | + if (this.queue.length === 0) this.$poolStatus.next('working'); |
| 37 | + } else if (this.freeWorkers.length === this.workers.size) { |
| 38 | + this.$poolStatus.next('idle'); |
| 39 | + } |
| 40 | + }); |
| 41 | + |
| 42 | + this.$poolStatus.subscribe((v) => { |
| 43 | + this.poolStatus = v; |
| 44 | + }); |
| 45 | + |
| 46 | + this.handleDestroySubscription = this.$workerDestroyed.subscribe(() => { |
| 47 | + this.addWorker(); |
| 48 | + }); |
| 49 | + } |
| 50 | + |
| 51 | + protected addWorker() { |
| 52 | + const worker = this.workerFactory(); |
| 53 | + const messageHandler = (result: unknown) => { |
| 54 | + worker[taskInfoSymbol](result, undefined); |
| 55 | + worker[taskInfoSymbol] = undefined; |
| 56 | + this.freeWorkers.push(worker); |
| 57 | + this.$workerFreed.next(); |
| 58 | + }; |
| 59 | + const errorHandler = (e) => { |
| 60 | + if (worker[taskInfoSymbol]) worker[taskInfoSymbol](undefined, e); |
| 61 | + else this.$workerError.next(e); |
| 62 | + }; |
| 63 | + worker.on('message', messageHandler); |
| 64 | + worker.on('error', errorHandler); |
| 65 | + worker.once('exit', () => { |
| 66 | + worker.off('message', messageHandler); |
| 67 | + worker.off('error', errorHandler); |
| 68 | + this.workers.delete(worker); |
| 69 | + this.$workerDestroyed.next(); |
| 70 | + }); |
| 71 | + |
| 72 | + // TODO: debugging |
| 73 | + // worker.on('message', (...args) => console.log('DEBUG message: ', args)); |
| 74 | + // worker.on('messageerror', (...args) => console.log('DEBUG messageerror: ', args)); |
| 75 | + // worker.on('error', (...args) => console.log('DEBUG error: ', args)); |
| 76 | + // worker.on('exit', (...args) => console.log('DEBUG exit: ', args)); |
| 77 | + // worker.on('online', (...args) => console.log('DEBUG online: ', args)); |
| 78 | + |
| 79 | + this.workers.add(worker); |
| 80 | + this.$workerCreated.next(); |
| 81 | + this.freeWorkers.push(worker); |
| 82 | + this.$workerFreed.next(); |
| 83 | + } |
| 84 | + |
| 85 | + public runTask(task: any, callback: any) { |
| 86 | + if (this.terminating) throw Error('TMP IMP terminating'); |
| 87 | + if (this.freeWorkers.length === 0) { |
| 88 | + this.queue.push({ task, callback }); |
| 89 | + if (this.queue.length === 1) this.$poolStatus.next('queued'); |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + const wasIdle = this.freeWorkers.length === this.workers.size; |
| 94 | + const worker = this.freeWorkers.pop()!; |
| 95 | + if (wasIdle) this.$poolStatus.next('working'); |
| 96 | + worker[taskInfoSymbol] = callback; |
| 97 | + worker.postMessage(task); |
| 98 | + } |
| 99 | + |
| 100 | + public async terminate(force: boolean) { |
| 101 | + this.terminating = true; |
| 102 | + this.handleDestroySubscription.unsubscribe(); |
| 103 | + if (!force) { |
| 104 | + // Prevent new tasks and wait for exising queue to drain |
| 105 | + await new Promise<void>((resolve) => { |
| 106 | + if ( |
| 107 | + this.freeWorkers.length === this.workers.size && |
| 108 | + this.queue.length === 0 |
| 109 | + ) { |
| 110 | + return resolve(); |
| 111 | + } |
| 112 | + const subscription = this.$workerFreed.subscribe(() => { |
| 113 | + // Wait for the queue to drain and the workers to free |
| 114 | + if ( |
| 115 | + this.freeWorkers.length === this.workers.size && |
| 116 | + this.queue.length === 0 |
| 117 | + ) { |
| 118 | + subscription.unsubscribe(); |
| 119 | + resolve(); |
| 120 | + } |
| 121 | + }); |
| 122 | + }); |
| 123 | + } |
| 124 | + |
| 125 | + const workerTerminatePs: Array<Promise<number>> = []; |
| 126 | + for (const worker of this.workers) { |
| 127 | + workerTerminatePs.push(worker.terminate()); |
| 128 | + } |
| 129 | + await Promise.all(workerTerminatePs); |
| 130 | + // Console.log('workers', this.workers.size); |
| 131 | + // console.log('queue', this.queue.length); |
| 132 | + // console.log('freeWorkers', this.freeWorkers.length); |
| 133 | + // Cleaning up subjects |
| 134 | + this.$workerCreated.complete(); |
| 135 | + this.$workerDestroyed.complete(); |
| 136 | + this.$workerFreed.complete(); |
| 137 | + this.$workerError.complete(); |
| 138 | + this.$poolStatus.complete(); |
| 139 | + } |
| 140 | + |
| 141 | + /** |
| 142 | + * Returns a promise that will resolve once all tasks have been completed. |
| 143 | + * Will reject if a task failed. |
| 144 | + */ |
| 145 | + public completed(): Promise<void> { |
| 146 | + return new Promise<void>((resolve, reject) => { |
| 147 | + if (this.poolStatus === 'idle') return resolve(); |
| 148 | + const errorSubscription = this.$workerError.subscribe((e) => { |
| 149 | + errorSubscription.unsubscribe(); |
| 150 | + stateSubscription.unsubscribe(); |
| 151 | + reject(e); |
| 152 | + }); |
| 153 | + const stateSubscription = this.$poolStatus.subscribe((v) => { |
| 154 | + if (v === 'idle') { |
| 155 | + errorSubscription.unsubscribe(); |
| 156 | + stateSubscription.unsubscribe(); |
| 157 | + return resolve(); |
| 158 | + } |
| 159 | + }); |
| 160 | + }); |
| 161 | + } |
| 162 | + |
| 163 | + /** |
| 164 | + * Returns a promise that will resolve once all tasks have been completed. |
| 165 | + */ |
| 166 | + public settled(): Promise<void> { |
| 167 | + return new Promise<void>((resolve) => { |
| 168 | + if (this.poolStatus === 'idle') return resolve(); |
| 169 | + const subscription = this.$poolStatus.subscribe((v) => { |
| 170 | + if (v === 'idle') { |
| 171 | + subscription.unsubscribe(); |
| 172 | + return resolve(); |
| 173 | + } |
| 174 | + }); |
| 175 | + }); |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +export default WorkerPool; |
0 commit comments