Open in a new tab

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

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Replace the sleep job with your own (i, signal) => Promise; pass the signal down to fetch so 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 }) and take() for the start rate, raced against the signal with abort.race.
  • mutex.create().runExclusive(fn) around the shared result list.
  • One AbortController for the whole batch; Promise.allSettled keeps the count of what was cancelled.

Code

main.js

javascriptApache-2.074 lines

// 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

htmlApache-2.025 lines

<!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>