* We batch items together trying to minimize their processing, for example as * network queries. For that we wait a small moment before processing a batch. * We limit also the number of items we try to process in a single batch so that * if we have many items pending in a short amount of time, we
| 35 | * processing right away. |
| 36 | */ |
| 37 | class BatchProcessor<TItem, TResult> { |
| 38 | |
| 39 | _currentProcessCount: number; |
| 40 | _options: BatchProcessorOptions; |
| 41 | _processBatch: ProcessBatch<TItem, TResult>; |
| 42 | _queue: Array<QueueItem<TItem, TResult>>; |
| 43 | _timeoutHandle: ?number; |
| 44 | |
| 45 | constructor(options: BatchProcessorOptions, processBatch: ProcessBatch<TItem, TResult>) { |
| 46 | this._options = options; |
| 47 | this._processBatch = processBatch; |
| 48 | this._queue = []; |
| 49 | this._timeoutHandle = null; |
| 50 | this._currentProcessCount = 0; |
| 51 | (this: any)._processQueue = this._processQueue.bind(this); |
| 52 | } |
| 53 | |
| 54 | _onBatchFinished() { |
| 55 | this._currentProcessCount--; |
| 56 | this._processQueueOnceReady(); |
| 57 | } |
| 58 | |
| 59 | _onBatchResults(jobs: Array<QueueItem<TItem, TResult>>, results: Array<TResult>) { |
| 60 | invariant(results.length === jobs.length, 'Not enough results returned.'); |
| 61 | for (let i = 0; i < jobs.length; ++i) { |
| 62 | jobs[i].resolve(results[i]); |
| 63 | } |
| 64 | this._onBatchFinished(); |
| 65 | } |
| 66 | |
| 67 | _onBatchError(jobs: Array<QueueItem<TItem, TResult>>, error: mixed) { |
| 68 | for (let i = 0; i < jobs.length; ++i) { |
| 69 | jobs[i].reject(error); |
| 70 | } |
| 71 | this._onBatchFinished(); |
| 72 | } |
| 73 | |
| 74 | _processQueue() { |
| 75 | this._timeoutHandle = null; |
| 76 | const {concurrency} = this._options; |
| 77 | while (this._queue.length > 0 && this._currentProcessCount < concurrency) { |
| 78 | this._currentProcessCount++; |
| 79 | const jobs = this._queue.splice(0, this._options.maximumItems); |
| 80 | this._processBatch(jobs.map(job => job.item)).then( |
| 81 | this._onBatchResults.bind(this, jobs), |
| 82 | this._onBatchError.bind(this, jobs), |
| 83 | ); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | _processQueueOnceReady() { |
| 88 | if (this._queue.length >= this._options.maximumItems) { |
| 89 | clearTimeout(this._timeoutHandle); |
| 90 | process.nextTick(this._processQueue); |
| 91 | return; |
| 92 | } |
| 93 | if (this._timeoutHandle == null) { |
| 94 | this._timeoutHandle = setTimeout( |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…