@threadedstack/wmd-web 0.1.30 → 0.1.32

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 (62) hide show
  1. package/README.md +23 -2
  2. package/RELEASE.json +123 -16
  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 +47 -2
  8. package/src/edge/bridge.js +297 -0
  9. package/src/edge/codes.js +10 -0
  10. package/src/edge/ctl.js +199 -0
  11. package/src/edge/error-kind.js +4 -0
  12. package/src/edge/frame.html +4 -0
  13. package/src/edge/frame.js +48 -0
  14. package/src/edge/fs-route.js +301 -0
  15. package/src/edge/hist.js +46 -0
  16. package/src/edge/msg.js +106 -0
  17. package/src/edge/node-args.js +194 -0
  18. package/src/edge/node-guest-opts.js +108 -0
  19. package/src/edge/node-opts.js +82 -0
  20. package/src/edge/own/adapter.js +271 -0
  21. package/src/edge/own/capi.js +200 -0
  22. package/src/edge/own/child-host.js +196 -0
  23. package/src/edge/own/fs-bridge.js +71 -0
  24. package/src/edge/own/fs-own-route.js +356 -0
  25. package/src/edge/own/guest-spawner.js +235 -0
  26. package/src/edge/own/hub.js +430 -0
  27. package/src/edge/own/loader.js +81 -0
  28. package/src/edge/own/memcap.js +95 -0
  29. package/src/edge/own/payload-size.js +15 -0
  30. package/src/edge/own/pool.js +160 -0
  31. package/src/edge/own/procfs.js +84 -0
  32. package/src/edge/own/serdes-codec.js +317 -0
  33. package/src/edge/own/service-receiver.js +98 -0
  34. package/src/edge/own/shim-post.js +185 -0
  35. package/src/edge/own/stack-fix.js +36 -0
  36. package/src/edge/own/stdio-pipe.js +80 -0
  37. package/src/edge/own/v8-serdes.js +970 -0
  38. package/src/edge/own/wasm-counters.js +144 -0
  39. package/src/edge/own/worker.js +97 -0
  40. package/src/edge/page.js +162 -0
  41. package/src/edge/plan.js +65 -0
  42. package/src/edge/resolve.js +44 -0
  43. package/src/edge/runtime.js +94 -0
  44. package/src/edge/sdk/adapter.js +151 -0
  45. package/src/edge/sdk/forward.js +80 -0
  46. package/src/edge/sdk/napi-stub.js +50 -0
  47. package/src/edge/sdk/relay.js +17 -0
  48. package/src/edge/service-host.js +382 -0
  49. package/src/edge/service-port.js +245 -0
  50. package/src/edge/shim.js +161 -0
  51. package/src/edge/site.js +106 -0
  52. package/src/edge/spawn-guard.js +80 -0
  53. package/src/edge/tz.js +103 -0
  54. package/src/edge/worker.js +121 -0
  55. package/src/edge/workers.js +27 -0
  56. package/src/host/chan-service.js +75 -8
  57. package/src/host/chan-services.js +77 -3
  58. package/src/host/ctl.js +26 -5
  59. package/src/host/edge-go.js +7 -3
  60. package/src/host/edge-host.js +327 -0
  61. package/src/host/yamux.js +21 -8
  62. package/wmdpack.wasm +0 -0
