1
0

feat: serializing queue with min-interval pacing

This commit is contained in:
2026-08-29 16:05:29 +02:00
parent a54f56834d
commit b79a72a81b
2 changed files with 69 additions and 0 deletions

27
server/src/queue.ts Normal file
View File

@@ -0,0 +1,27 @@
export interface SerialQueueOptions {
/** Minimum delay between task starts. 0 = unpaced. */
minIntervalMs?: number
}
export class SerialQueue {
private tail: Promise<unknown> = Promise.resolve()
private lastStart = 0
private minIntervalMs: number
constructor(opts: SerialQueueOptions = {}) {
this.minIntervalMs = opts.minIntervalMs ?? 0
}
run<T>(fn: () => Promise<T>): Promise<T> {
const result = this.tail.then(async () => {
if (this.minIntervalMs > 0) {
const wait = this.lastStart + this.minIntervalMs - Date.now()
if (wait > 0) await new Promise((r) => setTimeout(r, wait))
}
this.lastStart = Date.now()
return fn()
})
this.tail = result.catch(() => {})
return result
}
}