class ConcurrencyQueue { constructor(maxConcurrency = 2) { this.maxConcurrency = maxConcurrency; this.runningCount = 0; this.queue = []; } enqueue(taskFn, { signal } = {}) { return new Promise((resolve, reject) => { // 취소한 대기 항목만 회수한다. 실행 중인 다른 작업이나 전체 큐를 비우지 않는다. const cleanup = () => signal?.removeEventListener('abort', abort); const entry = { taskFn, resolve, reject, cleanup }; const abort = () => { const index = this.queue.indexOf(entry); if (index >= 0) this.queue.splice(index, 1); cleanup(); reject(new Error('Queued request cancelled')); }; if (signal?.aborted) { abort(); return; } signal?.addEventListener('abort', abort, { once: true }); this.queue.push(entry); this.next(); }); } next() { if (this.runningCount >= this.maxConcurrency) { return; } if (this.queue.length === 0) { return; } const { taskFn, resolve, reject, cleanup } = this.queue.shift(); cleanup(); this.runningCount++; Promise.resolve() .then(() => taskFn()) .then(result => { this.runningCount = Math.max(0, this.runningCount - 1); resolve(result); this.next(); }) .catch(err => { this.runningCount = Math.max(0, this.runningCount - 1); reject(err); this.next(); }); } cancelAll() { const pending = this.queue.splice(0); for (const { reject, cleanup } of pending) { cleanup(); reject(new Error('Queue cancelled')); } } } module.exports = { ConcurrencyQueue };