Files
hyperframes/packages/engine/src/utils/concurrencyLimit.ts
T
Miguel Ángel 4b68f73fe7 fix(engine): long exports with many clips no longer stall at 90% or hide a timeout (#5375)
* fix(engine): long exports with many clips no longer stall at 90% or hide a timeout

* fix(engine): stop queued frame extractions on cancel and time out distributed assembly

* refactor(engine): simplify the extraction slot check and its concurrency test

* test(engine): prove a cancelled extraction leaves the queue, skip the shell shim on Windows

* test(engine): wait for the held extraction's own record before cancelling the queued one
2026-10-10 02:43:44 +00:00

37 lines
1.2 KiB
TypeScript

/**
* Runs at most `limit` tasks at once; later tasks wait, in order, for a free slot. A waiter whose
* `signal` aborts stops waiting and runs at once without a slot, so a cancel never queues behind others.
*/
export function createConcurrencyLimit(
limit: number,
): <T>(task: () => Promise<T>, signal?: AbortSignal) => Promise<T> {
let active = 0;
const waiting: Array<() => void> = [];
const waitForSlot = (signal?: AbortSignal) =>
new Promise<boolean>((resolve) => {
const granted = () => {
signal?.removeEventListener("abort", aborted);
resolve(true);
};
const aborted = () => {
waiting.splice(waiting.indexOf(granted), 1);
resolve(false);
};
waiting.push(granted);
signal?.addEventListener("abort", aborted, { once: true });
});
return async (task, signal) => {
if (signal?.aborted) return task();
if (active < limit) active++;
else if (!(await waitForSlot(signal))) return task();
try {
return await task();
} finally {
// Hand the slot straight to the next waiter so a newcomer cannot take it first.
const next = waiting.shift();
if (next) next();
else active--;
}
};
}