@orangecharts/wrun-chart-host 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +5 -4
  2. package/dist/constants/feature-flags.constants.js +7 -2
  3. package/dist/host-env.d.ts +3 -19
  4. package/dist/host-ports.types.d.ts +1 -14
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/interfaces/wrun-runtime.interface.d.ts +88 -13
  8. package/dist/interfaces/wrun-runtime.interface.js +17 -3
  9. package/dist/utility/chart/chart-mount-epoch.util.d.ts +12 -0
  10. package/dist/utility/chart/chart-mount-epoch.util.js +32 -0
  11. package/dist/utility/wrun/wrun-bar-count.util.d.ts +17 -6
  12. package/dist/utility/wrun/wrun-bar-count.util.js +27 -12
  13. package/dist/utility/wrun/wrun-host.service.d.ts +114 -50
  14. package/dist/utility/wrun/wrun-host.service.js +351 -151
  15. package/dist/utility/wrun/wrun-hover.util.d.ts +3 -0
  16. package/dist/utility/wrun/wrun-hover.util.js +25 -4
  17. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +2 -2
  18. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +2 -2
  19. package/dist/utility/wrun/wrun-pack.util.d.ts +2 -1
  20. package/dist/utility/wrun/wrun-prefix-cohort.util.d.ts +1 -1
  21. package/dist/utility/wrun/wrun-prefix-cohort.util.js +1 -1
  22. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +5 -3
  23. package/dist/utility/wrun/wrun-sandbox-row-source.d.ts +2 -2
  24. package/dist/utility/wrun/wrun-sha256.leaf.d.ts +13 -0
  25. package/dist/utility/wrun/wrun-sha256.leaf.js +84 -0
  26. package/dist/workers/wrun/wrun-abi-host.d.ts +15 -2
  27. package/dist/workers/wrun/wrun-abi-host.js +31 -12
  28. package/dist/workers/wrun/wrun-engine-handler.d.ts +11 -28
  29. package/dist/workers/wrun/wrun-engine-handler.js +181 -12
  30. package/package.json +1 -1
@@ -1,10 +1,24 @@
1
1
  /**
2
- * Main-thread WRUN host: compiles a package's wasm (sha256-verified against
3
- * the metadata pin when present), owns the sandbox worker, and runs packed
4
- * series requests through it. One shared worker serves every dev overlay;
5
- * requests are id-matched, and a request that outlives its timeout poisons
6
- * the worker (terminate + respawn) so a spinning guest cannot wedge later
7
- * runs.
2
+ * Main-thread WRUN host: loads a package's module into the sandbox worker,
3
+ * owns that worker, and runs packed series requests through it. One shared
4
+ * worker serves every dev overlay; requests are id-matched, and a request
5
+ * that outlives its clock poisons the worker (terminate + respawn) so a
6
+ * spinning guest cannot wedge later runs.
7
+ *
8
+ * Modules (the shared engine protocol, wrun-chart-host 0.6.0): the main
9
+ * thread never hashes and never compiles a module. `loadModule` keeps a
10
+ * private copy of the package's bytes and posts them (`module-load`); the
11
+ * worker hashes them, checks the sheet's `wasm_sha256` pin, clamps the
12
+ * memory, prepares and compiles them (wrun-engine-handler.ts) and answers the
13
+ * module's key, digest and imports, which the opaque handle carries. Every
14
+ * full run and live-start names the module by key and carries the bytes
15
+ * again (copied, never transferred), so a respawned worker compiles them
16
+ * anew; nothing here tracks which keys the worker holds. Each request has
17
+ * two clocks of WRUN_RUN_TIMEOUT_MS: the start ceiling from the post (the
18
+ * wait behind other requests, the compile and the instantiation), then the
19
+ * run deadline from the worker's `{ id, running: true }`, posted once the
20
+ * module is instantiated, when the request executes; a terminal answer
21
+ * settles a request in either phase.
8
22
  *
9
23
  * Isolation: a death of the shared worker (the run timeout, or an error
10
24
  * event with a request in flight) rejects every pending request with
@@ -38,11 +52,10 @@
38
52
  * (`attachWrunStrategy`) exactly like the handle set.
39
53
  */
40
54
  import { ensureWrunChartHostSharedHost, wrunChartHostEnv } from '../../host-env.js';
41
- import { abiAtLeast, attachWrunLive, WrunLiveOrderError, wrunLiveOf } from '../../interfaces/wrun-runtime.interface.js';
55
+ import { abiAtLeast, attachWrunLive, WrunLiveOrderError, wrunLiveOf, wrunModuleKey, } from '../../interfaces/wrun-runtime.interface.js';
42
56
  import { LOCAL_ENGINE_SELF_HEAL_RESET_GRACE_MS, localEngineSelfHealDelayMs, } from '../chart/local-engine-self-heal-backoff.util.js';
