From d853e57db7c13424b9763b1d39998f2dbe6ca7dc Mon Sep 17 00:00:00 2001 From: npmrun <1549469775@qq.com> Date: Thu, 14 May 2026 14:46:55 +0800 Subject: [PATCH] feat: add Executor Pool with concurrency control --- server/scheduler/executor-pool.ts | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 server/scheduler/executor-pool.ts diff --git a/server/scheduler/executor-pool.ts b/server/scheduler/executor-pool.ts new file mode 100644 index 0000000..a78ed92 --- /dev/null +++ b/server/scheduler/executor-pool.ts @@ -0,0 +1,50 @@ +import log4js from "logger"; + +const logger = log4js.getLogger("SCHEDULER"); + +type QueuedTask = { + run: () => void; +}; + +export class ExecutorPool { + private running = 0; + private queue: QueuedTask[] = []; + private maxConcurrency: number; + + constructor(maxConcurrency = 5) { + this.maxConcurrency = maxConcurrency; + } + + get activeCount(): number { + return this.running; + } + + get queuedCount(): number { + return this.queue.length; + } + + async execute(fn: () => Promise): Promise { + if (this.running >= this.maxConcurrency) { + logger.info( + "Pool full (%d/%d), queuing task (%d in queue)", + this.running, + this.maxConcurrency, + this.queue.length + 1 + ); + await new Promise((resolve) => { + this.queue.push({ run: resolve }); + }); + } + + this.running++; + try { + await fn(); + } finally { + this.running--; + const next = this.queue.shift(); + if (next) { + next.run(); + } + } + } +}