@threadedstack/wmd-web 0.1.39 → 0.1.42

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 (57) hide show
  1. package/README.md +243 -1
  2. package/RELEASE.json +84 -49
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +231 -4
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +223 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +126 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +15 -2
  38. package/src/edge/sbx/cap.js +48 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +278 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/setup.js +9 -6
  54. package/src/host/chan-service.js +8 -5
  55. package/src/host/chan-services.js +29 -4
  56. package/src/host/edge-host.js +58 -3
  57. package/wmdpack.wasm +0 -0
@@ -0,0 +1,11 @@
1
+ // X25 gate 2b: the file-route round trips of a python run, counted by the runtime (edge/browser/src/fsroute.rs FSSTAT, ten u64 words):
2
+ // calls and microseconds in total, of `stat`, of `ctl`, of every other method; then the first call's start and the last call's end (microseconds, timeOrigin + now). The hub reads the table from the runtime's memory.
3
+
4
+ /** {n, us, stat, ctl, other} from the table at `addr` (8-aligned) of `buffer`, or null when there is none there. */
5
+ export function readFsStats(buffer, addr) {
6
+ if (!buffer || !addr || addr % 8 !== 0 || addr + 80 > buffer.byteLength) return null
7
+ const w = new BigUint64Array(buffer, addr, 10)
8
+ const v = i => Number(Atomics.load(w, i))
9
+ return { n: v(0), us: v(1), stat: { n: v(2), us: v(3) }, ctl: { n: v(4), us: v(5) }, other: { n: v(6), us: v(7) },
10
+ firstMs: v(8) ? v(8) / 1000 : null, lastMs: v(9) ? v(9) / 1000 : null }
11
+ }
@@ -11,6 +11,7 @@
11
11
  //
12
12
  // The runtime module and its glue are the build output of edge/browser (edge/browser/build.sh).
13
13
 
14
+ import { exitOfRun } from './exit-now.js'
14
15
  import { BIG_SHARE, payloadBytes } from './payload-size.js'
15
16
  import { WorkerPool } from './pool.js'
16
17
  import { serveFsCall } from './fs-bridge.js'
@@ -18,11 +19,24 @@ import { StdinPipe, setTtySize } from './stdio-pipe.js'
18
19
  import { capMemoryMax, pagesOfMiB } from './memcap.js'
19
20
  import { hasJspi } from './loader.js'
20
21
  import { withProc } from './procfs.js'
22
+ import { MarkBook } from './marks.js'
23
+ import { readFsStats } from './fs-stats.js'
21
24
 
22
25
  const NO_ROUTE = { handle: () => ({ error: { code: 'ENOSYS', message: 'this runtime has no file route' } }) }
23
26
 
24
27
  export { payloadBytes }
25
28
 