43
57
  import { attachWrunStrategy, readWrunStrategySheet, wrunStrategyParamsOf } from './wrun-box-segment.util.js';
44
58
  import { assertWrunSheetAbiCoupling, attachWrunDrawSkips, attachWrunHandles, readWrunHandleDefaults, } from './wrun-handles.util.js';
45
- import { clampWrunModuleMemory } from './wrun-memory-clamp.util.js';
46
59
  import { packWrunRows, unpackWrunResponse, wrunAbiVersion } from './wrun-pack.util.js';
47
60
  import { WrunQuarantinedError, WrunWorkerPoisonError } from './wrun-registry-errors.util.js';
48
61
  import { bindWrunHostLiveSeriesEnd } from './wrun-overlay-drivers.util.js';
@@ -89,9 +102,74 @@ const WRUN_RUN_TIMEOUT_MS = 20_000;
89
102
  export const WRUN_WORKER_RESPAWN_WINDOW_MS = 60_000;
90
103
  /** `strategyBars` stride: open, high, low, close per row. */
91
104
  const STRATEGY_BAR_STRIDE = 4;
92
- /** How many compiled modules the host keeps by wasm digest (compileModule). Every package version, draft Run
93
- * and REPL compile mints a digest, and a compiled module is mostly native memory the heap never shows. */
105
+ /** How many module handles the host keeps (loadModule): every package version, draft Run and REPL compile mints a
106
+ * key, and the engine worker keeps an LRU of the same size of the compiled modules behind them. */
94
107
  export const WRUN_MODULE_CACHE_CAPACITY = 16;
108
+ /** The provisional key tokens of unpinned loads: one per caller bytes object and ABI, held as long as the bytes are. */
109
+ const provisionalModuleKeys = new WeakMap();
110
+ /** An unpinned load's key until the worker names its digest: the caller's bytes object AND the ABI, so loads of one
111
+ * buffer for two ABIs never share (or replace) each other's entry. */
112
+ function provisionalModuleKey(bytes, abi) {
113
+ let byAbi = provisionalModuleKeys.get(bytes);
114
+ if (byAbi === undefined) {
115
+ byAbi = new Map();
116
+ provisionalModuleKeys.set(bytes, byAbi);
117
+ }
118
+ let key = byAbi.get(abi);
119
+ if (key === undefined) {
120
+ key = Object.freeze({ abi });
121
+ byAbi.set(abi, key);
122
+ }
123
+ return key;
124
+ }
125
+ /** The original bytes behind each handle this module's hosts loaded: copied at the load, never handed out, posted
126
+ * (copied, never transferred) with every full run and live-start. A handle no host here loaded has none: its runs
127
+ * carry no bytes, and a worker that does not hold its key refuses them by name. */
128
+ const wrunModuleBytes = new WeakMap();
129
+ const NO_MODULE_BYTES = new Uint8Array(0);
130
+ /** A caller's module bytes as a view of exactly their own range. */
131
+ function moduleBytesView(bytes) {
132
+ return ArrayBuffer.isView(bytes)
133
+ ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
134
+ : new Uint8Array(bytes);
135
+ }
136
+ /** A private copy of a caller's module bytes, in an ordinary buffer of its own: the caller may reuse, change or
137
+ * transfer its buffer after the load, and a shared buffer never backs the copy (a clone of a view on shared memory
138
+ * shares it, so the worker's copy could rewrite the bytes this host keeps). */
139
+ function snapshotModuleBytes(bytes) {
140
+ return new Uint8Array(moduleBytesView(bytes));
141
+ }
142
+ /** Whether a caller's bytes equal a private copy: the length, then every byte. */
143
+ function sameModuleBytes(copy, bytes) {
144
+ const view = moduleBytesView(bytes);
145
+ if (view.byteLength !== copy.byteLength)
146
+ return false;
147
+ for (let at = 0; at < view.byteLength; at += 1) {
148
+ if (view[at] !== copy[at])
149
+ return false;
150
+ }
151
+ return true;
152
+ }
153
+ /** The client's handle for a load the worker answered: opaque, frozen, its imports in the worker's order. */
154
+ function wrunModuleHandleOf(response, abi) {
155
+ return Object.freeze({
156
+ key: response.key,
157
+ sha256: response.sha256,
158
+ abi,
159
+ imports: Object.freeze(response.imports.map(({ module, name }) => Object.freeze({ module, name }))),
160
+ });
161
+ }
162
+ /** A refused load as its caller reads it: the class and the words the main thread's compile threw before 0.6.0 (a
163
+ * pin mismatch names the sheet's pin and the digest the worker found; an engine compile refusal is a
164
+ * WebAssembly.CompileError again; a clamp or rewrite refusal keeps its plain words). */
165
+ function wrunModuleLoadError(response, metadata) {
166
+ if (response.code === 'module-pin-mismatch') {
167
+ return new Error(`WRUN ${metadata.id}: wasm sha256 mismatch (metadata pins ${metadata.wasm_sha256}, bytes are ${response.sha256})`);
168
+ }
169
+ if (response.code === 'module-compile-failed')
170
+ return new WebAssembly.CompileError(response.error);
171
+ return new Error(response.error);
172
+ }
95
173
  /** The quarantine key of a package: its metadata id plus the wasm digest the
96
174
  * metadata pins, so a republished build (new digest) starts clean while every
97
175
  * overlay of the same build shares one hold (two charts, two instances: a
@@ -193,11 +271,14 @@ function packWrunRunRequest(metadata, rows, initArgs, strategy, configure, textP
193
271
  export class WrunBrowserHost {
194
272
  worker = null;
195
273
  pending = new Map();
274
+ /** One counter numbers loads, runs and live-ends: a retired incarnation's late answer names an id no entry holds. */
196
275
  requestSeq = 0;
