import { priorityQueue, type AsyncPriorityQueue } from 'async'; import { withTimeout } from './utils.js'; export class TaskProcessor { private maxParallelTasks: number; private taskQueue: AsyncPriorityQueue<() => Promise>; constructor(maxParallelTasks: number) { this.maxParallelTasks = maxParallelTasks; this.taskQueue = priorityQueue(function (task, callback) { task().then(() => callback(), (e) => callback(e)); }, this.maxParallelTasks); this.taskQueue.error((e) => { console.log("Error in task queue task: " + e); }) console.log(`Task processor created with a maximum of ${maxParallelTasks} parallel tasks`); } schedule(task: () => Promise, timeoutMs: number, priority = 100): Promise { return new Promise((resolve, reject) => { const wrappedTask = () => withTimeout(task(), timeoutMs); this.taskQueue.push(wrappedTask, priority, (err) => { if (err) { reject(err); } else { resolve(); } }); }) } unsaturated(): Promise { return this.taskQueue.unsaturated(); } }