29
+ /**
30
+ * The options JSON a `run` message carries to the runtime (edge/browser/src/lib.rs `RunOpts`). `net` is true only when the caller asked: a runtime
31
+ * that gets no `net` has no network (every socket call is ENOTSUP, as before X5 net).
32
+ */
33
+ export function runOptionsJson({ fs, cwd, stdin, tty, children, exec, shim, net = false, jspi, argv0, fscache }) {
34
+ // fscache (X25 gate 2e): what the start keeps of the tree, a bit mask (1 listings, 2 stats); absent = the runtime's default
35
+ return JSON.stringify({ fs, cwd, stdin, tty, children, exec, shim, net: !!net, jspi, ...(argv0 ? { argv0 } : {}), ...(Number.isInteger(fscache) && fscache >= 0 ? { fscache } : {}) })
36
+ }
37
+
38
+ const sumCalls = (t) => Object.values(t || {}).reduce((s, v) => s + (parseInt(v, 10) || 0), 0)
39
+
26
40
  export class OwnRuntime {
27
41
  #opts
28
42
  #create
@@ -65,10 +79,23 @@ export class OwnRuntime {
65
79
  this.#create = this.#opts.create || ((url, o) => new Worker(url, o))
66
80
  const base = typeof location === 'undefined' ? undefined : location.href
67
81
  this.#glue = new URL(this.#opts.glueUrl, base).href
82
+ if (this.#opts.marks) this.#marks = new MarkBook()
68
83
  }
69
84
 
70
85
  // The route the program's file calls go to: /proc/self/stat and statm (procfs.js: the module's memory) in front of the page's route.
71
86
  #routeCache = null
87
+ // X5 default1 round 2 (B2.1): the Workers' marks of the program (own/marks.js), only with the option marks
88
+ #marks = null
89
+ #calls = null // X25 gate 2c item 2: the latest run's ring of the first runtime calls and the totals (edgeMarks=2)
90
+ get marks() {
91
+ if (!this.#marks) return null
92
+ const fs = this.#fsStat && this.#memory ? readFsStats(this.#memory.buffer, this.#fsStat) : null
93
+ const first = { ...this.#marks.first }
94
+ for (const [k, v] of Object.entries(this.#marks.last)) if (this.#marks.n[k] > 1) first[k + 'Last'] = v
95
+ if (fs && fs.firstMs) first.fsFirst = fs.firstMs
96
+ if (fs && fs.lastMs) first.fsLast = fs.lastMs
97
+ return { first, n: { ...this.#marks.n }, series: Object.fromEntries(Object.entries(this.#marks.all).filter(([k, v]) => v.length > 1).map(([k, v]) => [k, [...v]])), fs, memMiB: this.#memory ? Math.round(this.#memory.buffer.byteLength / 1048576) : null, ...(this.#calls ? { calls: this.#calls } : {}) }
98
+ }
72
99
  // one line for the route's ring (on the page, through the file route's `note` call: the frame's route is a port to the page, it has no ring of its own)
73
100
  // fix5 round 6: counters of the file calls of the Workers, off unless the frame's global __wmdFsTime is set (a Worker stamps t0 on the call; see worker.js)
74
101
  #fsT = globalThis.__wmdFsTime ? new Map() : null
@@ -122,16 +149,20 @@ export class OwnRuntime {
122
149
  this.#main.addEventListener('error', (e) => this.#fatal(new Error('runtime main worker: ' + (e.message || 'error'))))
123
150
  const ready = new Promise((resolve, reject) => (this.#booted = { resolve, reject }))
124
151
  this.#byScope.set(this.#scopes + 1, this.#main)
125
- this.#main.postMessage({ type: 'init', role: 'main', capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, fsTime: !!this.#fsT, glue: this.#glue, module: this.#module, stack })
152
+ this.#main.postMessage({ type: 'init', role: 'main', capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...(this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}), fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, glue: this.#glue, ...(this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}), module: this.#module, stack })
126
153
  const up = await ready
127
154
  this.#memory = up.memory
128
155
  this.#stdin = new StdinPipe(this.#memory, up.stdin)
129
156
  this.#ttyAddr = up.tty
130
157
  this.#pool = new WorkerPool({
131
158
  create: () => this.#create(workerUrl, { type: 'module', name: 'wmd-own-thread' }),
132
- init: (w) => (this.#byScope.set(this.#scopes + 1, w), w.postMessage({ type: 'init', role: 'thread', capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, fsTime: !!this.#fsT, trace: this.#opts.trace | 0, glue: this.#glue, module: this.#module, memory: this.#memory, stack })),
159
+ init: (w) => (this.#byScope.set(this.#scopes + 1, w), w.postMessage({ type: 'init', role: 'thread', capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...(this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}), fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, trace: this.#opts.trace | 0, glue: this.#glue, ...(this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}), module: this.#module, memory: this.#memory, stack })),
133
160
  spare: this.#opts.spare,
134
161
  max: this.#opts.max,
162
+ idleMs: this.#opts.poolIdleMs | 0,
163
+ onRetire: (_id, w) => {
164
+ for (const [k, v] of this.#byScope) if (v === w) this.#byScope.delete(k)
165
+ },
135
166
  onMessage: (_id, data) => this.#fromWorker(data),
136
167
  onFailure: (_id, tasks, err) => {
137
168
  // a Worker that trapped or failed (a thread that stops without a word is found by this line in the route's ring)
@@ -147,27 +178,68 @@ export class OwnRuntime {
147
178
  // stdin 'pipe' (writeStdin and closeStdin feed it) or 'null' (end of input at once; the default)
148
179
  // children true: a file that is not wasm is run by the page's ChildHost (child-host.js, through the file route's child_* methods)
149
180
  // exec the program's own path as it knows it (process.execPath): a spawn of it runs the same module again in this runtime
181
+ // net X5 net: true gives the program the container's network: its sockets are `net_*` calls on the file route (net-host.js)
150
182
  // shim true: that child gets --require /.wmd-edge/linux.cjs
183
+ // argv0 X25 gate 1: the program's name as it sees it (CPython finds its prefix from it); default "main"
151
184
  // tty { in, out, err, cols, rows }: which of the three are terminals (the others are pipes) and the terminal's size
152
185
  // The file system is the page's file route (option fsRoute of start()): the program's root is that route's tree.
153
- run({ program, args = [], env = [], node = false, cwd, stdin = 'null', tty = {}, children = false, exec, shim = false }) {
186
+ // ready X5 default1 round 2 (B2.1): the program made ready by OwnRuntime.prepare (capped bytes, their sha256 and the compiled module): node only;
187
+ // the runtime compiles and hashes nothing and the bytes are not copied here (a kept frame hands the same ones to each start)
188
+ run({ program, ready = null, args = [], env = [], node = false, cwd, stdin = 'null', tty = {}, children = false, exec, shim = false, net = false, argv0, fscache }) {
154
189
  if (this.#dead) return Promise.reject(new Error('runtime terminated'))
155
190
  const id = this.#nextRun++
156
- let buf = program instanceof ArrayBuffer ? program.slice(0) : program.buffer.slice(program.byteOffset, program.byteOffset + program.byteLength)
157
- // the declared maximum of the program's memory is capped (memcap.js): WebKit reserves it when the memory is made
158
- if (this.#opts.memoryMaxMiB) {
159
- const cap = capMemoryMax(new Uint8Array(buf), pagesOfMiB(this.#opts.memoryMaxMiB))
160
- this.memoryCap = { before: cap.before, after: cap.after }
161
- if (cap.bytes.buffer !== buf) buf = cap.bytes.buffer
191
+ let buf = null
192
+ if (ready) {
193
+ this.memoryCap = ready.cap
194
+ } else {
195
+ buf = program instanceof ArrayBuffer ? program.slice(0) : program.buffer.slice(program.byteOffset, program.byteOffset + program.byteLength)
196
+ // the declared maximum of the program's memory is capped (memcap.js): WebKit reserves it when the memory is made
197
+ if (this.#opts.memoryMaxMiB) {
198
+ const cap = capMemoryMax(new Uint8Array(buf), pagesOfMiB(this.#opts.memoryMaxMiB))
199
+ this.memoryCap = { before: cap.before, after: cap.after }
200
+ if (cap.bytes.buffer !== buf) buf = cap.bytes.buffer
201
+ }
162
202
  }
163
203
  return new Promise((resolve, reject) => {
164
204
  this.#runs.set(id, { resolve, reject })
165
- const opts = JSON.stringify({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, jspi: hasJspi() })
205
+ const opts = runOptionsJson({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, net, jspi: hasJspi(), argv0, fscache })
166
206
  if (tty.cols || tty.rows) setTtySize(this.#memory, this.#ttyAddr, tty.cols || 80, tty.rows || 24)
167
- this.#main.postMessage({ type: 'run', id, program: buf, args, env, node, opts }, [buf])
207
+ this.#calls = null // the run's ring is the biggest one of its Workers (worker.js posts one per task)
208
+ if (ready) this.#main.postMessage({ type: 'run', id, program: ready.bytes, module: ready.module, hash: ready.hash, args, env, node, opts })
209
+ else this.#main.postMessage({ type: 'run', id, program: buf, args, env, node, opts }, [buf])
168
210
  })
169
211
  }
170
212
 
213
+ /**
214
+ * X5 default1 round 2 (B2.1): a program made ready to run once and kept (by the frame, for the next starts): its bytes with the memory's maximum
215
+ * capped as run() caps it (memoryMaxMiB, default 1024), copied into a SharedArrayBuffer when the page may make one (posting it to a Worker then
216
+ * copies nothing), the sha256 of those bytes, and the compiled module. -> {bytes, hash, module, cap, memoryMaxMiB}
217
+ */
218
+ static async prepare(program, { memoryMaxMiB = 1024, compile = (b) => WebAssembly.compile(b), digest = (b) => crypto.subtle.digest('SHA-256', b) } = {}) {
219
+ let bytes = program instanceof Uint8Array ? program : new Uint8Array(program)
220
+ let cap = { before: null, after: null }
221
+ if (memoryMaxMiB) {
222
+ const c = capMemoryMax(bytes, pagesOfMiB(memoryMaxMiB))
223
+ cap = { before: c.before, after: c.after }
224
+ bytes = c.bytes
225
+ }
226
+ // the digest and the compile read the plain bytes (an engine may refuse a shared view), both at once
227
+ const plain = typeof SharedArrayBuffer === 'function' && bytes.buffer instanceof SharedArrayBuffer ? bytes.slice() : bytes
228
+ const [hash, module] = await Promise.all([digest(plain), compile(plain)])
229
+ // (not decided by `crossOriginIsolated`: a Worker made from a data: URL says false in WebKit although its frame is isolated and it makes shared memory
230
+ // like any other; the bytes then stayed plain and every post of them copied the program, 59 MB for each start of node. The constructor says if it can.)
231
+ if (typeof SharedArrayBuffer === 'function' && !(bytes.buffer instanceof SharedArrayBuffer)) {
232
+ try {
233
+ const shared = new Uint8Array(new SharedArrayBuffer(bytes.length))
234
+ shared.set(bytes)
235
+ bytes = shared
236
+ } catch {
237
+ // no shared memory here: the bytes stay as they are
238
+ }
239
+ }
240
+ return { bytes, hash: new Uint8Array(hash), module, cap, memoryMaxMiB }
241
+ }
242
+
171
243
  /** Input for the program's standard input (bytes). Held and fed as the program reads: the ring is 256 KiB. */
172
244
  writeStdin(bytes) {
173
245
  this.#stdin.write(bytes)
@@ -216,6 +288,12 @@ export class OwnRuntime {
216
288
  })
217
289
  }
218
290
 
291
+ #forged = 0
292
+ /** How many messages of the Workers were of no known kind (dropped, X5 fix3p P3). */
293
+ get forged() {
294
+ return this.#forged
295
+ }
296
+
219
297
  /** Counters of the threads' messages (see #capi). */
220
298
  get capiStats() {
221
299
  return { ...this.#capiN }
@@ -296,6 +374,10 @@ export class OwnRuntime {
296
374
  }
297
375
  }
298
376
 
377
+ #fsStat = 0 // address of the runtime's table of file-route round trips (python runs, fs-stats.js), 0 until it says
378
+ #sigWake = 0 // address in the runtime's memory of the word that wakes the signal thread, 0 until the program registers a flag
379
+ #sigFlags = [] // X25 gate 2: {words, at, bits} the program registered (CPython's eval breaker), see 'sigflag'
380
+
299
381
  get workerCount() {
300
382
  return this.#dead ? 0 : 1 + (this.#pool ? this.#pool.live : 0)
301
383
  }
@@ -307,6 +389,12 @@ export class OwnRuntime {
307
389
  signal(n) {
308
390
  if (n === 9) return this.terminate()
309
391
  this.#opts.fsRoute?.queueSignal?.(0, n)
392
+ if (this.#sigWake && this.#memory) {
393
+ // the signal thread of a program that registered a flag (python): one more on its word, and wake it
394
+ const w = new Int32Array(this.#memory.buffer)
395
+ Atomics.add(w, this.#sigWake >> 2, 1)
396
+ Atomics.notify(w, this.#sigWake >> 2)
397
+ }
310
398
  }
311
399
 
312
400
  terminate() {
@@ -330,6 +418,12 @@ export class OwnRuntime {
330
418
  case 'spawn':
331
419
  this.#spawn(data)
332
420
  break
421
+ case 'mark':
422
+ if (this.#marks) this.#marks.add(data.name, data.t)
423
+ break
424
+ case 'calls':
425
+ if (this.#marks && (!this.#calls || sumCalls(data.totals) >= sumCalls(this.#calls.totals))) this.#calls = { seen: data.seen, wrapped: data.wrapped, ring: data.ring, totals: data.totals, inst: data.inst }
426
+ break
333
427
  case 'counts': {
334
428
  const w = this.#countWait.get(data.seq)
335
429
  if (w) {
@@ -367,23 +461,40 @@ export class OwnRuntime {
367
461
  this.#opts.onLog({ type: 'log', text: 'fs call failed: ' + (e && e.message) })
368
462
  })
369
463
  break
464
+ case 'fsstat':
465
+ if (Number.isInteger(data.addr)) this.#fsStat = data.addr
466
+ break
467
+ case 'sigflag':
468
+ // X25 gate 2: the program (CPython) registered a flag word; it is set when the runtime has queued a signal (sigraise)
469
+ if (data.wake) this.#sigWake = data.wake // the word the runtime's signal thread waits on (edge/browser pysignal.rs)
470
+ if (data.buffer && data.buffer.byteLength >= data.addr + 4 && data.addr % 4 === 0) this.#sigFlags.push({ words: new Int32Array(data.buffer), at: data.addr >> 2, bits: data.bits | 0 })
471
+ break
472
+ case 'sigraise':
473
+ for (const f of this.#sigFlags) Atomics.or(f.words, f.at, f.bits)
474
+ break
370
475
  case 'note': {
371
476
  // a line from the runtime's own code (child spawning, fix round 5): kept in the route's ring
372
477
  this.#note(String(data.text))
373
478
  break
374
479
  }
375
480
  case 'exit':
376
- case 'run-error':
481
+ case 'run-error': {
377
482
  // Output of other threads may still be on its way (Workers' messages have no common order): hold the end of
378
483
  // the run until as many outputs arrived as were sent.
379
- this.#held.push(data)
484
+ // X5 net round 2: an exit from a thread Worker (process.exit in the program's JavaScript, exit-now.js) has no run id: the run waiting is the one
485
+ const end = exitOfRun(data, this.#runs)
486
+ if (end) this.#held.push(end)
380
487
  this.#release()
381
488
  break
489
+ }
382
490
  case 'fatal':
383
491
  this.#fatal(new Error(data.error))
384
492
  break
385
493
  default:
386
- this.#opts.onLog(data)
494
+ // X5 fix3p P3: the Workers run the container's code, which can post any message. One that is none of the kinds above is not the runtime's:
495
+ // it is dropped and counted (forged, adapter stats(), the bridge's forgedMessages), never handed to onLog as if it were the runtime's log.
496
+ // The runtime's own log lines are made here (#refuse, the file calls) and reach onLog directly.
497
+ this.#forged++
387
498
  }
388
499
  }
389
500
 
@@ -403,6 +514,7 @@ export class OwnRuntime {
403
514
  // A thread asks for a Worker for a job. The message is forwarded unread: it carries the module and the shared
404
515
  // memory (structured clone) and the address of the job.
405
516
  #spawn(data) {
517
+ if (this.#marks) this.#marks.add('spawnReq', performance.timeOrigin + performance.now())
406
518
  if (this.#opts.debug) console.log('[hub] spawn request, ack', data.ack, 'pool', JSON.stringify({ live: this.#pool.live, idle: this.#pool.idle, busy: this.#pool.busy, starting: this.#pool.starting }))
407
519
  try {
408
520
  this.#pool.dispatch({ type: 'task', msg: data.msg, ack: data.ack })
@@ -67,8 +67,9 @@ function suspendingImports(turn, run) {
67
67
  })
68
68
  }
69
69
 
70
- export async function loadRuntime({ glue, module, memory, stack, debug = false, importer = u => import(u), jspi = hasJspi(), role = 'main' }) {
71
- const g = await importer(glue)
70
+ export async function loadRuntime({ glue, glueScript, module, memory, stack, debug = false, importer = u => import(u), jspi = hasJspi(), role = 'main' }) {
71
+ // glueScript (the data form): the glue as an expression, evaluated under a short source name (a module of a long data: URL puts that URL in every Error stack)
72
+ const g = glueScript ? (0, eval)(glueScript + '\n//# sourceURL=wmd-glue.js') : await importer(glue)
72
73
  const init = () => g.default({ module_or_path: module, memory, thread_stack_size: stack })
73
74
  // A thread Worker runs its jobs through WebAssembly.promising (worker.js) so the program's main context can wait for the
74
75
  // engine's event loop (Edge.js's event-loop checkpoint is a suspension); it needs the turn import suspending.
@@ -0,0 +1,158 @@
1
+ // X5 default1 round 2 (B2.1): marks of one node start, off unless the page option edgeMarks=1 asks. Every Worker of the runtime that has them on
2
+ // posts {type: 'mark', name, t} to the hub (hub.js) for the WebAssembly objects of the program: the compile of the program's module (a Module
3
+ // made of PROGRAM_BYTES or more), and each instance of a WASIX program. t is on the clock every Worker shares (timeOrigin + now).
4
+ // The hub keeps the first time of each name and how many came (marks()), the adapter turns them into stages (adapter.js).
5
+
6
+ export const PROGRAM_BYTES = 8 << 20
7
+ export const at = () => performance.timeOrigin + performance.now()
8
+
9
+ const sizeOf = (b) => (b && typeof b.byteLength === 'number' ? b.byteLength : 0)
10
+ // a WASIX program's import object: the runtime's own module (wasm-bindgen's glue) has none of these
11
+ const isProgram = (imports) => !!(imports && (imports.wasix_32v1 || imports.wasix_64v1 || imports.wasi_snapshot_preview1 || imports.wasi_unstable))
12
+
13
+ // X25 gate 2c item 2: the first CALL_RING calls of the program's first instance into the runtime (its WASIX imports), off unless asked
14
+ export const CALL_RING = 400
15
+ const PUSH_EVERY = 64
16
+ const WASIX = ['wasix_32v1', 'wasix_64v1', 'wasi_snapshot_preview1', 'wasi_unstable']
17
+
18
+ class CallLog {
19
+ ring = [] // [name, ms since the instance was made, microseconds inside the call]; the snapshot has them as one string each
20
+ totals = {} // name -> [calls, microseconds inside]; the snapshot has them as "calls us"
21
+ n = 0
22
+ t0 = performance.now()
23
+ // the Worker that makes the instance may be ended at the program's exit before it can send a last message: every PUSH_EVERY calls (and at the ring's last call) the state goes out
24
+ post = null
25
+ wrap(name, f) {
26
+ const log = this
27
+ return function (...a) {
28
+ const t = performance.now()
29
+ try {
30
+ return f.apply(this, a)
31
+ } finally {
32
+ const us = (performance.now() - t) * 1000
33
+ const e = (log.totals[name] ||= [0, 0])
34
+ e[0]++
35
+ e[1] += us
36
+ if (log.ring.length < CALL_RING) log.ring.push([name, Math.round((t - log.t0) * 1000) / 1000, Math.round(us)])
37
+ if (log.post && (++log.n % PUSH_EVERY === 0 || log.ring.length === CALL_RING)) log.post(log.snapshot())
38
+ }
39
+ }
40
+ }
41
+ wrapImports(imports) {
42
+ const out = { ...imports }
43
+ this.wrapped = {}
44
+ for (const ns of WASIX) {
45
+ if (!imports[ns]) continue
46
+ this.wrapped[ns] = Object.keys(imports[ns]).length
47
+ out[ns] = Object.fromEntries(Object.entries(imports[ns]).map(([k, v]) => [k, typeof v === 'function' ? this.wrap(k, v) : v]))
48
+ }
49
+ return out
50
+ }
51
+ reset() {
52
+ this.ring = []
53
+ this.totals = {}
54
+ this.n = 0
55
+ this.taken = false
56
+ }
57
+ // each call of the ring as one string "name startMs us" (the harness's page.evaluate nulls arrays nested this deep)
58
+ snapshot() {
59
+ return { inst: (this.g && this.g.__wmdInst ? this.g.__wmdInst : []).map((p) => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`), seen: this.seen || 0, taken: !!this.taken, wrapped: this.wrapped || null, ring: this.ring.map((r) => r.join(' ')), totals: Object.fromEntries(Object.entries(this.totals).map(([k, v]) => [k, `${v[0]} ${Math.round(v[1])}`])) }
60
+ }
61
+ }
62
+
63
+ /** Wraps the constructors of WebAssembly.Module and WebAssembly.Instance of `g` (Proxies, so the objects stay the engine's own).
64
+ * With `{ calls: true }` the WASIX imports of the first program instance are wrapped and the returned object's `snapshot()` gives the ring and the totals. */
65
+ export function installMarks(g, post, opts = {}) {
66
+ const W = g.WebAssembly
67
+ if (!W || W.__wmdMarks) return W && W.__wmdMarks
68
+ const calls = opts.calls ? new CallLog() : null
69
+ if (calls && opts.postCalls) calls.post = opts.postCalls
70
+ // X25 gate 2d: the runtime appends [JS instantiate ms, exports step ms] of each instance it makes to this array (patched wasmer js backend)
71
+ if (calls) ((g.__wmdInst = []), (calls.g = g))
72
+ const Mod = W.Module
73
+ const Inst = W.Instance
74
+ W.Module = new Proxy(Mod, {
75
+ construct(T, a, nt) {
76
+ const big = sizeOf(a[0]) >= PROGRAM_BYTES
77
+ const t0 = at()
78
+ const m = Reflect.construct(T, a, nt)
79
+ if (big) (post('compile0', t0), post('compile1', at()))
80
+ return m
81
+ },
82
+ })
83
+ W.Instance = new Proxy(Inst, {
84
+ construct(T, a, nt) {
85
+ const prog = isProgram(a[1])
86
+ const t0 = at()
87
+ if (prog && calls) calls.seen = (calls.seen || 0) + 1
88
+ let args = a
89
+ if (prog && calls && !calls.taken) ((calls.taken = true), (args = [a[0], calls.wrapImports(a[1]), ...a.slice(2)]))
90
+ const i = Reflect.construct(T, args, nt)
91
+ if (prog && calls && args !== a) calls.t0 = performance.now()
92
+ if (prog) (post('inst0', t0), post('inst1', at()))
93
+ return i
94
+ },
95
+ })
96
+ const compile = W.compile
97
+ W.compile = function (b, ...rest) {
98
+ const big = sizeOf(b) >= PROGRAM_BYTES
99
+ const t0 = at()
100
+ const p = compile.call(this, b, ...rest)
101
+ if (big) (post('acompile0', t0), p.then(() => post('acompile1', at()), () => {}))
102
+ return p
103
+ }
104
+ W.__wmdMarks = calls || true
105
+ return calls
106
+ }
107
+
108
+ /** The hub's side: first time of each mark and how many came. */
109
+ export class MarkBook {
110
+ first = {}
111
+ last = {} // the latest time of each name (X25 gate 2b: the Workers of one start come one after the other)
112
+ n = {}
113
+ all = {} // every time of a name, in order, at most 64 (X25 gate 2b: the series of the thread starts)
114
+ add(name, t) {
115
+ if (typeof name !== 'string' || typeof t !== 'number') return
116
+ if (this.first[name] === undefined) this.first[name] = t
117
+ if (this.last[name] === undefined || t > this.last[name]) this.last[name] = t
118
+ this.n[name] = (this.n[name] || 0) + 1
119
+ const a = (this.all[name] ||= [])
120
+ if (a.length < 64) a.push(t)
121
+ }
122
+ }
123
+
124
+ // The stages of a start out of its marks (milliseconds; a stage whose two ends are not both there is left out):
125
+ // fwLoad the frame made the Worker until its script ran check HASHES.txt, the runtime's files fetched, hashed and compiled
126
+ // rtCompile the runtime's wasm compiled (a part of check) program the program's bytes fetched (or taken from the kept frame)
127
+ // shim the shim written to the route boot OwnRuntime.start: the main Worker and the pool
128
+ // toMain run posted until the main Worker had it compile the program's module compiled (inside the runtime)
129
+ // toInst compiled until its first instance began inst the first instance made
130
+ // toOut instance made until the first output of the program tail first output (or the instance) until the run's end came to the frame's Worker
131
+ // exitHop the main Worker's exit until the frame's Worker had it (a part of tail)
132
+ export const STAGES = [
133
+ ['fwLoad', 'frame', 'fw'],
134
+ ['check', 'load0', 'checked'],
135
+ ['rtCompile', 'rtc0', 'rtc1'],
136
+ ['program', 'start0', 'program'],
137
+ ['shim', 'program', 'shim'],
138
+ ['boot', 'shim', 'booted'],
139
+ ['toMain', 'runPost', 'runRecv'],
140
+ ['compile', 'compile0', 'compile1'],
141
+ ['toInst', 'compile1', 'inst0'],
142
+ ['inst', 'inst0', 'inst1'],
143
+ ['toOut', 'inst1', 'firstOut'],
144
+ ['tail', ['firstOut', 'inst1'], 'exitRecv'],
145
+ ['exitHop', 'exitPost', 'exitRecv'],
146
+ ['run', 'runPost', 'exitRecv'],
147
+ ]
148
+
149
+ export function stagesOf(m) {
150
+ const pick = (k) => (Array.isArray(k) ? k.map((x) => m[x]).find((v) => typeof v === 'number') : m[k])
151
+ const out = {}
152
+ for (const [name, a, b] of STAGES) {
153
+ const x = pick(a)
154
+ const y = pick(b)
155
+ if (typeof x === 'number' && typeof y === 'number') out[name] = Math.round((y - x) * 10) / 10
156
+ }
157
+ return out
158
+ }