Open in a new tab

Hash a list of inputs in a pool of fw workers with a progress bar, and run the same job inline through an in-memory channel when workers are unavailable.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

CPU work that would freeze the page: hashing, compression, parsing. fw workers get the modules you name, so the job code is the same as on the page, and the pool spreads the inputs over N workers.

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. Keep job free of closures over the page: its source text is what the worker runs.

What it shows

  • fw.createWorker(fn, { dependencies, workerFw }): the worker receives { libs, process } with the named modules resolved; with workerFw: processMessage.workerFramework, process has onmessage and postMessage, so the job is host-independent.
  • workerPool.create({ factory, size }), pool.run(input) per input (each finished input moves the progress bar), pool.terminate() when done.
  • processMessage.sync(): the same job, no worker, through a synchronous channel, which is the fallback when Worker is missing.
  • A worker that cannot start (a strict worker-src policy, for example) is reported on the page, not left spinning.
  • For a worker that calls functions on the page while it runs, see fw/process-rpc.

Code

main.js

javascriptApache-2.076 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { workerPool } from '@awacloud/fw/process/workerPool.js';
import { processMessage } from '@awacloud/fw/process/message.js';
import { sha256 } from '@awacloud/fw/crypto/hash/sha256.js';

fw.runtime.registerAllDeep([workerPool, processMessage, sha256]);
const POOL = fw.runtime.resolve('workerPool');
const MESSAGE = fw.runtime.resolve('processMessage');
/** Modules the job needs; fw serialises them into the worker. */
export const DEPS = ['sha256', 'bitArray'];
export const hasWorkers = typeof Worker === 'function';

/**
 * The job, written once for both hosts (`process` is a message channel in a
 * worker and inline). It captures nothing: its source is what the worker gets.
 * @param {{ libs: Record<string, any>, process: { onmessage: Function, postMessage: Function } }} ctx
 */
export function job({ libs, process }) {
    process.onmessage = (/** @type {{ data: string }} */ event) => {
        const bytes = libs.bitArray.ba_to_ui8(libs.sha256.hash(event.data));
        process.postMessage(Array.from(bytes, (/** @type {number} */ b) => b.toString(16).padStart(2, '0')).join(''));
    };
}

/**
 * Hash the inputs over a pool of `size` workers, in input order.
 * `workerFw: processMessage.workerFramework` gives the job its `process`
 * inside the worker (the default is an empty object).
 * @param {string[]} inputs @param {number} size @param {() => void} onDone called once per finished input
 */
export async function hashInPool(inputs, size, onDone) {
    const options = { dependencies: ['processMessage', ...DEPS], workerFw: MESSAGE.workerFramework };
    const pool = POOL.create({ factory: () => fw.createWorker(job, options), size });
    try {
        return await Promise.all(inputs.map((text) => pool.run(text).then((/** @type {string} */ hash) => {
            onDone();
            return hash;
        })));
    } finally {
        pool.terminate();
    }
}

/** The same job inline, through a synchronous in-memory channel. @param {string[]} inputs */
export function hashInline(inputs) {
    const { process, manager } = MESSAGE.sync();
    job({ libs: fw.runtime.resolveAll(DEPS), process });
    /** @type {string[]} */
    const out = [];
    manager.onmessage = (/** @type {{ data: string }} */ event) => out.push(event.data);
    for (const text of inputs) manager.postMessage(text);
    return out;
}

/** @param {string} id */
const el = (id) => /** @type {HTMLElement} */ (document.getElementById(id));
const bar = /** @type {HTMLProgressElement} */ (el('progress'));

el('pool').addEventListener('click', async () => {
    const list = /** @type {HTMLTextAreaElement} */ (el('inputs')).value.split('\n').filter(Boolean);
    bar.max = list.length;
    bar.value = 0;
    el('status').textContent = hasWorkers ? 'hashing in a pool of 2 workers…' : 'no Worker here: running inline';
    try {
        const hashes = hasWorkers ? await hashInPool(list, 2, () => { bar.value += 1; }) : hashInline(list);
        el('results').replaceChildren(...hashes.map((hash) => {
            const li = document.createElement('li');
            li.textContent = hash;
            return li;
        }));
        if (hasWorkers) el('status').textContent = `${hashes.length} digests from a pool of 2 workers`;
    } catch (err) {
        el('status').textContent = `failed: ${/** @type {Error} */ (err).message}`;
    }
});

index.html

htmlApache-2.028 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 · Hash in a worker pool, inline when there is none</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>Hash in a worker pool, inline when there is none</h1>
    <label for="inputs">One input per line</label>
    <textarea id="inputs" rows="4">abc
hello
fw</textarea>
    <button id="pool" type="button">Hash in a pool of 2 workers</button>
    <p id="status" aria-live="polite"></p>
    <progress id="progress" max="1" value="0"></progress>
    <ol id="results" aria-label="SHA-256 digests"></ol>
  </main>
</body>
</html>