@@ -0,0 +1,430 @@
1
+ // The page side of wmd's own runtime (X5 own runtime, step 3). It starts the "runtime main" Worker, owns the pool
2
+ // of thread Workers and does what a blocked thread cannot: start Workers. The page's main thread never blocks, so
3
+ // a request from a blocked thread ({ type: 'spawn' }) is always answered.
4
+ //
5
+ // const rt = await OwnRuntime.start({ wasmUrl, glueUrl, workerUrl, onOut, fsRoute, trace })
6
+ // fsRoute { handle(method, args, data) } answers the program's file calls (fs-own-route.js); without it the program has no files
7
+ // memoryMaxMiB cap on the maximum of the program's memory, default 1024 (0: none); see memcap.js
8
+ // trace 0 off, 1 failed WASIX calls, 2 every call (to the Workers' consoles; the program's environment is never traced)
9
+ // const { code } = await rt.run({ program, args, env })
10
+ // rt.terminate() // ends every Worker; none is left
11
+ //
12
+ // The runtime module and its glue are the build output of edge/browser (edge/browser/build.sh).
13
+
14
+ import { BIG_SHARE, payloadBytes } from './payload-size.js'
15
+ import { WorkerPool } from './pool.js'
16
+ import { serveFsCall } from './fs-bridge.js'
17
+ import { StdinPipe, setTtySize } from './stdio-pipe.js'
18
+ import { capMemoryMax, pagesOfMiB } from './memcap.js'
19
+ import { hasJspi } from './loader.js'
20
+ import { withProc } from './procfs.js'
21
+
22
+ const NO_ROUTE = { handle: () => ({ error: { code: 'ENOSYS', message: 'this runtime has no file route' } }) }
23
+
24
+ export { payloadBytes }
25
+
26
+ export class OwnRuntime {
27
+ #opts
28
+ #create
29
+ #module = null
30
+ #memory = null
31
+ #main = null
32
+ #pool = null
33
+ #booted = null
34
+ // one BroadcastChannel name for all Workers of this runtime (node's messages between threads, capi.js) and a number for each Worker
35
+ #capi = `wmd-own-capi-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`
36
+ #scopes = 0
37
+ #byScope = new Map() // scope -> Worker (a want names its asker by scope)
38
+ #big = new Map() // key -> {data, size, sent: Set(scope)}: shares of BIG_SHARE bytes or more, held here and sent to the Worker that asks (fix7 F18)
39
+ #bigHeld = new Map() // key -> bytes the held share costs now (page copy, the sender's, and each Worker's)
40
+ #wants = new Map() // key -> Set(scope): asks that came before the share
41
+ #runs = new Map()
42
+ #nextRun = 1
43
+ #dead = false
44
+ #outsSeen = 0
45
+ // fix7 (F18): what the threads' messages cost. A message from a Worker comes to the page as one copy, and the page sends each Worker its own copy (a
46
+ // structured clone of a non-shared buffer): `copies` counts the receivers, `copyBytes` the bytes cloned to them, `heldBytes` what the shares that were
47
+ // not deleted yet keep in Workers (the sender's table and each receiver's), `heldPeak` its largest value.
48
+ #capiN = { messages: 0, bytes: 0, copies: 0, copyBytes: 0, maxMessage: 0, maxRecipients: 0, heldBytes: 0, heldPeak: 0 }
49
+ #capiHeld = new Map()
50
+ #countWait = new Map() // fix7 item 15: seq -> {got: [], want, done}
51
+ #countSeq = 0
52
+ #held = []
53
+ #glue
54
+ #stdin = null
55
+ #ttyAddr = 0
56
+
57
+ static async start(opts) {
58
+ const rt = new OwnRuntime(opts)
59
+ await rt.#boot()
60
+ return rt
61
+ }
62
+
63
+ constructor(opts) {
64
+ this.#opts = { spare: 2, max: 128, stack: 4 * 1024 * 1024, memoryMaxMiB: 1024, onOut: () => {}, onLog: () => {}, ...opts }
65
+ this.#create = this.#opts.create || ((url, o) => new Worker(url, o))
66
+ const base = typeof location === 'undefined' ? undefined : location.href
67
+ this.#glue = new URL(this.#opts.glueUrl, base).href
68
+ }
69
+
70
+ // 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
+ #routeCache = null
72
+ // 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
+ // 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
+ #fsT = globalThis.__wmdFsTime ? new Map() : null
75
+ #timed(t0) {
76
+ const tr = performance.timeOrigin + performance.now()
77
+ return (method, inB, outB) => {
78
+ const td = performance.timeOrigin + performance.now()
79
+ const m = this.#fsT.get(method) || { n: 0, serveMs: 0, waitMs: 0, postMs: 0, inB: 0, outB: 0 }
80
+ m.n++
81
+ m.serveMs += td - tr
82
+ if (typeof t0 === 'number') {
83
+ m.waitMs += td - t0
84
+ m.postMs += tr - t0
85
+ }
86
+ m.inB += inB
87
+ m.outB += outB
88
+ this.#fsT.set(method, m)
89
+ }
90
+ }
91
+ get fsTiming() {
92
+ return this.#fsT ? Object.fromEntries(this.#fsT) : null
93
+ }
94
+
95
+ #note(text) {
96
+ try {
97
+ const r = this.#opts.fsRoute && this.#opts.fsRoute.handle && this.#opts.fsRoute.handle('note', [String(text).slice(0, 160)], new Uint8Array(0))
98
+ if (r && typeof r.catch === 'function') r.catch(() => {})
99
+ } catch {
100
+ // a route that is gone is no reason to stop
101
+ }
102
+ }
103
+
104
+ #route() {
105
+ if (!this.#opts.fsRoute) return NO_ROUTE
106
+ return (this.#routeCache ||= withProc(this.#opts.fsRoute, () => this.#memory.buffer.byteLength))
107
+ }
108
+
109
+ async #boot() {
110
+ const { wasmUrl, workerUrl, stack } = this.#opts
111
+ try {
112
+ this.#module = this.#opts.module || (await WebAssembly.compileStreaming(fetch(wasmUrl)))
113
+ } catch (e) {
114
+ // fix 11 (F-M): a runtime wasm that is not there (a 404 is the browser's own bare TypeError) or does not compile is a runtime that did not load: the
115
+ // page counts it and remembers it (src/edge/worker.js, bridge.js) as it does for a file that does not match HASHES.txt
116
+ const err = new Error(`the runtime's wasm did not load (${wasmUrl}): ${String((e && e.message) || e)}`)
117
+ err.runtimeFiles = true
118
+ throw err
119
+ }
120
+ this.#main = this.#create(workerUrl, { type: 'module', name: 'wmd-own-main' })
121
+ this.#main.addEventListener('message', (e) => this.#fromWorker(e.data))
122
+ this.#main.addEventListener('error', (e) => this.#fatal(new Error('runtime main worker: ' + (e.message || 'error'))))
123
+ const ready = new Promise((resolve, reject) => (this.#booted = { resolve, reject }))
124
+ 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 })
126
+ const up = await ready
127
+ this.#memory = up.memory
128
+ this.#stdin = new StdinPipe(this.#memory, up.stdin)
129
+ this.#ttyAddr = up.tty
130
+ this.#pool = new WorkerPool({
131
+ 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 })),
133
+ spare: this.#opts.spare,
134
+ max: this.#opts.max,
135
+ onMessage: (_id, data) => this.#fromWorker(data),
136
+ onFailure: (_id, tasks, err) => {
137
+ // a Worker that trapped or failed (a thread that stops without a word is found by this line in the route's ring)
138
+ this.#note('thread ended: ' + String((err && err.message) || err).slice(0, 140))
139
+ for (const t of tasks) this.#refuse(t.ack, err)
140
+ },
141
+ })
142
+ this.#pool.warm()
143
+ }
144
+
145
+ // Runs a WASIX program (bytes) to its end: { code }. One program per runtime.
146
+ // cwd the program's working directory
147
+ // stdin 'pipe' (writeStdin and closeStdin feed it) or 'null' (end of input at once; the default)
148
+ // 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
+ // exec the program's own path as it knows it (process.execPath): a spawn of it runs the same module again in this runtime
150
+ // shim true: that child gets --require /.wmd-edge/linux.cjs
151
+ // tty { in, out, err, cols, rows }: which of the three are terminals (the others are pipes) and the terminal's size
152
+ // 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 }) {
154
+ if (this.#dead) return Promise.reject(new Error('runtime terminated'))
155
+ 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
162
+ }
163
+ return new Promise((resolve, reject) => {
164
+ this.#runs.set(id, { resolve, reject })
165
+ const opts = JSON.stringify({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, jspi: hasJspi() })
166
+ 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])
168
+ })
169
+ }
170
+
171
+ /** Input for the program's standard input (bytes). Held and fed as the program reads: the ring is 256 KiB. */
172
+ writeStdin(bytes) {
173
+ this.#stdin.write(bytes)
174
+ }
175
+ /** End of input. */
176
+ closeStdin() {
177
+ this.#stdin.close()
178
+ }
179
+ /** The terminal changed size (a window size change). */
180
+ resize(cols, rows) {
181
+ setTtySize(this.#memory, this.#ttyAddr, cols, rows)
182
+ }
183
+
184
+ // The number of Workers that are alive: the main one and the pool's.
185
+ /** The size of the module's memory now, in bytes (it only grows: after a run this is the run's peak). */
186
+ get memoryBytes() {
187
+ return this.#memory ? this.#memory.buffer.byteLength : 0
188
+ }
189
+
190
+ /**
191
+ * fix7 item 15: the WebAssembly counters of every Worker of this runtime (wasm-counters.js), asked at once and gathered for at most `ms`:
192
+ * [{role, c}], the main Worker first.
193
+ */
194
+ collectCounts(ms = 400) {
195
+ if (this.#dead) return Promise.resolve([])
196
+ const ws = [this.#main, ...(this.#pool ? this.#pool.workers : [])].filter(Boolean)
197
+ const seq = ++this.#countSeq
198
+ return new Promise((resolve) => {
199
+ const w = { got: [], want: ws.length }
200
+ const end = () => {
201
+ this.#countWait.delete(seq)
202
+ resolve(w.got)
203
+ }
204
+ w.end = end
205
+ this.#countWait.set(seq, w)
206
+ const t = setTimeout(end, ms)
207
+ w.clear = () => clearTimeout(t)
208
+ for (const x of ws) {
209
+ try {
210
+ x.postMessage({ type: 'counts', seq })
211
+ } catch {
212
+ w.want--
213
+ }
214
+ }
215
+ if (w.got.length >= w.want) (w.clear(), end())
216
+ })
217
+ }
218
+
219
+ /** Counters of the threads' messages (see #capi). */
220
+ get capiStats() {
221
+ return { ...this.#capiN }
222
+ }
223
+
224
+ // fix7 F18: a large share is kept for the Workers that ask; each asker gets one copy, once
225
+ #capiHold(k, data) {
226
+ const have = this.#big.get(k)
227
+ const e = have ? ((have.data = data), have) : { data, size: payloadBytes((data.msg || {}).envelope), sent: new Set() }
228
+ if (!have) {
229
+ this.#big.set(k, e)
230
+ const c = this.#capiN
231
+ c.messages++
232
+ c.bytes += e.size
233
+ c.maxMessage = Math.max(c.maxMessage, e.size)
234
+ c.heldBytes += e.size * 2 // this copy and the sender's own
235
+ this.#bigHeld.set(k, e.size * 2)
236
+ c.heldPeak = Math.max(c.heldPeak, c.heldBytes)
237
+ }
238
+ const asks = this.#wants.get(k)
239
+ if (asks) {
240
+ this.#wants.delete(k)
241
+ for (const sc of asks) this.#capiServe(k, e, sc)
242
+ }
243
+ }
244
+
245
+ #capiWant(k, scope) {
246
+ const e = this.#big.get(k)
247
+ if (e) return this.#capiServe(k, e, scope)
248
+ const asks = this.#wants.get(k) || new Set()
249
+ asks.add(scope)
250
+ this.#wants.set(k, asks)
251
+ if (this.#wants.size > 4096) this.#wants.delete(this.#wants.keys().next().value) // asks for handles that are never shared as large
252
+ }
253
+
254
+ #capiServe(k, e, scope) {
255
+ const w = this.#byScope.get(scope)
256
+ if (!w || e.sent.has(scope)) return
257
+ e.sent.add(scope)
258
+ const c = this.#capiN
259
+ c.copies++
260
+ c.copyBytes += e.size
261
+ c.maxRecipients = Math.max(c.maxRecipients, e.sent.size)
262
+ c.heldBytes += e.size
263
+ this.#bigHeld.set(k, (this.#bigHeld.get(k) || 0) + e.size)
264
+ c.heldPeak = Math.max(c.heldPeak, c.heldBytes)
265
+ try {
266
+ w.postMessage(e.data)
267
+ } catch {
268
+ // that Worker is gone
269
+ }
270
+ }
271
+
272
+ #countCapi(data) {
273
+ const c = this.#capiN
274
+ const m = data.msg || {}
275
+ const to = [this.#main, ...(this.#pool ? this.#pool.workers : [])].filter(Boolean).length
276
+ const size = payloadBytes(m.envelope)
277
+ const k = `${m.registry}:${m.handle}`
278
+ if (m.t === 'share') {
279
+ c.messages++
280
+ c.bytes += size
281
+ c.copies += to
282
+ c.copyBytes += size * to
283
+ c.maxMessage = Math.max(c.maxMessage, size)
284
+ c.maxRecipients = Math.max(c.maxRecipients, to)
285
+ const held = size * (to + 1) // each Worker that got a copy, and the sender's own envelope
286
+ c.heldBytes += held - (this.#capiHeld.get(k) || 0)
287
+ this.#capiHeld.set(k, held)
288
+ c.heldPeak = Math.max(c.heldPeak, c.heldBytes)
289
+ } else if (m.t === 'delete' && this.#capiHeld.has(k)) {
290
+ c.heldBytes -= this.#capiHeld.get(k)
291
+ this.#capiHeld.delete(k)
292
+ }
293
+ if (m.t === 'delete' && this.#bigHeld.has(k)) {
294
+ c.heldBytes -= this.#bigHeld.get(k)
295
+ this.#bigHeld.delete(k)
296
+ }
297
+ }
298
+
299
+ get workerCount() {
300
+ return this.#dead ? 0 : 1 + (this.#pool ? this.#pool.live : 0)
301
+ }
302
+ get pool() {
303
+ return this.#pool
304
+ }
305
+
306
+ /** Signal n for the program: the shim takes it from the route's queue (OwnFsRoute.queueSignal) and acts as node does (a handler, or exit 128+n). 9 ends it at once. */
307
+ signal(n) {
308
+ if (n === 9) return this.terminate()
309
+ this.#opts.fsRoute?.queueSignal?.(0, n)
310
+ }
311
+
312
+ terminate() {
313
+ this.#dead = true
314
+ if (this.#main) this.#main.terminate()
315
+ if (this.#pool) this.#pool.terminateAll()
316
+ this.#fatal(new Error('runtime terminated'))
317
+ }
318
+
319
+ #fromWorker(data) {
320
+ switch (data && data.type) {
321
+ case 'ready':
322
+ if (this.#booted) this.#booted.resolve(data)
323
+ this.#booted = null
324
+ break
325
+ case 'out':
326
+ this.#outsSeen++
327
+ this.#opts.onOut(data.fd, data.data)
328
+ this.#release()
329
+ break
330
+ case 'spawn':
331
+ this.#spawn(data)
332
+ break
333
+ case 'counts': {
334
+ const w = this.#countWait.get(data.seq)
335
+ if (w) {
336
+ w.got.push({ role: data.role, c: data.c })
337
+ if (w.got.length >= w.want) (w.clear(), w.end())
338
+ }
339
+ break
340
+ }
341
+ case 'capi': {
342
+ // node's messages between threads (capi.js). A share of BIG_SHARE bytes or more is held here and sent only to the Worker that asks
343
+ // for it (the receiver is one thread of the pool; a copy to each of the Workers cost 7 copies of every Buffer, fix7 F18); the others
344
+ // are forwarded to every Worker, the sender ignores its own
345
+ const m = data.msg || {}
346
+ const k = `${m.registry}:${m.handle}`
347
+ if (m.t === 'want') return this.#capiWant(k, m.from)
348
+ if (m.t === 'share' && payloadBytes(m.envelope) >= BIG_SHARE) return this.#capiHold(k, data)
349
+ if (m.t === 'share') this.#wants.delete(k)
350
+ if (m.t === 'delete') {
351
+ this.#big.delete(k)
352
+ this.#wants.delete(k)
353
+ }
354
+ this.#countCapi(data)
355
+ for (const w of [this.#main, ...(this.#pool ? this.#pool.workers : [])]) if (w) w.postMessage(data)
356
+ break
357
+ }
358
+ case 'fs':
359
+ // a file call from a thread: answered here, on the page, which never blocks
360
+ serveFsCall(this.#memory, data.slot, this.#route(), this.#fsT ? this.#timed(data.t0) : undefined)
361
+ .then((m) => {
362
+ // the answer of a peek is written and the Worker woken: the route's ring says so (a child's spawn that stops after it is then known to stop in the Worker)
363
+ if (m === 'peek') this.#note('hub: peek answered')
364
+ })
365
+ .catch((e) => {
366
+ this.#note('fs call failed: ' + String((e && e.message) || e).slice(0, 120))
367
+ this.#opts.onLog({ type: 'log', text: 'fs call failed: ' + (e && e.message) })
368
+ })
369
+ break
370
+ case 'note': {
371
+ // a line from the runtime's own code (child spawning, fix round 5): kept in the route's ring
372
+ this.#note(String(data.text))
373
+ break
374
+ }
375
+ case 'exit':
376
+ case 'run-error':
377
+ // Output of other threads may still be on its way (Workers' messages have no common order): hold the end of
378
+ // the run until as many outputs arrived as were sent.
379
+ this.#held.push(data)
380
+ this.#release()
381
+ break
382
+ case 'fatal':
383
+ this.#fatal(new Error(data.error))
384
+ break
385
+ default:
386
+ this.#opts.onLog(data)
387
+ }
388
+ }
389
+
390
+ #release() {
391
+ const ready = this.#held.filter((d) => this.#outsSeen >= (d.outs || 0))
392
+ if (!ready.length) return
393
+ this.#held = this.#held.filter((d) => !ready.includes(d))
394
+ for (const d of ready) {
395
+ const run = this.#runs.get(d.id)
396
+ this.#runs.delete(d.id)
397
+ if (!run) continue
398
+ if (d.type === 'exit') run.resolve({ code: d.code })
399
+ else run.reject(new Error(d.error))
400
+ }
401
+ }
402
+
403
+ // A thread asks for a Worker for a job. The message is forwarded unread: it carries the module and the shared
404
+ // memory (structured clone) and the address of the job.
405
+ #spawn(data) {
406
+ 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
+ try {
408
+ this.#pool.dispatch({ type: 'task', msg: data.msg, ack: data.ack })
409
+ } catch (err) {
410
+ this.#refuse(data.ack, err)
411
+ }
412
+ }
413
+
414
+ // Tells the thread that asked that it gets no Worker: ack word 0 -> 2, and wakes it. A word already set (the
415
+ // thread started) is left alone.
416
+ #refuse(ack, err) {
417
+ this.#opts.onLog({ type: 'log', text: 'spawn refused: ' + (err && err.message) })
418
+ if (!ack || !this.#memory) return
419
+ const words = new Int32Array(this.#memory.buffer)
420
+ Atomics.compareExchange(words, ack >> 2, 0, 2)
421
+ Atomics.notify(words, ack >> 2)
422
+ }
423
+
424
+ #fatal(err) {
425
+ if (this.#booted) this.#booted.reject(err)
426
+ this.#booted = null
427
+ for (const run of this.#runs.values()) run.reject(err)
428
+ this.#runs.clear()
429
+ }
430
+ }
@@ -0,0 +1,81 @@
1
+ // The loader of wmd's own runtime: what a Worker (the runtime-main Worker or a thread Worker) and the frame do to get the
2
+ // runtime module running. One place, so every Worker starts it the same way.
3
+ //
4
+ // loadRuntime({ glue, module, memory, stack, debug, importer })
5
+ // glue URL of wasm-bindgen's JavaScript (wmd_browser.js of edge/browser/build.sh)
6
+ // module the compiled WebAssembly.Module (compiled once on the page, sent to every Worker)
7
+ // memory the shared WebAssembly.Memory (absent on the first Worker, which makes it)
8
+ // stack bytes of stack of a thread
9
+ // returns { glue, memory }: the glue module, and the shared memory every Worker must be given
10
+ //
11
+ // The N-API snippet of the glue imports acorn from `../../acorn/acorn.mjs`, a file next to the glue (bundle-acorn.sh), so a
12
+ // Worker needs no import map and no bare specifier.
13
+
14
+ /** The message the page sends a Worker to start it. Throws on a message that cannot start a Worker. */
15
+ export function checkInit(m) {
16
+ if (!m || m.type !== 'init') throw new Error('not an init message')
17
+ if (typeof m.glue !== 'string' || !m.glue) throw new Error('init: glue URL missing')
18
+ if (!m.module) throw new Error('init: compiled module missing')
19
+ if (m.role !== 'main' && m.role !== 'thread') throw new Error(`init: role must be main or thread, got ${m.role}`)
20
+ if (m.role === 'thread' && !m.memory) throw new Error('init: a thread Worker needs the shared memory')
21
+ return m
22
+ }
23
+
24
+ /** True when this engine can suspend a WebAssembly call and resume it from the event loop (JSPI). */
25
+ export const hasJspi = () => typeof WebAssembly.promising === 'function' && typeof WebAssembly.Suspending === 'function'
26
+
27
+ // What `wmd_turn` (edge/browser/src/tasks.rs) waits for: the Worker's event loop having run. Right after a wake-up a message
28
+ // channel gives the shortest turn; a loop that stays idle falls back to a 2 ms timer so it does not spin.
29
+ export function makeTurn(now = () => performance.now(), channel = () => new MessageChannel(), timer = setTimeout) {
30
+ let last = 0
31
+ let idle = 0
32
+ let ch = null
33
+ return () => {
34
+ const t = now()
35
+ idle = t - last > 50 ? 0 : idle + 1
36
+ last = t
37
+ if (idle < 100) {
38
+ ch ||= channel()
39
+ return new Promise(r => {
40
+ ch.port1.onmessage = () => r()
41
+ ch.port2.postMessage(0)
42
+ })
43
+ }
44
+ return new Promise(r => timer(r, 2))
45
+ }
46
+ }
47
+
48
+ // Gives the wasm-bindgen glue's `wmdTurn` import (a plain JavaScript function in the generated code) to the engine as a
49
+ // suspending function, while the glue instantiates the module. The glue calls `WebAssembly.instantiate` or `new
50
+ // WebAssembly.Instance` with an import object; the entry of that object whose name has `wmdTurn` in it is replaced.
51
+ function suspendingImports(turn, run) {
52
+ const wrap = imports => {
53
+ for (const ns of Object.values(imports || {})) {
54
+ for (const k of Object.keys(ns || {})) {
55
+ if (k.includes('wmdTurn')) ns[k] = new WebAssembly.Suspending(turn)
56
+ }
57
+ }
58
+ return imports
59
+ }
60
+ const inst = WebAssembly.instantiate
61
+ const Inst = WebAssembly.Instance
62
+ WebAssembly.instantiate = (src, imports, ...rest) => inst.call(WebAssembly, src, wrap(imports), ...rest)
63
+ WebAssembly.Instance = new Proxy(Inst, { construct: (T, [mod, imports], nt) => Reflect.construct(T, [mod, wrap(imports)], nt) })
64
+ return run().finally(() => {
65
+ WebAssembly.instantiate = inst
66
+ WebAssembly.Instance = Inst
67
+ })
68
+ }
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)
72
+ const init = () => g.default({ module_or_path: module, memory, thread_stack_size: stack })
73
+ // A thread Worker runs its jobs through WebAssembly.promising (worker.js) so the program's main context can wait for the
74
+ // engine's event loop (Edge.js's event-loop checkpoint is a suspension); it needs the turn import suspending.
75
+ const turning = jspi && role === 'thread'
76
+ const wasm = turning ? await suspendingImports(makeTurn(), init) : await init()
77
+ g.wmd_init()
78
+ g.wmd_set_debug(!!debug)
79
+ if (turning) g.wmd_enable_turn()
80
+ return { glue: g, memory: memory || wasm.memory, exports: wasm, turning }
81
+ }
@@ -0,0 +1,95 @@
1
+ // A cap on the maximum of a guest's linear memory (item 7). WebKit reserves the declared maximum of every shared memory when
2
+ // the memory is made and gives it back only at garbage collection (web/test/own/memlimit.spec.js: a 4 GiB maximum allows about
3
+ // 15 runtimes in one page, a 1 GiB one about 38). wasixcc declares 4 GiB for every program, Edge.js's node too (65536 pages).
4
+ // This rewrites the maximum in the module's bytes before it is compiled: the memory import (section 2) or the memory
5
+ // section (5). The new number is written in as many bytes as the old one, padded with continuation bytes (a LEB128 number may
6
+ // be padded), so no section changes its size and nothing is moved. A maximum already under the cap, and a memory with no
7
+ // maximum, are left as they are (a program with no maximum grows as far as the engine lets it; the cap is for programs that
8
+ // ask for a lot).
9
+
10
+ const PAGE = 65536
11
+
12
+ function readLeb(b, i) {
13
+ let r = 0
14
+ let s = 0
15
+ for (;;) {
16
+ const x = b[i++]
17
+ r += (x & 0x7f) * 2 ** s
18
+ s += 7
19
+ if (!(x & 0x80)) return [r, i]
20
+ }
21
+ }
22
+
23
+ function writePadded(b, at, len, value) {
24
+ for (let k = 0; k < len; k++) {
25
+ const part = value % 128
26
+ value = Math.floor(value / 128)
27
+ b[at + k] = part | (k < len - 1 ? 0x80 : 0)
28
+ }
29
+ }
30
+
31
+ /** Returns {bytes, before, after} (pages; before is null if no memory with a maximum was found). `bytes` is a copy when changed. */
32
+ export function capMemoryMax(wasm, maxPages) {
33
+ const b = wasm instanceof Uint8Array ? wasm : new Uint8Array(wasm)
34
+ let i = 8
35
+ while (i < b.length) {
36
+ const id = b[i++]
37
+ let size
38
+ ;[size, i] = readLeb(b, i)
39
+ const end = i + size
40
+ if (id === 2) {
41
+ let [count, j] = readLeb(b, i)
42
+ for (let n = 0; n < count; n++) {
43
+ let l
44
+ ;[l, j] = readLeb(b, j)
45
+ j += l
46
+ ;[l, j] = readLeb(b, j)
47
+ j += l
48
+ const kind = b[j++]
49
+ if (kind === 0) [, j] = readLeb(b, j)
50
+ else if (kind === 1) {
51
+ j++
52
+ const [fl, k] = readLeb(b, j)
53
+ j = k
54
+ ;[, j] = readLeb(b, j)
55
+ if (fl & 1) [, j] = readLeb(b, j)
56
+ } else if (kind === 2) {
57
+ const r = capLimits(b, j, maxPages)
58
+ if (r.done) return r
59
+ j = r.next
60
+ } else if (kind === 3) j += 2
61
+ else {
62
+ j++
63
+ ;[, j] = readLeb(b, j)
64
+ }
65
+ }
66
+ } else if (id === 5) {
67
+ const [count, j0] = readLeb(b, i)
68
+ let j = j0
69
+ for (let n = 0; n < count; n++) {
70
+ const r = capLimits(b, j, maxPages)
71
+ if (r.done) return r
72
+ j = r.next
73
+ }
74
+ }
75
+ i = end
76
+ }
77
+ return { bytes: b, before: null, after: null }
78
+ }
79
+
80
+ // limits at j: flags, min, max?
81
+ function capLimits(b, j, maxPages) {
82
+ const [flags, a] = readLeb(b, j)
83
+ const [min, c] = readLeb(b, a)
84
+ if (!(flags & 1)) return { done: false, next: c }
85
+ const [max, d] = readLeb(b, c)
86
+ const len = d - c
87
+ const cap = Math.max(maxPages, min)
88
+ if (max <= cap) return { done: true, bytes: b, before: max, after: max }
89
+ if (cap >= 128 ** len) throw new Error('memory cap does not fit the number it replaces')
90
+ const out = b.slice()
91
+ writePadded(out, c, len, cap)
92
+ return { done: true, bytes: out, before: max, after: cap }
93
+ }
94
+
95
+ export const pagesOfMiB = mib => Math.floor((mib * 1024 * 1024) / PAGE)
@@ -0,0 +1,15 @@
1
+ // How large a thread message is (hub.js counts it; capi.js and hub.js decide with it which shares are pulled, fix7 F18).
2
+
3
+ /** A share of at least this many bytes is not sent to every Worker: the page holds it and sends it to the Worker that asks (hub.js, capi.js). */
4
+ export const BIG_SHARE = 1 << 20
5
+
6
+ /** The bytes a thread message carries in buffers (shallow walk, a few levels): what each copy of it costs in a Worker's memory. */
7
+ export function payloadBytes(v, depth = 0, seen = new Set()) {
8
+ if (!v || typeof v !== 'object' || depth > 6 || seen.has(v)) return 0
9
+ if (ArrayBuffer.isView(v)) return v.byteLength
10
+ if (v instanceof ArrayBuffer || (typeof SharedArrayBuffer !== 'undefined' && v instanceof SharedArrayBuffer)) return v.byteLength
11
+ seen.add(v)
12
+ let n = 0
13
+ for (const k of Object.keys(v)) n += payloadBytes(v[k], depth + 1, seen)
14
+ return n
15
+ }