197
- /** Compiles by wasm digest, least recently used first (Map order: a hit moves its entry to the end). The cache
198
- * only dedupes compiles and owns no module: a mounted overlay keeps the module it was handed (its record), and
199
- * a live session keeps its instance in the worker (live ticks name the session, never a module), so an
200
- * eviction stops neither. */
276
+ /** The order requests enter the `run` phase in (`PendingRequest.runOrder`). */
277
+ runSeq = 0;
278
+ /** Loads by module, least recently used first (Map order: a hit moves its entry to the end). The cache only
279
+ * dedupes loads and owns no module: a mounted overlay keeps the handle it was handed (its record), and a live
280
+ * session keeps its instance in the worker (live ticks name the session, never a module), so an eviction stops
281
+ * neither; a handle's bytes stay behind it whatever the cache lets go, and its runs carry them. */
201
282
  moduleCache = new Map();
202
283
  /** Live sessions the current worker holds (installed by an ok live-start,
203
284
  * dropped by live-end, a sessionLost answer, or the worker's death). */
@@ -213,15 +294,15 @@ export class WrunBrowserHost {
213
294
  * the first death, so the first spawn ever never opens a window. */
214
295
  lastRespawnAt = null;
215
296
  respawnHeldUntil = 0;
216
- /** Spin the sandbox worker and load the shared host (the compile's module
217
- * rewrite, the packer, the strategy resolver) and the authoring kit (the
218
- * run path's two kit tables, the daemon-only sources and the token
219
- * names) ahead of the first add (the Indicators tab opening is the
220
- * signal), so the first package a reader mounts pays neither the worker
221
- * spawn nor a module parse on its click. Idempotent; a load failure
222
- * surfaces on the first compile or run as before, never here. A held
223
- * respawn is not warmed around: the window exists to keep the worker
224
- * down. */
297
+ /** Spin the sandbox worker and load the shared host (the packer, the
298
+ * strategy resolver; the worker holds its own for the module rewrite) and
299
+ * the authoring kit (the run path's two kit tables, the daemon-only
300
+ * sources and the token names) ahead of the first add (the Indicators tab
301
+ * opening is the signal), so the first package a reader mounts pays
302
+ * neither the worker spawn nor a module parse on its click. Idempotent; a
303
+ * load failure surfaces on the first module load or run as before, never
304
+ * here. A held respawn is not warmed around: the window exists to keep the
305
+ * worker down. */
225
306
  warm() {
226
307
  if (this.respawnHold() === null)
227
308
  this.ensureWorker();
@@ -244,79 +325,127 @@ export class WrunBrowserHost {
244
325
  this.lastRespawnAt = null;
245
326
  this.respawnHeldUntil = 0;
246
327
  }
247
- /** Compile (and cache) a package module. The cache key is the sha256 of
248
- * the bytes, so identical bytes compile once whatever package name they
249
- * arrive under. When the metadata pins `wasm_sha256`, a mismatch refuses
250
- * before compilation; so does a memory the clamp refuses (a maximum or a
251
- * starting size over the worker's memory limit, shared or 64-bit memory),
252
- * and a memory declared with no maximum compiles with the limit as its
253
- * maximum (clampWrunModuleMemory).
328
+ /** Load (and cache) a package module: the worker hashes the bytes, refuses a
329
+ * digest other than the sheet's `wasm_sha256` pin with the words this host
330
+ * always used, refuses a memory the clamp refuses (a maximum or a starting
331
+ * size over the worker's memory limit, shared or 64-bit memory), stamps
332
+ * the limit as the maximum of a memory declared without one, exports every
333
+ * mutable global for the live lane's snapshot and restore, and compiles
334
+ * (wrun-engine-handler.ts `compileWrunModuleBytes`). This thread keeps a
335
+ * private copy of the bytes behind the handle and hashes and compiles
336
+ * nothing. A load needs the worker: during a held respawn every load
337
+ * rejects with the held death, a cached one too, and its start ceiling
338
+ * bounds the wait and the compile.
254
339
  *
255
- * The cache is an LRU of WRUN_MODULE_CACHE_CAPACITY compiled modules.
256
- * Every consumer of a digest in flight shares its one compile, and a
257
- * compile in flight is never evicted; eviction drops compiled entries
258
- * only, least recently used first, so the cache passes the capacity
259
- * only while more compiles than that are in flight. A failed compile is
260
- * not cached: its entry leaves before its consumers see the failure, and
261
- * the next request compiles again. */
262
- async compileModule(wasmBytes, metadata) {
263
- const digest = await sha256Hex(wasmBytes);
264
- if (metadata.wasm_sha256 && metadata.wasm_sha256 !== digest) {
265
- throw new Error(`WRUN ${metadata.id}: wasm sha256 mismatch (metadata pins ${metadata.wasm_sha256}, bytes are ${digest})`);
340
+ * The cache is an LRU of WRUN_MODULE_CACHE_CAPACITY handles, keyed by the
341
+ * sheet's pin and ABI when it pins one (its identity before and after the
342
+ * load), else by the bytes object and the ABI until the worker names the
343
+ * digest, then by the module's key; the first handle of a key stays the
344
+ * one every caller shares. A hit serves only bytes equal to the ones its
345
+ * entry loads: other bytes under the key (a pin claimed by bytes it was
346
+ * not verified from, a reused buffer whose content changed) go to the
347
+ * worker, which checks them against the pin, beside the cached entry and
348
+ * never in its place. Every caller of a load in flight shares its one
349
+ * post, and a load in flight is never evicted; eviction drops loaded
350
+ * entries only, least recently used first, so the cache passes the
351
+ * capacity only while more loads than that are in flight. A failed load is
352
+ * not cached: its entry leaves before its callers see the failure, and the
353
+ * next request loads again. Async, as the compile was: every failure (a
354
+ * detached buffer included) is a rejection, and nothing here awaits before
355
+ * the entry is cached. */
356
+ async loadModule(wasmBytes, metadata) {
357
+ // The hold first, before the cache: the window keeps the worker down, and a handle served from the cache now
358
+ // would only meet the held death at its first run.
359
+ const held = this.respawnHold();
360
+ if (held)
361
+ throw held;
362
+ const abi = wrunAbiVersion(metadata);
363
+ const pin = metadata.wasm_sha256 ? metadata.wasm_sha256 : undefined;
364
+ const cacheKey = pin !== undefined ? wrunModuleKey(pin, abi) : provisionalModuleKey(wasmBytes, abi);
365
+ const hit = this.moduleCache.get(cacheKey);
366
+ if (hit !== undefined && sameModuleBytes(hit.bytes, wasmBytes)) {
367
+ // A hit is the most recent use: set again, at the end of the order eviction reads from the front.
368
+ this.moduleCache.delete(cacheKey);
369
+ this.moduleCache.set(cacheKey, hit);
370
+ return hit.handle;
266
371
  }
267
- let entry = this.moduleCache.get(digest);
268
- if (entry) {
269
- // A hit is the most recent use: set again below, at the end of the order eviction reads from the front.
270
- this.moduleCache.delete(digest);
372
+ const bytes = snapshotModuleBytes(wasmBytes);
373
+ // Under a key whose entry loads other bytes, this load verifies its own beside that entry, never in its place.
374
+ const cacheable = hit === undefined;
375
+ const created = {
376
+ abi,
377
+ bytes,
378
+ loaded: false,
379
+ handle: this.requestModuleLoad(bytes, abi, pin, metadata).then((handle) => this.cacheLoadedModule(cacheable ? cacheKey : null, created, handle), (error) => {
380
+ if (cacheable && this.moduleCache.get(cacheKey) === created)
381
+ this.moduleCache.delete(cacheKey);
382
+ throw error;
383
+ }),
384
+ };
385
+ if (cacheable) {
386
+ this.moduleCache.set(cacheKey, created);
387
+ this.trimModuleCache();
271
388
  }
272
- else {
273
- // Clamp-at-load: the worker checks the memory only after a guest call
274
- // returns, so a memory with no maximum let one onBar() take hundreds
275
- // of MB first. With the limit stamped as the maximum, the engine
276
- // refuses the growth inside the call (the guest traps). A refusal
277
- // throws here, before anything is cached, like the sha mismatch.
278
- const bounded = clampWrunModuleMemory(new Uint8Array(wasmBytes));
279
- // The module the worker instantiates exports every mutable global
280
- // under __wrun_g<index> so the live lane's snapshot/restore covers the
281
- // module's counters beside its memory (a compiler keeps top-level
282
- // scalars in globals; a memory-only restore left them post-row and a
283
- // same-bar or close-confirm re-evaluation then read stale state).
284
- // Identity (the sha pin above, the cache key) stays over the original
285
- // bytes; only the memory and export sections change. The rewriter is
286
- // the shared host's `prepareModuleBytes` (the same rewrite under every
287
- // ABI), loaded at the first compile and never on chart boot: this host
288
- // sits on the chart's startup graph through the driver registry, and a
289
- // viewer who never mounts an Indicator must not pay for host.js.
290
- const abi = wrunAbiVersion(metadata);
291
- const created = {
292
- compiled: false,
293
- module: wrunChartHostEnv()
294
- .loadSharedHost()
295
- .then(({ prepareModuleBytes }) => WebAssembly.compile(prepareModuleBytes(bounded, abi)))
296
- .then((module) => {
297
- created.compiled = true;
298
- this.trimModuleCache();
299
- return module;
300
- }, (error) => {
301
- if (this.moduleCache.get(digest) === created)
302
- this.moduleCache.delete(digest);
303
- throw error;
304
- }),
305
- };
306
- entry = created;
389
+ return created.handle;
390
+ }
391
+ /** A load answered: its entry leaves the key it waited under (an unpinned sheet's provisional key; none for a load
392
+ * that verified other bytes beside a cached entry) for the module's own key. A handle already loaded under that key
393
+ * stays the one every caller shares. */
394
+ cacheLoadedModule(cacheKey, entry, handle) {
395
+ if (cacheKey !== null && this.moduleCache.get(cacheKey) === entry)
396
+ this.moduleCache.delete(cacheKey);
397
+ const known = this.moduleCache.get(handle.key);
398
+ if (known !== undefined && known !== entry && known.loaded) {
399
+ this.moduleCache.delete(handle.key);
400
+ this.moduleCache.set(handle.key, known);
401
+ return known.handle;
307
402
  }
308
- this.moduleCache.set(digest, entry);
403
+ entry.loaded = true;
404
+ this.moduleCache.set(handle.key, entry);
309
405
  this.trimModuleCache();
310
- return entry.module;
406
+ return handle;
311
407
  }
312
- /** Evict compiled entries, least recently used first, until the cache is back at its capacity (a compile
313
- * in flight stays: its consumers share it). */
408
+ /** Post one `module-load` of the private bytes (copied, never transferred: the handle keeps them for its runs) and
409
+ * mint the handle from the worker's answer. */
410
+ requestModuleLoad(bytes, abi, pin, metadata) {
411
+ return new Promise((resolve, reject) => {
412
+ const request = {
413
+ kind: 'module-load',
414
+ id: ++this.requestSeq,
415
+ abi,
416
+ ...(pin !== undefined ? { sha256Pin: pin } : {}),
417
+ bytes,
418
+ };
419
+ this.post(request, [], {
420
+ kind: 'load',
421
+ // The package a compile that outlives its ceiling is held under, like a run's.
422
+ quarantineKey: wrunHostQuarantineKey(metadata),
423
+ overrideQuarantine: false,
424
+ reject,
425
+ settle: (response) => {
426
+ if (!response.ok) {
427
+ reject(wrunModuleLoadError(response, metadata));
428
+ }
429
+ else if (!('kind' in response)) {
430
+ reject(new Error(`WRUN ${metadata.id}: module load ${request.id} was answered as a run`));
431
+ }
432
+ else {
433
+ const handle = wrunModuleHandleOf(response, abi);
434
+ wrunModuleBytes.set(handle, bytes);
435
+ resolve(handle);
436
+ }
437
+ },
438
+ });
439
+ });
440
+ }
441
+ /** Evict loaded entries, least recently used first, until the cache is back at its capacity (a load in flight
442
+ * stays: its callers share it). */
314
443
  trimModuleCache() {
315
- for (const [digest, entry] of this.moduleCache) {
444
+ for (const [key, entry] of this.moduleCache) {
316
445
  if (this.moduleCache.size <= WRUN_MODULE_CACHE_CAPACITY)
317
446
  return;
318
- if (entry.compiled)
319
- this.moduleCache.delete(digest);
447
+ if (entry.loaded)
448
+ this.moduleCache.delete(key);
320
449
  }
321
450
  }
322
451
  async runSeries(input) {
@@ -333,11 +462,10 @@ export class WrunBrowserHost {
333
462
  const id = ++this.requestSeq;
334
463
  const request = {
335
464
  id,
336
- module: input.module,
337
465
  mode: input.mode ?? 'historical',
338
466
  ...packed,
339
467
  };
340
- const response = await this.dispatch(request, transfer, lane);
468
+ const response = await this.dispatchWithModule(request, transfer, lane, input.module);
341
469
  return this.unpack(response, input.metadata, input.rows);
342
470
  }
343
471
  /** Full run that also opens (or replaces) a live forming-bar session under
@@ -366,15 +494,14 @@ export class WrunBrowserHost {
366
494
  kind: 'live-start',
367
495
  sessionKey: input.sessionKey,
368
496
  id,
369
- module: input.module,
370
497
  mode: 'live',
371
498
  ...(input.epoch !== undefined ? { epoch: input.epoch } : {}),
372
499
  ...packed,
373
500
  };
374
- const response = await this.dispatch(request, transfer, {
501
+ const response = await this.dispatchWithModule(request, transfer, {
375
502
  ...lane,
376
503
  session: { key: input.sessionKey, opens: true },
377
- });
504
+ }, input.module);
378
505
  return this.unpack(response, input.metadata, input.rows);
379
506
  }
380
507
  /** One live tick: evaluate only `rows` (the new/revised forming-bar rows)
@@ -483,18 +610,105 @@ export class WrunBrowserHost {
483
610
  }
484
611
  return { quarantineKey, overrideQuarantine: overrideQuarantine === true };
485
612
  }
613
+ /** A full run or a live-start: the module rides the request, its key (the worker reuses the module it holds under
614
+ * it) and the host's private copy of its bytes (copied by structured clone, never transferred: a worker that does
615
+ * not hold the key, a respawned one or one that let it go, compiles them). The packed request's own `abi` stays
616
+ * the run's sheet's. */
617
+ dispatchWithModule(request, transfer, lane, module) {
618
+ return this.dispatch({ ...request, moduleKey: module.key, moduleBytes: wrunModuleBytes.get(module) ?? NO_MODULE_BYTES }, transfer, lane);
619
+ }
486
620
  dispatch(request, transfer, lane) {
621
+ return new Promise((resolve, reject) => {
622
+ this.post(request, transfer, {
623
+ ...lane,
624
+ kind: 'run',
625
+ reject,
626
+ settle: (response, entry) => this.settleRun(entry, response, resolve, reject),
627
+ });
628
+ });
629
+ }
630
+ /**
631
+ * Post one request under a pending entry: the respawn hold first (a held death refuses it, nothing posted), then
632
+ * the worker, the entry in its `start` phase with the start ceiling armed (the wait behind other requests, the
633
+ * module's compile and its instantiation, bounded as the dispatch clock bounded the hold before 0.6.0), then the
634
+ * post. A request the structured clone refuses fails alone (its entry and clock go with it).
635
+ */
636
+ post(request, transfer, init) {
487
637
  const held = this.respawnHold();
488
- if (held)
489
- return Promise.reject(held);
638
+ if (held) {
639
+ init.reject(held);
640
+ return;
641
+ }
490
642
  const worker = this.ensureWorker();
491
- return new Promise((resolve, reject) => {
492
- // A run that never answers means the guest is spinning; the worker is
493
- // poisoned and replaced so later runs start clean.
494
- const timer = setTimeout(() => this.poisonWorker('timeout', 'WRUN worker terminated after a timed-out run', request.id), WRUN_RUN_TIMEOUT_MS);
495
- this.pending.set(request.id, { ...lane, resolve, reject, timer });
643
+ const entry = { ...init, phase: 'start', runOrder: 0, timer: this.armClock(request.id) };
644
+ this.pending.set(request.id, entry);
645
+ try {
496
646
  worker.postMessage(request, transfer);
497
- });
647
+ }
648
+ catch (error) {
649
+ if (this.pending.get(request.id) === entry) {
650
+ this.pending.delete(request.id);
651
+ clearTimeout(entry.timer);
652
+ }
653
+ entry.reject(error instanceof Error ? error : new Error(String(error)));
654
+ }
655
+ }
656
+ /** A phase's clock: a request that outlives it means the worker is stuck (a guest spinning, a compile that never
657
+ * ends), so the worker is poisoned and replaced and later requests start clean. */
658
+ armClock(id) {
659
+ return setTimeout(() => this.poisonWorker('timeout', 'WRUN worker terminated after a timed-out run', id), WRUN_RUN_TIMEOUT_MS);
660
+ }
661
+ /** One answer from the worker. `running` moves its request to the `run` phase on a fresh clock (a second one, one
662
+ * for a load or for no pending request changes nothing); a terminal answer settles its request in either phase;
663
+ * an answer for no pending request (an untracked live-end's, a retired incarnation's) is dropped. */
664
+ receive(message) {
665
+ const entry = this.pending.get(message.id);
666
+ if (entry === undefined)
667
+ return;
668
+ if ('running' in message) {
669
+ if (entry.kind !== 'run' || entry.phase === 'run')
670
+ return;
671
+ // The module is instantiated and the run executes: its own deadline replaces the start ceiling, whatever the
672
+ // queue, the compile and the instantiation took.
673
+ clearTimeout(entry.timer);
674
+ entry.phase = 'run';
675
+ entry.runOrder = ++this.runSeq;
676
+ entry.timer = this.armClock(message.id);
677
+ return;
678
+ }
679
+ this.pending.delete(message.id);
680
+ clearTimeout(entry.timer);
681
+ entry.settle(message, entry);
682
+ }
683
+ /** A run's terminal answer: the package answered (an overridden quarantine is cleared by the success, and an
684
+ * opened session is one the worker now holds), a lost session, a live-order refusal, or a failure. */
685
+ settleRun(entry, response, resolve, reject) {
686
+ const { session } = entry;
687
+ if (response.ok) {
688
+ if ('kind' in response) {
689
+ reject(new Error(`WRUN request ${response.id} was answered as a module load`));
690
+ return;
691
+ }
692
+ if (entry.overrideQuarantine)
693
+ this.quarantines.delete(entry.quarantineKey);
694
+ if (session?.opens)
695
+ this.liveSessionKeys.add(session.key);
696
+ resolve(response);
697
+ }
698
+ else if (response.sessionLost) {
699
+ if (session)
700
+ this.liveSessionKeys.delete(session.key);
701
+ reject(new WrunLiveSessionLostError(response.error));
702
+ }
703
+ else if (response.code === 'live-order')
704
+ reject(new WrunLiveOrderError(response.error));
705
+ else {
706
+ // A failed tick drops its session in the worker; a failed start
707
+ // never replaces the session already open under its key.
708
+ if (session && !session.opens)
709
+ this.liveSessionKeys.delete(session.key);
710
+ reject(new Error(response.error));
711
+ }
498
712
  }
499
713
  ensureWorker() {
500
714
  if (this.worker)
@@ -506,41 +720,10 @@ export class WrunBrowserHost {
506
720
  // The host's engine port spawns the sandbox worker (web: the worker factory, with the worker script's URL and
507
721
  // the factory's failure source, both the app's), synchronously, as the host's own call did.
508
722
  this.worker = wrunChartHostEnv().engine.spawnWorker({
509
- // The sandbox worker posts no handshake: any message proves it up. No ready deadline: the run
510
- // timeout, the quarantine and the respawn window own this worker's liveness.
723
+ // The sandbox worker posts no handshake: any message proves it up. No ready deadline: the requests' clocks,
724
+ // the quarantine and the respawn window own this worker's liveness.
511
725
  readiness: { mode: 'first-message' },
512
- onMessage: (event) => {
513
- const response = event.data;
514
- const pending = this.pending.get(response.id);
515
- if (!pending)
516
- return;
517
- this.pending.delete(response.id);
518
- clearTimeout(pending.timer);
519
- const { session } = pending;
520
- if (response.ok) {
521
- // The package answered: an overridden quarantine is cleared by the
522
- // success, and an opened session is one the worker now holds.
523
- if (pending.overrideQuarantine)
524
- this.quarantines.delete(pending.quarantineKey);
525
- if (session?.opens)
526
- this.liveSessionKeys.add(session.key);
527
- pending.resolve(response);
528
- }
529
- else if (response.sessionLost) {
530
- if (session)
531
- this.liveSessionKeys.delete(session.key);
532
- pending.reject(new WrunLiveSessionLostError(response.error));
533
- }
534
- else if (response.code === 'live-order')
535
- pending.reject(new WrunLiveOrderError(response.error));
536
- else {
537
- // A failed tick drops its session in the worker; a failed start
538
- // never replaces the session already open under its key.
539
- if (session && !session.opens)
540
- this.liveSessionKeys.delete(session.key);
541
- pending.reject(new Error(response.error));
542
- }
543
- },
726
+ onMessage: (event) => this.receive(event.data),
544
727
  // A worker-level error (a script or module chunk that would not load, an
545
728
  // uncaught throw in the worker script) leaves the Worker unable to answer
546
729
  // anything: keep it installed and every later run would post into a void
@@ -556,20 +739,20 @@ export class WrunBrowserHost {
556
739
  }
557
740
  /**
558
741
  * The shared worker died: quarantine the package that was running (the
559
- * timed-out request's, or the oldest in flight when the error event fired, the
560
- * worker answers in dispatch order), terminate the worker, remember the
561
- * death for the respawn window, and reject every pending request with the
562
- * poison error naming the live sessions lost with the worker. Nothing in
563
- * flight means nothing to quarantine (a worker that dies idle is only a
742
+ * culprit, `culpritOf`), terminate the worker, remember the death for the
743
+ * respawn window, and reject every pending request (loads included) with
744
+ * the poison error naming the live sessions lost with the worker. Nothing
745
+ * in flight means nothing to quarantine (a worker that dies idle is only a
564
746
  * death for the window). `message` is what every casualty reads; the
565
- * timed-out request keeps its own deadline sentence. The death's context
566
- * (cause, the culprit's package and session, the budget a timeout used up)
567
- * is recorded here once, frozen, and rides every rejection of this death,
568
- * the respawn hold's included, so a casualty can name who held the sandbox.
747
+ * culprit of a timeout keeps its own deadline sentence. The death's
748
+ * context (cause, the culprit's package, session and phase, the budget a
749
+ * timeout used up) is recorded here once, frozen, and rides every
750
+ * rejection of this death, the respawn hold's included, so a casualty can
751
+ * name who held the sandbox.
569
752
  */
570
- poisonWorker(reason, message, culpritId) {
753
+ poisonWorker(reason, message, expiredId) {
571
754
  const now = Date.now();
572
- const culprit = culpritId !== undefined ? this.pending.get(culpritId) : this.pending.values().next().value;
755
+ const culprit = this.culpritOf(expiredId);
573
756
  if (culprit !== undefined)
574
757
  this.quarantine(culprit.quarantineKey, reason, now);
575
758
  const casualties = new Set(this.liveSessionKeys);
@@ -585,7 +768,9 @@ export class WrunBrowserHost {
585
768
  kind,
586
769
  ...(culprit !== undefined ? { quarantineKey: culprit.quarantineKey } : {}),
587
770
  ...(culprit?.session !== undefined ? { sessionKey: culprit.session.key } : {}),
588
- // The run clock starts at dispatch: the budget bounds the hold, not the execution.
771
+ ...(culprit !== undefined ? { phase: culprit.phase } : {}),
772
+ // A phase's clock (from the post for `start`, from `running` for `run`): the budget bounds the hold, not the
773
+ // execution.
589
774
  ...(kind === 'timeout' ? { heldMs: WRUN_RUN_TIMEOUT_MS } : {}),
590
775
  at: now,
591
776
  });
@@ -596,11 +781,30 @@ export class WrunBrowserHost {
596
781
  }
597
782
  for (const [id, entry] of this.pending) {
598
783
  clearTimeout(entry.timer);
599
- const own = reason === 'timeout' && id === culpritId ? `WRUN run ${id} timed out after ${WRUN_RUN_TIMEOUT_MS}ms` : message;
784
+ const own = reason === 'timeout' && entry === culprit
785
+ ? `WRUN ${entry.kind === 'load' ? 'module load' : 'run'} ${id} timed out after ${WRUN_RUN_TIMEOUT_MS}ms`
786
+ : message;
600
787
  entry.reject(wrunWorkerPoisonError(death, own));
601
788
  }
602
789
  this.pending.clear();
603
790
  }
791
+ /** Who held the worker when it died: the request in the `run` phase, the hog holding the worker's synchronous turn
792
+ * (the expired request itself when it was running, else the first that started running), else the expired
793
+ * request (nothing ran: its own wait and compile used its ceiling up), else, for an error event, the oldest
794
+ * request in flight. */
795
+ culpritOf(expiredId) {
796
+ const expired = expiredId !== undefined ? this.pending.get(expiredId) : undefined;
797
+ if (expired?.phase === 'run')
798
+ return expired;
799
+ let hog;
800
+ for (const entry of this.pending.values()) {
801
+ if (entry.phase === 'run' && (hog === undefined || entry.runOrder < hog.runOrder))
802
+ hog = entry;
803
+ }
804
+ if (hog !== undefined)
805
+ return hog;
806
+ return expiredId !== undefined ? expired : this.pending.values().next().value;
807
+ }
604
808
  /** Put (or keep) a package on the ladder: a death while its previous hold
605
809
  * runs, or inside the reset grace after it, is a repeat and doubles the
606
810
  * hold (capped); a later death starts over at the base hold. Records past
@@ -649,7 +853,3 @@ catch {
649
853
  export function __resetWrunBrowserHostGuardsForTests() {
650
854
  sharedHost?.resetGuardsForTests();
651
855
  }
652
- async function sha256Hex(bytes) {
653
- const digest = await crypto.subtle.digest('SHA-256', bytes);
654
- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
655
- }
@@ -119,6 +119,9 @@ export interface WrunTemplateSelf {
119
119
  }
120
120
  /** The sparkline's default window when a block declares no `bars`. */
121
121
  export declare const WRUN_SPARK_DEFAULT_BARS = 32;
122
+ /** `value` as written when a style reads it as a colour and nothing else (a hex, or a numeric rgb()/hsl() form),
123
+ * else undefined. The gate paintColor and every block view sink (WrunBlocks) share. */
124
+ export declare function wrunPaintColor(value: unknown): string | undefined;
122
125
  /** An output's display label: the declared `label`, else its name read as
123
126
  * words (the legend's own rule, wrunLegendName). */
124
127
  export declare function wrunOutputDisplayLabel(output: Pick<WrunMetadataOutput, 'name' | 'label'>): string;