@threadedstack/wmd-web 0.1.38 → 0.1.41
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.
- package/README.md +239 -2
- package/RELEASE.json +97 -53
- package/guest/arm64/Image +1 -1
- package/guest/arm64/Image-4k +1 -1
- package/guest/arm64/initramfs.cpio.gz +0 -0
- package/package.json +3 -3
- package/src/boot.js +321 -12
- package/src/edge/auto.js +77 -0
- package/src/edge/base.js +10 -0
- package/src/edge/bridge.js +76 -7
- package/src/edge/ctl.js +21 -4
- package/src/edge/error-kind.js +6 -0
- package/src/edge/frame-code.gen.js +6 -0
- package/src/edge/frame.js +58 -15
- package/src/edge/msg.js +3 -0
- package/src/edge/own/adapter.js +208 -19
- package/src/edge/own/exit-now.js +62 -0
- package/src/edge/own/fs-own-route.js +40 -3
- package/src/edge/own/fs-stats.js +11 -0
- package/src/edge/own/hub.js +125 -14
- package/src/edge/own/loader.js +3 -2
- package/src/edge/own/marks.js +158 -0
- package/src/edge/own/net-host.js +873 -0
- package/src/edge/own/node-globals.js +142 -0
- package/src/edge/own/pool.js +30 -1
- package/src/edge/own/service-receiver.js +7 -1
- package/src/edge/own/shim-post.js +38 -0
- package/src/edge/own/worker.js +34 -1
- package/src/edge/page.js +448 -25
- package/src/edge/pins.gen.js +17 -0
- package/src/edge/pins.js +21 -0
- package/src/edge/plan.js +45 -9
- package/src/edge/python-module.js +18 -0
- package/src/edge/python-pins.js +64 -0
- package/src/edge/python-plan.js +280 -0
- package/src/edge/python-source.js +34 -0
- package/src/edge/runtime.js +13 -2
- package/src/edge/sbx/cap.js +36 -0
- package/src/edge/sbx/common.js +186 -0
- package/src/edge/sbx/doc.js +121 -0
- package/src/edge/sbx/files.js +112 -0
- package/src/edge/sbx/frame.js +126 -0
- package/src/edge/sbx/gate.js +115 -0
- package/src/edge/sbx/sha256.js +68 -0
- package/src/edge/sbx/worker-entry.js +36 -0
- package/src/edge/sems.js +113 -0
- package/src/edge/service-host.js +57 -5
- package/src/edge/service-port.js +79 -5
- package/src/edge/setup.js +275 -0
- package/src/edge/shim.js +3 -1
- package/src/edge/watch.js +101 -0
- package/src/edge/worker.js +31 -2
- package/src/gowasm/boot-setup.js +175 -0
- package/src/gowasm/make-pins-module.mjs +35 -0
- package/src/gowasm/pins-data.js +162 -0
- package/src/gowasm/setup.js +167 -0
- package/src/gowasm/twin-fetch.js +27 -0
- package/src/host/chan-service.js +33 -6
- package/src/host/chan-services.js +29 -4
- package/src/host/ckpt.js +78 -0
- package/src/host/csp-reason.js +64 -0
- package/src/host/ctl.js +30 -8
- package/src/host/edge-go.js +94 -4
- package/src/host/edge-host.js +58 -3
- package/src/host/gowasm-guard.js +11 -1
- package/src/host/gowasm-worker.js +90 -35
- package/src/host/pinned-fetch.js +436 -0
- package/wmdpack.wasm +0 -0
package/src/edge/own/hub.js
CHANGED
|
@@ -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,23 @@ 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 }) {
|
|
34
|
+
return JSON.stringify({ fs, cwd, stdin, tty, children, exec, shim, net: !!net, jspi, ...(argv0 ? { argv0 } : {}) })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const sumCalls = (t) => Object.values(t || {}).reduce((s, v) => s + (parseInt(v, 10) || 0), 0)
|
|
38
|
+
|
|
26
39
|
export class OwnRuntime {
|
|
27
40
|
#opts
|
|
28
41
|
#create
|
|
@@ -65,10 +78,23 @@ export class OwnRuntime {
|
|
|
65
78
|
this.#create = this.#opts.create || ((url, o) => new Worker(url, o))
|
|
66
79
|
const base = typeof location === 'undefined' ? undefined : location.href
|
|
67
80
|
this.#glue = new URL(this.#opts.glueUrl, base).href
|
|
81
|
+
if (this.#opts.marks) this.#marks = new MarkBook()
|
|
68
82
|
}
|
|
69
83
|
|
|
70
84
|
// 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
85
|
#routeCache = null
|
|
86
|
+
// X5 default1 round 2 (B2.1): the Workers' marks of the program (own/marks.js), only with the option marks
|
|
87
|
+
#marks = null
|
|
88
|
+
#calls = null // X25 gate 2c item 2: the latest run's ring of the first runtime calls and the totals (edgeMarks=2)
|
|
89
|
+
get marks() {
|
|
90
|
+
if (!this.#marks) return null
|
|
91
|
+
const fs = this.#fsStat && this.#memory ? readFsStats(this.#memory.buffer, this.#fsStat) : null
|
|
92
|
+
const first = { ...this.#marks.first }
|
|
93
|
+
for (const [k, v] of Object.entries(this.#marks.last)) if (this.#marks.n[k] > 1) first[k + 'Last'] = v
|
|
94
|
+
if (fs && fs.firstMs) first.fsFirst = fs.firstMs
|
|
95
|
+
if (fs && fs.lastMs) first.fsLast = fs.lastMs
|
|
96
|
+
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 } : {}) }
|
|
97
|
+
}
|
|
72
98
|
// 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
99
|
// 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
100
|
#fsT = globalThis.__wmdFsTime ? new Map() : null
|
|
@@ -122,16 +148,20 @@ export class OwnRuntime {
|
|
|
122
148
|
this.#main.addEventListener('error', (e) => this.#fatal(new Error('runtime main worker: ' + (e.message || 'error'))))
|
|
123
149
|
const ready = new Promise((resolve, reject) => (this.#booted = { resolve, reject }))
|
|
124
150
|
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 })
|
|
151
|
+
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
152
|
const up = await ready
|
|
127
153
|
this.#memory = up.memory
|
|
128
154
|
this.#stdin = new StdinPipe(this.#memory, up.stdin)
|
|
129
155
|
this.#ttyAddr = up.tty
|
|
130
156
|
this.#pool = new WorkerPool({
|
|
131
157
|
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 })),
|
|
158
|
+
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
159
|
spare: this.#opts.spare,
|
|
134
160
|
max: this.#opts.max,
|
|
161
|
+
idleMs: this.#opts.poolIdleMs | 0,
|
|
162
|
+
onRetire: (_id, w) => {
|
|
163
|
+
for (const [k, v] of this.#byScope) if (v === w) this.#byScope.delete(k)
|
|
164
|
+
},
|
|
135
165
|
onMessage: (_id, data) => this.#fromWorker(data),
|
|
136
166
|
onFailure: (_id, tasks, err) => {
|
|
137
167
|
// 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 +177,68 @@ export class OwnRuntime {
|
|
|
147
177
|
// stdin 'pipe' (writeStdin and closeStdin feed it) or 'null' (end of input at once; the default)
|
|
148
178
|
// 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
179
|
// exec the program's own path as it knows it (process.execPath): a spawn of it runs the same module again in this runtime
|
|
180
|
+
// net X5 net: true gives the program the container's network: its sockets are `net_*` calls on the file route (net-host.js)
|
|
150
181
|
// shim true: that child gets --require /.wmd-edge/linux.cjs
|
|
182
|
+
// argv0 X25 gate 1: the program's name as it sees it (CPython finds its prefix from it); default "main"
|
|
151
183
|
// tty { in, out, err, cols, rows }: which of the three are terminals (the others are pipes) and the terminal's size
|
|
152
184
|
// The file system is the page's file route (option fsRoute of start()): the program's root is that route's tree.
|
|
153
|
-
|
|
185
|
+
// ready X5 default1 round 2 (B2.1): the program made ready by OwnRuntime.prepare (capped bytes, their sha256 and the compiled module): node only;
|
|
186
|
+
// the runtime compiles and hashes nothing and the bytes are not copied here (a kept frame hands the same ones to each start)
|
|
187
|
+
run({ program, ready = null, args = [], env = [], node = false, cwd, stdin = 'null', tty = {}, children = false, exec, shim = false, net = false, argv0 }) {
|
|
154
188
|
if (this.#dead) return Promise.reject(new Error('runtime terminated'))
|
|
155
189
|
const id = this.#nextRun++
|
|
156
|
-
let buf =
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
190
|
+
let buf = null
|
|
191
|
+
if (ready) {
|
|
192
|
+
this.memoryCap = ready.cap
|
|
193
|
+
} else {
|
|
194
|
+
buf = program instanceof ArrayBuffer ? program.slice(0) : program.buffer.slice(program.byteOffset, program.byteOffset + program.byteLength)
|
|
195
|
+
// the declared maximum of the program's memory is capped (memcap.js): WebKit reserves it when the memory is made
|
|
196
|
+
if (this.#opts.memoryMaxMiB) {
|
|
197
|
+
const cap = capMemoryMax(new Uint8Array(buf), pagesOfMiB(this.#opts.memoryMaxMiB))
|
|
198
|
+
this.memoryCap = { before: cap.before, after: cap.after }
|
|
199
|
+
if (cap.bytes.buffer !== buf) buf = cap.bytes.buffer
|
|
200
|
+
}
|
|
162
201
|
}
|
|
163
202
|
return new Promise((resolve, reject) => {
|
|
164
203
|
this.#runs.set(id, { resolve, reject })
|
|
165
|
-
const opts =
|
|
204
|
+
const opts = runOptionsJson({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, net, jspi: hasJspi(), argv0 })
|
|
166
205
|
if (tty.cols || tty.rows) setTtySize(this.#memory, this.#ttyAddr, tty.cols || 80, tty.rows || 24)
|
|
167
|
-
this.#
|
|
206
|
+
this.#calls = null // the run's ring is the biggest one of its Workers (worker.js posts one per task)
|
|
207
|
+
if (ready) this.#main.postMessage({ type: 'run', id, program: ready.bytes, module: ready.module, hash: ready.hash, args, env, node, opts })
|
|
208
|
+
else this.#main.postMessage({ type: 'run', id, program: buf, args, env, node, opts }, [buf])
|
|
168
209
|
})
|
|
169
210
|
}
|
|
170
211
|
|
|
212
|
+
/**
|
|
213
|
+
* 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
|
|
214
|
+
* capped as run() caps it (memoryMaxMiB, default 1024), copied into a SharedArrayBuffer when the page may make one (posting it to a Worker then
|
|
215
|
+
* copies nothing), the sha256 of those bytes, and the compiled module. -> {bytes, hash, module, cap, memoryMaxMiB}
|
|
216
|
+
*/
|
|
217
|
+
static async prepare(program, { memoryMaxMiB = 1024, compile = (b) => WebAssembly.compile(b), digest = (b) => crypto.subtle.digest('SHA-256', b) } = {}) {
|
|
218
|
+
let bytes = program instanceof Uint8Array ? program : new Uint8Array(program)
|
|
219
|
+
let cap = { before: null, after: null }
|
|
220
|
+
if (memoryMaxMiB) {
|
|
221
|
+
const c = capMemoryMax(bytes, pagesOfMiB(memoryMaxMiB))
|
|
222
|
+
cap = { before: c.before, after: c.after }
|
|
223
|
+
bytes = c.bytes
|
|
224
|
+
}
|
|
225
|
+
// the digest and the compile read the plain bytes (an engine may refuse a shared view), both at once
|
|
226
|
+
const plain = typeof SharedArrayBuffer === 'function' && bytes.buffer instanceof SharedArrayBuffer ? bytes.slice() : bytes
|
|
227
|
+
const [hash, module] = await Promise.all([digest(plain), compile(plain)])
|
|
228
|
+
// (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
|
|
229
|
+
// 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.)
|
|
230
|
+
if (typeof SharedArrayBuffer === 'function' && !(bytes.buffer instanceof SharedArrayBuffer)) {
|
|
231
|
+
try {
|
|
232
|
+
const shared = new Uint8Array(new SharedArrayBuffer(bytes.length))
|
|
233
|
+
shared.set(bytes)
|
|
234
|
+
bytes = shared
|
|
235
|
+
} catch {
|
|
236
|
+
// no shared memory here: the bytes stay as they are
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return { bytes, hash: new Uint8Array(hash), module, cap, memoryMaxMiB }
|
|
240
|
+
}
|
|
241
|
+
|
|
171
242
|
/** Input for the program's standard input (bytes). Held and fed as the program reads: the ring is 256 KiB. */
|
|
172
243
|
writeStdin(bytes) {
|
|
173
244
|
this.#stdin.write(bytes)
|
|
@@ -216,6 +287,12 @@ export class OwnRuntime {
|
|
|
216
287
|
})
|
|
217
288
|
}
|
|
218
289
|
|
|
290
|
+
#forged = 0
|
|
291
|
+
/** How many messages of the Workers were of no known kind (dropped, X5 fix3p P3). */
|
|
292
|
+
get forged() {
|
|
293
|
+
return this.#forged
|
|
294
|
+
}
|
|
295
|
+
|
|
219
296
|
/** Counters of the threads' messages (see #capi). */
|
|
220
297
|
get capiStats() {
|
|
221
298
|
return { ...this.#capiN }
|
|
@@ -296,6 +373,10 @@ export class OwnRuntime {
|
|
|
296
373
|
}
|
|
297
374
|
}
|
|
298
375
|
|
|
376
|
+
#fsStat = 0 // address of the runtime's table of file-route round trips (python runs, fs-stats.js), 0 until it says
|
|
377
|
+
#sigWake = 0 // address in the runtime's memory of the word that wakes the signal thread, 0 until the program registers a flag
|
|
378
|
+
#sigFlags = [] // X25 gate 2: {words, at, bits} the program registered (CPython's eval breaker), see 'sigflag'
|
|
379
|
+
|
|
299
380
|
get workerCount() {
|
|
300
381
|
return this.#dead ? 0 : 1 + (this.#pool ? this.#pool.live : 0)
|
|
301
382
|
}
|
|
@@ -307,6 +388,12 @@ export class OwnRuntime {
|
|
|
307
388
|
signal(n) {
|
|
308
389
|
if (n === 9) return this.terminate()
|
|
309
390
|
this.#opts.fsRoute?.queueSignal?.(0, n)
|
|
391
|
+
if (this.#sigWake && this.#memory) {
|
|
392
|
+
// the signal thread of a program that registered a flag (python): one more on its word, and wake it
|
|
393
|
+
const w = new Int32Array(this.#memory.buffer)
|
|
394
|
+
Atomics.add(w, this.#sigWake >> 2, 1)
|
|
395
|
+
Atomics.notify(w, this.#sigWake >> 2)
|
|
396
|
+
}
|
|
310
397
|
}
|
|
311
398
|
|
|
312
399
|
terminate() {
|
|
@@ -330,6 +417,12 @@ export class OwnRuntime {
|
|
|
330
417
|
case 'spawn':
|
|
331
418
|
this.#spawn(data)
|
|
332
419
|
break
|
|
420
|
+
case 'mark':
|
|
421
|
+
if (this.#marks) this.#marks.add(data.name, data.t)
|
|
422
|
+
break
|
|
423
|
+
case 'calls':
|
|
424
|
+
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 }
|
|
425
|
+
break
|
|
333
426
|
case 'counts': {
|
|
334
427
|
const w = this.#countWait.get(data.seq)
|
|
335
428
|
if (w) {
|
|
@@ -367,23 +460,40 @@ export class OwnRuntime {
|
|
|
367
460
|
this.#opts.onLog({ type: 'log', text: 'fs call failed: ' + (e && e.message) })
|
|
368
461
|
})
|
|
369
462
|
break
|
|
463
|
+
case 'fsstat':
|
|
464
|
+
if (Number.isInteger(data.addr)) this.#fsStat = data.addr
|
|
465
|
+
break
|
|
466
|
+
case 'sigflag':
|
|
467
|
+
// X25 gate 2: the program (CPython) registered a flag word; it is set when the runtime has queued a signal (sigraise)
|
|
468
|
+
if (data.wake) this.#sigWake = data.wake // the word the runtime's signal thread waits on (edge/browser pysignal.rs)
|
|
469
|
+
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 })
|
|
470
|
+
break
|
|
471
|
+
case 'sigraise':
|
|
472
|
+
for (const f of this.#sigFlags) Atomics.or(f.words, f.at, f.bits)
|
|
473
|
+
break
|
|
370
474
|
case 'note': {
|
|
371
475
|
// a line from the runtime's own code (child spawning, fix round 5): kept in the route's ring
|
|
372
476
|
this.#note(String(data.text))
|
|
373
477
|
break
|
|
374
478
|
}
|
|
375
479
|
case 'exit':
|
|
376
|
-
case 'run-error':
|
|
480
|
+
case 'run-error': {
|
|
377
481
|
// Output of other threads may still be on its way (Workers' messages have no common order): hold the end of
|
|
378
482
|
// the run until as many outputs arrived as were sent.
|
|
379
|
-
|
|
483
|
+
// 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
|
|
484
|
+
const end = exitOfRun(data, this.#runs)
|
|
485
|
+
if (end) this.#held.push(end)
|
|
380
486
|
this.#release()
|
|
381
487
|
break
|
|
488
|
+
}
|
|
382
489
|
case 'fatal':
|
|
383
490
|
this.#fatal(new Error(data.error))
|
|
384
491
|
break
|
|
385
492
|
default:
|
|
386
|
-
|
|
493
|
+
// 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:
|
|
494
|
+
// it is dropped and counted (forged, adapter stats(), the bridge's forgedMessages), never handed to onLog as if it were the runtime's log.
|
|
495
|
+
// The runtime's own log lines are made here (#refuse, the file calls) and reach onLog directly.
|
|
496
|
+
this.#forged++
|
|
387
497
|
}
|
|
388
498
|
}
|
|
389
499
|
|
|
@@ -403,6 +513,7 @@ export class OwnRuntime {
|
|
|
403
513
|
// A thread asks for a Worker for a job. The message is forwarded unread: it carries the module and the shared
|
|
404
514
|
// memory (structured clone) and the address of the job.
|
|
405
515
|
#spawn(data) {
|
|
516
|
+
if (this.#marks) this.#marks.add('spawnReq', performance.timeOrigin + performance.now())
|
|
406
517
|
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
518
|
try {
|
|
408
519
|
this.#pool.dispatch({ type: 'task', msg: data.msg, ack: data.ack })
|
package/src/edge/own/loader.js
CHANGED
|
@@ -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
|
-
|
|
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
|
+
}
|