Open in a new tab

One fw worker hashes a list of inputs and, between inputs, calls progress() on the page through an RPC port.

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

When to use it

A long job runs off the main thread and the page needs more than its final answer: progress, a log line, a question back to the page. With RPC the worker calls named page functions and awaits them, instead of decoding a stream of raw messages.

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. Put your own functions in RPC.create({ ... }) on the page, and call them from the worker as await page.name(...).

What it shows

  • processRPC.create({ progress }) on the page: the functions the worker may call, and the port pair to hand over.
  • fw.createWorker(fn, { dependencies }): the worker's source is the function itself, so it captures nothing; fw serialises processRPC, sha256 and bitArray into it.
  • postMessage(inputs, [port[0]]) transfers one end of the port; in the worker, processRPC.open(event.ports[0]) gives the page proxy.
  • A worker that cannot start (a strict worker-src policy, for example) is reported on the page instead of leaving it waiting. For a pool of workers and an inline fallback, see fw/process-workers.

Code

main.js

javascriptApache-2.070 lines

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

fw.runtime.registerAllDeep([processRPC, sha256]);
const RPC = fw.runtime.resolve('processRPC');

/**
 * The worker's code. It captures nothing (its source is what the worker
 * gets): it opens the page's RPC port, hashes each input, and awaits
 * `page.progress(n)` between inputs, a call into the page.
 * @param {{ libs: Record<string, any> }} ctx
 */
function worker({ libs }) {
    self.onmessage = async (event) => {
        const page = await libs.processRPC.open(event.ports[0]);
        const hashes = [];
        for (const text of event.data) {
            const bytes = libs.bitArray.ba_to_ui8(libs.sha256.hash(text));
            hashes.push(Array.from(bytes, (/** @type {number} */ b) => b.toString(16).padStart(2, '0')).join(''));
            await page.progress(hashes.length);
        }
        self.postMessage(hashes);
    };
}

/**
 * Hash the inputs in one worker that reports its progress to the page over RPC.
 * @param {string[]} inputs @param {(done: number) => void} onProgress @returns {Promise<string[]>}
 */
export function hashWithProgress(inputs, onProgress) {
    const { port, close } = RPC.create({ progress: onProgress });
    return new Promise((resolve, reject) => {
        const thread = fw.createWorker(worker, { dependencies: ['processRPC', 'sha256', 'bitArray'] });
        /** @param {(value: any) => void} settle @param {any} value */
        const done = (settle, value) => {
            close();
            thread.terminate();
            settle(value);
        };
        thread.onmessage = (/** @type {{ data: string[] }} */ event) => done(resolve, event.data);
        thread.onerror = (/** @type {unknown} */ err) => {
            done(reject, err instanceof Error ? err : new Error(String(err)));
        };
        thread.postMessage(inputs, [port[0]]);
    });
}

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

el('run').addEventListener('click', async () => {
    const list = /** @type {HTMLTextAreaElement} */ (el('inputs')).value.split('\n').filter(Boolean);
    bar.max = list.length;
    bar.value = 0;
    el('status').textContent = 'hashing…';
    try {
        const hashes = await hashWithProgress(list, (done) => { bar.value = done; });
        el('results').replaceChildren(...hashes.map((hash) => {
            const li = document.createElement('li');
            li.textContent = hash;
            return li;
        }));
        el('status').textContent = `${hashes.length} digests, progress reported over RPC`;
    } 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 · A worker that calls back into the page</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>A worker that calls back into the page</h1>
    <label for="inputs">One input per line</label>
    <textarea id="inputs" rows="4">abc
hello
fw</textarea>
    <button id="run" type="button">Hash in one worker with progress</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>