feat: serializing queue with min-interval pacing
This commit is contained in:
27
server/src/queue.ts
Normal file
27
server/src/queue.ts
Normal 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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user