Live import progress across workers
struct BatchReport { source string checked int32 rejected int32 } interface Counts { checked number rejected number batches number } struct Progress { reports BatchReport[] private checked = 0 private rejected = 0 private mu rwMutex async publish(report BatchReport) { await mu.mute() defer mu.unmute() reports[reports.length] = report checked += report.checked rejected += report.rejected } async summary() Counts { await mu.readMute() defer mu.readUnmute() return {checked: checked, rejected: rejected, batches: reports.length} } } async func scan(progress Progress, source string, entries int32[], delay number) bool { // Space out the batches so that updates are visible in the preview. await <-after(delay) let rejected = 0 for entry in entries { if entry < 0 { rejected++ } } await progress.publish(BatchReport{ source: source, checked: entries.length as int32, rejected: rejected as int32, }) return typeof document == 'undefined' } const progress = Progress{reports: make(BatchReport[], 2)} const checkedValue = <dd>0</dd> const rejectedValue = <dd>0</dd> const batchesValue = <dd>0 / 2</dd> const status = <dl data-shared-progress="true" aria-live="polite" aria-atomic="true"> <div><dt>Checked</dt>{checkedValue}</div> <div><dt>Rejected</dt>{rejectedValue}</div> <div><dt>Batches</dt>{batchesValue}</div> </dl> const bar = <progress value={0} max={2} aria-label="Batches"></progress> const log = <ol></ol> const mode = <p hidden data-mode="true"></p> document.body.append(status, bar, log, mode) async func showBatch(source string) { const counts = await progress.summary() checkedValue.textContent = String(counts.checked) rejectedValue.textContent = String(counts.rejected) batchesValue.textContent = `${counts.batches} / 2` bar.value = counts.batches log.append(<li data-checked={String(counts.checked)} data-rejected={String(counts.rejected)} data-batches={String(counts.batches)} >{source} · Checked {counts.checked} · rejected {counts.rejected}</li>) } const north = go scan(progress, 'North', [10, -1, 18], 160) const south = go scan(progress, 'South', [-5, 22], 850) const worker = await north mode.textContent = worker ? 'Web Worker · shared memory' : 'Owning thread · shared memory unavailable' mode.hidden = false await showBatch('North') await south await showBatch('South') console.log(Struct.toObject(progress))
- Checked
- 3
- Rejected
- 1
- Batches
- 1 / 2
- North · Checked 3 · rejected 1
Web Worker · shared memory
The program printed nothing to the console.