Limit, rate-limit and cancel async jobs
Run async jobs with a concurrency limit and a rate limit, and cancel the rest.
Apache-2.0Runs on this page
Package: @awacloud/fw
Run async jobs with a concurrency limit and a start-rate limit, append their
results under a lock, and cancel the rest with an AbortSignal.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
You fan out work (uploads, API calls, image decoding) and must not flood the browser or the server: N at a time, M starts per second, one shared result list, and a Cancel button that really stops everything.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Replace the
sleepjob with your own(i, signal) => Promise; pass the signal down tofetchso cancellation reaches the network too.
What it shows
semaphore.create(n).acquire({ signal })/release()for the concurrency limit; waiting acquires reject when the signal aborts.tokenBucket.create({ capacity, refillRate, refillInterval })andtake()for the start rate, raced against the signal withabort.race.mutex.create().runExclusive(fn)around the shared result list.- One
AbortControllerfor the whole batch;Promise.allSettledkeeps the count of what was cancelled.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { abort } from '@awacloud/fw/io/sync/abort.js';
import { mutex } from '@awacloud/fw/io/sync/mutex.js';
import { semaphore } from '@awacloud/fw/io/sync/semaphore.js';
import { tokenBucket } from '@awacloud/fw/io/sync/tokenBucket.js';
fw.runtime.registerAllDeep([abort, mutex, semaphore, tokenBucket]);
const ABORT = fw.runtime.resolve('abort');
const MUTEX = fw.runtime.resolve('mutex');
const SEMAPHORE = fw.runtime.resolve('semaphore');
const BUCKET = fw.runtime.resolve('tokenBucket');
/** A 20 ms job that gives up as soon as the signal aborts. */
const sleep = (_i, signal) => ABORT.race(new Promise((resolve) => setTimeout(resolve, 20)), signal);
/**
* Run `count` jobs: at most `concurrency` in flight (semaphore), at most
* `rate` starts per `interval` ms (token bucket), results appended under a
* mutex. Aborting the signal rejects the jobs still waiting and interrupts
* the running ones.
* @param {{ count: number, concurrency?: number, rate?: number, interval?: number, signal?: AbortSignal,
* work?: (i: number, signal?: AbortSignal) => Promise<void>, onLog?: (line: string) => void }} opts
* @returns {Promise<{ done: number[], aborted: number, peak: number }>}
*/
export async function runJobs({
count, concurrency = 2, rate = 4, interval = 100, signal, work = sleep, onLog = () => {},
}) {
const slots = SEMAPHORE.create(concurrency);
const starts = BUCKET.create({ capacity: rate, refillRate: rate, refillInterval: interval });
const lock = MUTEX.create();
const done = [];
let running = 0;
let peak = 0;
const job = async (i) => {
await slots.acquire({ signal });
try {
await ABORT.race(starts.take(), signal);
running++;
peak = Math.max(peak, running);
try { await work(i, signal); } finally { running--; }
await lock.runExclusive(() => { done.push(i); onLog(`job ${i} done`); });
} catch (err) {
onLog(`job ${i} ${/** @type {Error} */ (err).message}`);
throw err;
} finally {
slots.release();
}
};
const results = await Promise.allSettled(Array.from({ length: count }, (_, i) => job(i)));
starts.cancel();
return { done, aborted: results.filter((r) => r.status === 'rejected').length, peak };
}
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
const log = /** @type {HTMLElement} */ (document.getElementById('log'));
/** @type {AbortController | null} */
let controller = null;
async function start() {
controller = new AbortController();
log.replaceChildren();
status.textContent = 'running';
const result = await runJobs({
count: 6,
signal: controller.signal,
onLog: (line) => { log.appendChild(document.createElement('li')).textContent = line; },
});
status.textContent = `${result.done.length} done, ${result.aborted} aborted, peak concurrency ${result.peak}`;
}
/** @type {HTMLElement} */ (document.getElementById('run')).addEventListener('click', start);
/** @type {HTMLElement} */ (document.getElementById('cancel'))
.addEventListener('click', () => controller?.abort(new Error('cancelled')));index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · Limit, rate-limit and cancel async jobs</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Limit, rate-limit and cancel async jobs</h1>
<p>Six jobs of 20 ms, at most 2 at a time, at most 4 starts per 100 ms.</p>
<button id="run" type="button">Run 6 jobs</button>
<button id="cancel" type="button">Cancel</button>
<p id="status" aria-live="polite">idle</p>
<ol id="log" aria-label="Job log"></ol>
</main>
</body>
</html>