Graceful Shutdown Draining In Flight Work
A shutdown coordinator that stops accepting work, waits for in-flight tasks to settle, and force-cancels whatever remains after a deadline.
Code
export async function drain(tracked, options = {}) {
const { deadlineMs = 5000, onForceCancel } = options;
if (!Array.isArray(tracked)) throw new TypeError("tracked must be an array");
if (tracked.length === 0) {
return { completed: 0, cancelled: 0, timedOut: false };
}
const settled = tracked.map((p) => Promise.resolve(p).then(() => "done", () => "failed"));
let timedOut = false;
const outcomes = await Promise.race([
Promise.all(settled),
new Promise((resolve) =>
setTimeout(() => {
timedOut = true;
if (onForceCancel) onForceCancel();
resolve(tracked.map(() => "cancelled"));
}, deadlineMs),
),
]);
const completed = outcomes.filter((o) => o === "done" || o === "failed").length;
const cancelled = outcomes.filter((o) => o === "cancelled").length;
return { completed, cancelled, timedOut };
}Report a problem with this exampleOpens a pre-filled issue on GitHub.