@tradalab/tskit
v0.3.0
Published
Framework-free TypeScript shared across tradalab: progress, retained resources, fetch, byte cache, assets across realms, Go wasm
Readme
@tradalab/tskit
Framework-free TypeScript shared across tradalab. No runtime dependency; every subpath imports in a page, a worker, an AudioWorklet and Node.
pnpm add @tradalab/tskit| Subpath | What it gives you |
|---|---|
| @tradalab/tskit/progress | ProgressTracker: progress over many items, bytes and phases |
| @tradalab/tskit/retain | Retainer: shared, reference-counted values with a keep time |
| @tradalab/tskit/fetch | fetchBytes: streamed download with stall timeout, retry and integrity check |
| @tradalab/tskit/cache | openByteStore: bytes in Cache Storage per name and version, memory fallback |
| @tradalab/tskit/assets | createAssets: the four above as one manager for a manifest of files; serve and connectAssets carry it into workers and worklets |
| @tradalab/tskit/gowasm | start a Go wasm module in any realm: AudioWorklet polyfills, sync start, a check that wasm_exec.js matches the .wasm |
Assets
import { createAssets } from "@tradalab/tskit/assets"
const assets = createAssets({
name: "mediakit",
version: "3.0.0",
fetch: (url, init) => fetch(url, init),
manifest: [
{ id: "face", url: "/mediakit/face_landmarker.task" },
{ id: "background", url: "/backgrounds/office.jpg", cacheable: false },
],
})
await assets.purgeOld()
await assets.preload(["face"], (p) => show(p.ratio, p.loaded, p.total))
const face = await assets.acquire("face", {
build: (bytes) => FaceLandmarker.createFromOptions(fileset, { baseOptions: { modelAssetBuffer: bytes } }),
dispose: (landmarker) => landmarker.close(),
})
face.release()fetchis required. The kit never calls the globalfetch: the app decides how requests go out.- Bytes live in Cache Storage under
<name>-v<version>;purgeOld()deletes the other versions of the same name. Where Cache Storage is missing or refuses to open (not a secure context, an AudioWorklet, some private modes) they stay in memory for the page;usage().storesays which. acquirebuilds once for every holder. After the lastreleasethe value is kept forkeepMs(default 30 s, 0 whennavigator.deviceMemoryis 4 or less) and then disposed. A wasm runtime does not reliably return its memory ondispose; terminate the worker that holds it there.acquireof an id already being built or held joins it: the runtime passed first is the one used. Every caller after the first gets its own copy frombytes, so transferring one copy to a worker does not empty another.state(id).phaseisidle,fetching,building,ready,keptorfailed, witherrorfor the last; an abort goes back toidle, notfailed.state(id)andsnapshot()return the same frozen object until something changes, so either can be thegetSnapshotofuseSyncExternalStorewithsubscribe.- A download shared by several callers stops only when every one of them has aborted.
Workers and worklets
The page owns the manager; other realms ask it for bytes over a port and tell it how their builds go.
const worker = new Worker("/detect-worker.js", { type: "module" })
const stop = assets.serve(worker)
// in the worker
import { connectAssets } from "@tradalab/tskit/assets"
const assets = connectAssets(self, { name: "mediakit", version: "3.0.0" })
const face = await assets.acquire("face", { build: (bytes) => makeLandmarker(bytes), dispose: (l) => l.close() })- A worker asks once per asset; the page downloads it once however many workers ask, and the worker then reads the bytes from its own Cache Storage, so nothing large crosses the port. Where the realm has no Cache Storage the bytes come in the message instead.
- The worker's
building,readyandfailedshow in the page'sstate(id)when the page does not build that id itself. With several workers, one still building wins over one ready, and one ready over one failed. Call the functionservereturned when the worker goes away;close()on the client does the same from the other side. - Messages share the port with the app's own, so the app's
onmessagesees them too. Skip them withisAssetsMessage(e.data)before anything else: a handler that treats an unknown message as "ready" or as "stop" otherwise acts on the kit's traffic. - A worker started by a worker is served through it:
client.serve(childWorker)relays the child's requests to the page and the child's builds up to it, so the page still downloads once and still sees every realm's state. Stopping that service, or the child'sclose(), drops only the child's state. - A worker aborting its request does not stop the page's download, which other callers may share.
- An AudioWorklet can neither fetch nor reach Cache Storage. Give it the bytes in
processorOptionswithawait assets.bytesFor(["go"]); each is a copy the caller may transfer.
Go wasm
import { goWorkletSource, startGo, startGoSync, runWorkletTimers } from "@tradalab/tskit/gowasm"
await ctx.audioWorklet.addModule(URL.createObjectURL(new Blob([goWorkletSource(wasmExecSource)])))
// in the processor's constructor, and runWorkletTimers() at the top of process()
const go = startGoSync(options.processorOptions.go)
go.exports.process(0.5)
const samples = go.view(Float32Array, go.exports.frameBuf(), 480)- An
AudioWorkletGlobalScopelacksperformance,crypto,TextEncoder,TextDecoderandsetTimeout, all five of whichwasm_exec.jsneeds (measured on Edge 157 and Firefox 160).goWorkletSourceprepends polyfills for exactly what is missing; timers run whenrunWorkletTimers()is called. The polyfills ship as source text, not as a function turned into text, so an app bundler (keepNames, minify) cannot break what reaches the worklet. startGoandstartGoSynccheck the module's imports against the loadedwasm_exec.jsfirst and throwGoMismatchErrornaming what is missing, instead of aLinkErrorthat names neither file. A worklet constructor has to be synchronous: usestartGoSyncthere.- Take a view of Go memory with
go.view(...)after every call that may allocate. When Go grows its memory, a view taken before has length 0 and reads nothing, without an error. main()must not return (select {}): calling into a Go module whosemainhas exited fails.
Progress
total is 0 until every item has a size, and stays 0 when one has none (no Content-Length, or a
compressed response); show done/items then. loaded never passes a known total, and drops
when a download breaks off. A failed item counts as done and adds no bytes. Listeners are called
at most every 100 ms for bytes and at once for phase changes; one that throws is removed.
ratio counts a building item as 0.9.
Fetch
fetchBytes(url, { fetch }) retries network errors, 5xx, 408 and 429 with a doubling backoff
(default 2 retries from 500 ms), never 4xx. It gives up when no byte arrives for stallMs
(default 15 s) rather than after a fixed total time. With sha256 a mismatch fails at once.
Errors are FetchError with failure (status, network, stall, integrity, aborted),
retryable and status.
