Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122/** * One heavy job at a time. * * An import expands a whole archive, parses the whole manuscript and writes it * back to the database. An export builds a whole manuscript, then deflates it into * a zip. Both are synchronous once they start, so they hold the event loop for * seconds and hold the bytes for as long as they run: a maximum-size import is * measured at hundreds of megabytes by the time the document is parsed, before * anything else is counted. * * A second request therefore cannot overlap that work. It can only wait and hold * its own copy of the bytes while it does, which is how a 1 GiB instance runs out * of memory without either request being unreasonable. So the expensive paths go * through this queue, and a caller that cannot get a turn is told to come back * rather than left waiting behind work nobody has started. * * A caller can hand over its request's signal. If the caller aborts while it * waits, the queue removes it and settles the call as a refusal. This frees its * place and releases the queued work. The queue does not stop work that already * started. The work runs to its own outcome. * * The work is not offloaded to another thread. It runs here, so the instance * stalls while it runs; that is the larger problem, and this queue does not solve * it. It bounds the memory and the pile of waiting callers. */
/** How many callers may wait for a turn before the answer is "come back later". */const MAX_WAITING = 4;
/** What a refused caller is told, in seconds. */export const RETRY_AFTER_SECONDS = 30;
/** * `ok: false` rather than a thrown error, because every caller has a request to * answer and none of them wants an exception as control flow. It covers a full * queue and a caller whose request aborted while waiting alike: neither ran any * work, and neither gets a value. */export type HeavyResult<T> = { ok: true; value: T } | { ok: false; retryAfter: number };
export type HeavyWorkOptions = { /** * The caller's request signal, when it has one. Aborting it while the caller * waits settles the call as a refusal and frees the place in the queue; * aborting it after the work has started changes nothing, because the work * runs to its own outcome either way. */ signal?: AbortSignal;};
type Waiter = { grant: () => void };
let running = false;const waiting: Waiter[] = [];
/** * Runs `work` with the instance's one heavy slot held, or reports when it will be * free. The slot is released even when the work throws. */export async function withHeavyWork<T>( work: () => T | Promise<T>, options: HeavyWorkOptions = {}): Promise<HeavyResult<T>> { const signal = options.signal;
// A caller that already left has nothing to run and takes no place. if (signal?.aborted) return { ok: false, retryAfter: RETRY_AFTER_SECONDS };
if (running) { if (waiting.length >= MAX_WAITING) return { ok: false, retryAfter: RETRY_AFTER_SECONDS };
const granted = await new Promise<boolean>((resolve) => { const waiter: Waiter = { grant: () => { signal?.removeEventListener('abort', onAbort); resolve(true); } };
function onAbort() { const parked = waiting.indexOf(waiter); if (parked < 0) return;
waiting.splice(parked, 1); resolve(false); }
waiting.push(waiter); signal?.addEventListener('abort', onAbort, { once: true }); });
if (!granted) return { ok: false, retryAfter: RETRY_AFTER_SECONDS }; }
running = true;
try { return { ok: true, value: await work() }; } finally { const next = waiting.shift();
// The slot passes straight to the next caller, so nobody can take it in the // gap between one release and the next start. if (next) next.grant(); else running = false; }}
/** The answer to a caller that found the queue full. */export function busyResponse(retryAfter: number = RETRY_AFTER_SECONDS): Response { return Response.json( { message: 'The instance is busy with another import or export. Try again in a moment.' }, { status: 503, headers: { 'retry-after': String(retryAfter) } } );}
/** Forgets every slot and waiter. A test helper; nothing in the app calls it. */export function resetHeavyWork(): void { running = false; waiting.length = 0;}