|
| 1 | +import { Logger, NoopLogger } from '@embedpdf/models'; |
| 2 | +import type { EncodeImageRequest, EncodeImageResponse } from './image-encoder-worker'; |
| 3 | + |
| 4 | +const LOG_SOURCE = 'ImageEncoderPool'; |
| 5 | +const LOG_CATEGORY = 'Encoder'; |
| 6 | + |
| 7 | +interface EncodingTask { |
| 8 | + resolve: (blob: Blob) => void; |
| 9 | + reject: (error: Error) => void; |
| 10 | +} |
| 11 | + |
| 12 | +/** |
| 13 | + * Pool of image encoding workers to offload OffscreenCanvas operations |
| 14 | + * from the main PDFium worker thread |
| 15 | + */ |
| 16 | +export class ImageEncoderWorkerPool { |
| 17 | + private workers: Worker[] = []; |
| 18 | + private pendingTasks = new Map<string, EncodingTask>(); |
| 19 | + private nextWorkerId = 0; |
| 20 | + private requestCounter = 0; |
| 21 | + private logger: Logger; |
| 22 | + |
| 23 | + /** |
| 24 | + * Create a pool of image encoding workers |
| 25 | + * @param poolSize - Number of workers to create (default: 2) |
| 26 | + * @param workerUrl - URL to the worker script |
| 27 | + * @param logger - Logger instance |
| 28 | + */ |
| 29 | + constructor( |
| 30 | + private poolSize: number = 2, |
| 31 | + private workerUrl: string, |
| 32 | + logger?: Logger, |
| 33 | + ) { |
| 34 | + this.logger = logger ?? new NoopLogger(); |
| 35 | + this.initialize(); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Initialize the worker pool |
| 40 | + */ |
| 41 | + private initialize() { |
| 42 | + this.logger.debug( |
| 43 | + LOG_SOURCE, |
| 44 | + LOG_CATEGORY, |
| 45 | + `Creating worker pool with ${this.poolSize} workers`, |
| 46 | + ); |
| 47 | + |
| 48 | + for (let i = 0; i < this.poolSize; i++) { |
| 49 | + try { |
| 50 | + const worker = new Worker(this.workerUrl, { type: 'module' }); |
| 51 | + worker.onmessage = this.handleWorkerMessage.bind(this); |
| 52 | + worker.onerror = this.handleWorkerError.bind(this); |
| 53 | + this.workers.push(worker); |
| 54 | + |
| 55 | + this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Worker ${i} created successfully`); |
| 56 | + } catch (error) { |
| 57 | + this.logger.error(LOG_SOURCE, LOG_CATEGORY, `Failed to create worker ${i}:`, error); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Handle messages from workers |
| 64 | + */ |
| 65 | + private handleWorkerMessage(event: MessageEvent<EncodeImageResponse>) { |
| 66 | + const response = event.data; |
| 67 | + const task = this.pendingTasks.get(response.id); |
| 68 | + |
| 69 | + if (!task) { |
| 70 | + this.logger.warn( |
| 71 | + LOG_SOURCE, |
| 72 | + LOG_CATEGORY, |
| 73 | + `Received response for unknown task: ${response.id}`, |
| 74 | + ); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + this.pendingTasks.delete(response.id); |
| 79 | + |
| 80 | + if (response.type === 'result') { |
| 81 | + task.resolve(response.data as Blob); |
| 82 | + } else { |
| 83 | + const errorData = response.data as { message: string }; |
| 84 | + task.reject(new Error(errorData.message)); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + /** |
| 89 | + * Handle worker errors |
| 90 | + */ |
| 91 | + private handleWorkerError(error: ErrorEvent) { |
| 92 | + this.logger.error(LOG_SOURCE, LOG_CATEGORY, 'Worker error:', error.message); |
| 93 | + } |
| 94 | + |
| 95 | + /** |
| 96 | + * Get the next available worker using round-robin |
| 97 | + */ |
| 98 | + private getNextWorker(): Worker | null { |
| 99 | + if (this.workers.length === 0) { |
| 100 | + return null; |
| 101 | + } |
| 102 | + |
| 103 | + const worker = this.workers[this.nextWorkerId]; |
| 104 | + this.nextWorkerId = (this.nextWorkerId + 1) % this.workers.length; |
| 105 | + return worker; |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Encode ImageData to Blob using a worker from the pool |
| 110 | + * @param imageData - Raw image data |
| 111 | + * @param imageType - Target image format |
| 112 | + * @param quality - Image quality (0-1) for lossy formats |
| 113 | + * @returns Promise that resolves to encoded Blob |
| 114 | + */ |
| 115 | + encode( |
| 116 | + imageData: { data: Uint8ClampedArray; width: number; height: number }, |
| 117 | + imageType: 'image/png' | 'image/jpeg' | 'image/webp' = 'image/webp', |
| 118 | + quality?: number, |
| 119 | + ): Promise<Blob> { |
| 120 | + return new Promise((resolve, reject) => { |
| 121 | + const worker = this.getNextWorker(); |
| 122 | + |
| 123 | + if (!worker) { |
| 124 | + reject(new Error('No workers available in the pool')); |
| 125 | + return; |
| 126 | + } |
| 127 | + |
| 128 | + const requestId = `encode-${Date.now()}-${this.requestCounter++}`; |
| 129 | + this.pendingTasks.set(requestId, { resolve, reject }); |
| 130 | + |
| 131 | + const request: EncodeImageRequest = { |
| 132 | + id: requestId, |
| 133 | + type: 'encode', |
| 134 | + data: { |
| 135 | + imageData: { |
| 136 | + data: imageData.data, |
| 137 | + width: imageData.width, |
| 138 | + height: imageData.height, |
| 139 | + }, |
| 140 | + imageType, |
| 141 | + quality, |
| 142 | + }, |
| 143 | + }; |
| 144 | + |
| 145 | + this.logger.debug( |
| 146 | + LOG_SOURCE, |
| 147 | + LOG_CATEGORY, |
| 148 | + `Sending encoding request ${requestId} (${imageData.width}x${imageData.height})`, |
| 149 | + ); |
| 150 | + |
| 151 | + // Transfer the buffer for better performance |
| 152 | + worker.postMessage(request, [imageData.data.buffer]); |
| 153 | + }); |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * Destroy all workers in the pool |
| 158 | + */ |
| 159 | + destroy() { |
| 160 | + this.logger.debug(LOG_SOURCE, LOG_CATEGORY, 'Destroying worker pool'); |
| 161 | + |
| 162 | + // Reject all pending tasks |
| 163 | + this.pendingTasks.forEach((task, id) => { |
| 164 | + task.reject(new Error('Worker pool destroyed')); |
| 165 | + this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Rejected pending task: ${id}`); |
| 166 | + }); |
| 167 | + this.pendingTasks.clear(); |
| 168 | + |
| 169 | + // Terminate all workers |
| 170 | + this.workers.forEach((worker, index) => { |
| 171 | + worker.terminate(); |
| 172 | + this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Worker ${index} terminated`); |
| 173 | + }); |
| 174 | + this.workers = []; |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Get the number of active workers in the pool |
| 179 | + */ |
| 180 | + get activeWorkers(): number { |
| 181 | + return this.workers.length; |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * Get the number of pending encoding tasks |
| 186 | + */ |
| 187 | + get pendingTasksCount(): number { |
| 188 | + return this.pendingTasks.size; |
| 189 | + } |
| 190 | +} |
0 commit comments