@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,144 @@
1
+ // fix7 item 15: what a node start allocates in WebAssembly terms, counted where it happens (the frame's Worker and each runtime Worker).
2
+ // const c = installWasmCounters(globalThis) wraps WebAssembly.compile / compileStreaming / instantiate / instantiateStreaming / Module / Memory
3
+ // and Response.arrayBuffer (the bytes fetched, by what the file is)
4
+ // c.snapshot() -> plain object compile {calls, bytes}, stream {calls, bytes}, instantiate {calls, bytes}, module {calls, bytes},
5
+ // memory {made, shared, live, liveBytes, madeBytes}, fetched {<class>: {calls, bytes}}
6
+ // Nothing is kept but numbers and WeakRefs: a Memory that the page has dropped shows as not live once the engine has collected it.
7
+ const kind = (url) => {
8
+ const u = String(url || '')
9
+ if (/edgejs\.wasm/.test(u)) return 'program'
10
+ if (/wmd_browser_bg\.wasm/.test(u)) return 'runtime'
11
+ if (/wmd_browser\.js/.test(u)) return 'glue'
12
+ if (/HASHES\.txt/.test(u)) return 'hashes'
13
+ if (/linux\.cjs/.test(u)) return 'shim'
14
+ return 'other'
15
+ }
16
+
17
+ const sizeOf = (src) => {
18
+ try {
19
+ if (src && typeof src.byteLength === 'number') return src.byteLength
20
+ if (src && src.buffer && typeof src.buffer.byteLength === 'number') return src.buffer.byteLength
21
+ } catch {
22
+ // not bytes
23
+ }
24
+ return 0
25
+ }
26
+
27
+ export function installWasmCounters(g) {
28
+ if (g.__wmdWasmCounters) return g.__wmdWasmCounters
29
+ const W = g.WebAssembly
30
+ const c = {
31
+ compile: { calls: 0, bytes: 0, ms: 0 },
32
+ stream: { calls: 0, bytes: 0, ms: 0 },
33
+ instantiate: { calls: 0, bytes: 0, ms: 0 },
34
+ module: { calls: 0, bytes: 0, ms: 0, maxMs: 0 },
35
+ memory: { made: 0, shared: 0, madeBytes: 0 },
36
+ fetched: {},
37
+ }
38
+ const refs = []
39
+ const kinds = [] // what each Memory was asked for (initial and maximum in pages), and how big it is when the counters are read
40
+ const wrapAsync = (name, slot, bytesOf) => {
41
+ const orig = W[name]
42
+ if (typeof orig !== 'function') return
43
+ W[name] = function (...a) {
44
+ c[slot].calls++
45
+ c[slot].bytes += bytesOf ? bytesOf(a[0]) : 0
46
+ const t0 = performance.now()
47
+ const p = orig.apply(this, a)
48
+ // the time a call takes to settle, summed (the calls of one Worker overlap only when it starts several at once)
49
+ return p && typeof p.then === 'function' ? p.finally(() => (c[slot].ms += performance.now() - t0)) : p
50
+ }
51
+ }
52
+ wrapAsync('compile', 'compile', sizeOf)
53
+ wrapAsync('instantiate', 'instantiate', sizeOf)
54
+ const streamBytes = (r) => {
55
+ // a Response (or a promise of one): the length the server announced
56
+ try {
57
+ return Number(r && r.headers && r.headers.get && r.headers.get('content-length')) || 0
58
+ } catch {
59
+ return 0
60
+ }
61
+ }
62
+ wrapAsync('compileStreaming', 'stream', null)
63
+ wrapAsync('instantiateStreaming', 'stream', null)
64
+ void streamBytes
65
+ // Proxies, not subclasses: the objects made must be the engine's own (same prototype, same type), because the runtime posts Modules and
66
+ // Memories to its threads and a subclass instance ended a child's spawn with "invalid shared-object type".
67
+ if (W.Module) {
68
+ W.Module = new Proxy(W.Module, {
69
+ construct(target, args) {
70
+ const t0 = performance.now()
71
+ const m = Reflect.construct(target, args)
72
+ const ms = performance.now() - t0
73
+ c.module.calls++
74
+ c.module.bytes += sizeOf(args[0])
75
+ c.module.ms += ms
76
+ c.module.maxMs = Math.max(c.module.maxMs, ms)
77
+ return m
78
+ },
79
+ })
80
+ }
81
+ if (W.Memory) {
82
+ W.Memory = new Proxy(W.Memory, {
83
+ construct(target, args) {
84
+ const d = args[0] || {}
85
+ const m = Reflect.construct(target, args)
86
+ c.memory.made++
87
+ if (d.shared) c.memory.shared++
88
+ refs.push(new WeakRef(m))
89
+ kinds.push({ ref: new WeakRef(m), initial: d.initial | 0, maximum: d.maximum, shared: !!d.shared })
90
+ return m
91
+ },
92
+ })
93
+ }
94
+ const R = g.Response && g.Response.prototype
95
+ if (R && R.arrayBuffer) {
96
+ const orig = R.arrayBuffer
97
+ R.arrayBuffer = async function () {
98
+ const b = await orig.call(this)
99
+ const k = kind(this.url)
100
+ const f = (c.fetched[k] ||= { calls: 0, bytes: 0 })
101
+ f.calls++
102
+ f.bytes += b.byteLength
103
+ return b
104
+ }
105
+ }
106
+ const api = {
107
+ kinds() {
108
+ return kinds.map((k) => {
109
+ const m = k.ref.deref()
110
+ return { initial: k.initial, maximum: k.maximum, shared: k.shared, pages: m ? m.buffer.byteLength / 65536 : null }
111
+ })
112
+ },
113
+ snapshot() {
114
+ let live = 0
115
+ let liveBytes = 0
116
+ for (let i = refs.length - 1; i >= 0; i--) {
117
+ const m = refs[i].deref()
118
+ if (!m) continue
119
+ live++
120
+ try {
121
+ liveBytes += m.buffer.byteLength
122
+ } catch {
123
+ // a memory that cannot be read
124
+ }
125
+ }
126
+ return JSON.parse(JSON.stringify({ ...c, memory: { ...c.memory, live, liveBytes }, kinds: api.kinds() }))
127
+ },
128
+ }
129
+ g.__wmdWasmCounters = api
130
+ return api
131
+ }
132
+
133
+ /** Adds two snapshots (numbers summed field by field). */
134
+ export function addCounts(a, b) {
135
+ const out = JSON.parse(JSON.stringify(a || {}))
136
+ const walk = (dst, src) => {
137
+ for (const [k, v] of Object.entries(src || {})) {
138
+ if (v && typeof v === 'object') walk((dst[k] ||= {}), v)
139
+ else dst[k] = (Number(dst[k]) || 0) + (Number(v) || 0)
140
+ }
141
+ }
142
+ walk(out, b)
143
+ return out
144
+ }
@@ -0,0 +1,97 @@
1
+ // The script of every Worker of wmd's own runtime (X5 own runtime, step 3): the runtime-main Worker and the thread
2
+ // Workers of the pool. It loads the one runtime module (the wasm-bindgen glue, whose URL the page sends) over the
3
+ // shared memory the page sends, and then does what it is told. The page's hub (hub.js) and pool (pool.js) send:
4
+ // { type: 'init', role, glue, module, memory?, stack? } instantiate the runtime; answers { type: 'ready', memory }
5
+ // { type: 'task', msg } thread Workers: run a spawned job; answers { type: 'done' }
6
+ // { type: 'run', id, program, args, env, opts } the main Worker: run a WASIX program (opts: JSON text, see lib.rs); answers { type: 'exit', id, code }
7
+ // A call into the runtime blocks this Worker until the job ends, so no message is read meanwhile; that is why a
8
+ // Worker takes one job at a time and the page starts more.
9
+
10
+ import { checkInit, loadRuntime } from './loader.js'
11
+ import { installCapi, installSerdesState } from './capi.js'
12
+ import { installWasmCounters } from './wasm-counters.js'
13
+ import { installStackHeader } from './stack-fix.js'
14
+
15
+ // node prints an uncaught error from its stack; Firefox and Safari leave the message out of it (stack-fix.js)
16
+ installStackHeader(globalThis)
17
+
18
+ let glue = null
19
+ let exports = null
20
+ let turning = false
21
+ let debug = false
22
+ let role = ''
23
+ let capi = null
24
+ let counters = null
25
+
26
+ const text = (err) => String((err && err.stack) || err)
27
+
28
+ self.addEventListener('message', async (e) => {
29
+ const m = e.data
30
+ try {
31
+ if (m.type === 'init') {
32
+ checkInit(m)
33
+ debug = !!m.debug
34
+ if (debug) console.log(`[w] performance.memory ${typeof performance.memory} used ${performance.memory && performance.memory.usedJSHeapSize}`)
35
+ role = m.role
36
+ counters = installWasmCounters(globalThis) // fix7 item 15: the numbers of WebAssembly objects made by this Worker
37
+ if (m.fsTime) {
38
+ // fix5 round 6 (only with the frame's __wmdFsTime): every file call carries the time it was posted, on the clock all Workers share
39
+ const post = self.postMessage.bind(self)
40
+ self.postMessage = (msg, t) => post(msg && msg.type === 'fs' ? { ...msg, t0: performance.timeOrigin + performance.now() } : msg, t)
41
+ }
42
+ // before the runtime loads: the napi engine reads these when its module is evaluated
43
+ if (m.capi) capi = installCapi(globalThis, { channel: m.capi, scope: m.scope % 4096, relay: (msg) => self.postMessage({ type: 'capi', msg }), log: m.debug ? (t) => console.log(`[capi s${m.scope}] ${t}`) : null })
44
+ if (capi) installSerdesState(globalThis, { scope: m.scope % 4096, note: m.fsTime ? (text) => self.postMessage({ type: 'note', text }) : null })
45
+ const r = await loadRuntime({ ...m, role: m.role })
46
+ glue = r.glue
47
+ exports = r.exports
48
+ turning = r.turning
49
+ glue.wmd_set_trace(m.trace | 0)
50
+ if (m.calltrace) glue.wmd_set_calltrace(true)
51
+ if (m.napifixOff) glue.wmd_set_napifix_off(true)
52
+ // linux.cjs's `__wmdCtl(pid, json)`: one synchronous control request to the page's file route (the shim takes it off
53
+ // the global before the program runs; see src/edge/shim.js)
54
+ globalThis.__wmdCtl = (_pid, json) => glue.wmd_ctl(json)
55
+ self.postMessage({
56
+ type: 'ready',
57
+ memory: r.memory,
58
+ stdin: { addr: glue.wmd_stdin_addr(), cap: glue.wmd_stdin_cap(), off: glue.wmd_stdin_offset() },
59
+ tty: glue.wmd_tty_addr(),
60
+ })
61
+ } else if (m.type === 'counts') {
62
+ self.postMessage({ type: 'counts', seq: m.seq, role, c: counters ? counters.snapshot() : null })
63
+ } else if (m.type === 'capi') {
64
+ // another thread's share, delete or hello (the page forwards them: hub.js)
65
+ if (capi) capi.receive(m.msg)
66
+ } else if (m.type === 'task') {
67
+ try {
68
+ if (debug) console.log('[w thread] task start')
69
+ if (turning) {
70
+ // through WebAssembly.promising: the job may suspend to let this Worker's event loop run (see loader.js)
71
+ const ptr = glue.wmd_thread_prepare(m.msg)
72
+ await WebAssembly.promising(exports.wmd_job_main)(ptr)
73
+ } else {
74
+ glue.wmd_thread_entry(m.msg)
75
+ }
76
+ } catch (err) {
77
+ // a trap leaves the instance's stack and state unusable: the pool ends this Worker
78
+ self.postMessage({ type: 'crash', error: text(err) })
79
+ return
80
+ }
81
+ if (debug) console.log('[w thread] task done')
82
+ self.postMessage({ type: 'done' })
83
+ } else if (m.type === 'run') {
84
+ try {
85
+ if (debug) console.log('[w main] run start')
86
+ const run = m.node ? glue.wmd_run_node : glue.wmd_run
87
+ if (!run) throw new Error('this build has no N-API support (build edge/browser with --features napi)')
88
+ const code = run(new Uint8Array(m.program), m.args || [], m.env || [], m.opts || '')
89
+ self.postMessage({ type: 'exit', id: m.id, code, outs: glue.wmd_out_count() })
90
+ } catch (err) {
91
+ self.postMessage({ type: 'run-error', id: m.id, error: text(err), outs: glue.wmd_out_count() })
92
+ }
93
+ }
94
+ } catch (err) {
95
+ self.postMessage({ type: 'fatal', error: text(err) })
96
+ }
97
+ })
@@ -0,0 +1,162 @@
1
+ // X5 part B (page option edge=1): the page's side of container node outside the guest.
2
+ //
3
+ // runEdge() puts node in an isolated frame on another site (`origin`, one host name per container; a frame of the
4
+ // page's own site would share its process and its cookies, docs/plans/x5-browser-node.md section 6), gives the
5
+ // frame two MessagePorts to the machine's channel service (vm.edgeFs, src/boot.js) and waits for the run's
6
+ // result. The page takes only log, step and done messages from the frame, and only from the frame's own origin
7
+ // and window: what a container prints reaches the page as the result of a step, never as a page message.
8
+ //
9
+ // runEdge({vm, p9port, origin, mounts, cfg, onOut, control}) -> Promise<{...done message of src/edge/worker.js}>
10
+ // onOut(kind, bytes): the program's output as it comes (cfg.stream); control: filled with stdin/stdinEnd/signal/abort
11
+ // (abort ends the frame at once; the promise rejects). releaseYield: false when the caller counts the open runs itself.
12
+ // rt: 'own' | 'sdk' (src/edge/runtime.js) goes to the frame in the run's config; job: the service's number of this node run (children)
13
+ // timeoutMs: a limit on the whole run, none by default (check4 F1b); the watch below is what ends a run whose frame is dead
14
+ // The page watches the frame: no ready message in startTimeoutMs, a frame taken out of the page, a frame that stops answering pings
15
+ // (pingMissMs), no process in readyTimeoutMs: the run ends at once with an error that says which (rejects with err.why set).
16
+ // onLog gets log and step messages ({type:'step', name:'ready'} once the process runs)
17
+ // mounts: {id: {at: '/w', path: 'w', ro: false}}: `at` where node sees the mount, `path` the container path
18
+ // the Overlay serves there (below `root`, 'rootfs' in the guest's layout).
19
+
20
+ import { cleanRelay } from './msg.js'
21
+ import { portsOf } from './runtime.js'
22
+
23
+ let runSeq = 0
24
+ /** fix7 item 15: the frames this page made and removed (a finished program's frame is removed in `finish`); `live` is the difference. */
25
+ export const frameCounts = { created: 0, removed: 0 }
26
+
27
+ /** The error a run ends with when the frame is lost or does not start: why is one of 'start', 'ready', 'removed', 'silent', 'timeout', 'stopped', 'pagehide', 'badmsg'. */
28
+ function lost(why, text) {
29
+ const e = new Error(text)
30
+ e.why = why
31
+ return e
32
+ }
33
+
34
+ /** How long the page waits for the frame's page to load (fix7 F10; it was 30 s: the first node of a page whose frame site is down waited that long). */
35
+ export const FRAME_START_LIMIT_MS = 5000
36
+
37
+ export function runEdge({
38
+ vm, job = 0, p9port, origin, mounts, cfg, root = 'rootfs', yieldMs, onLog = () => {}, onOut = null, control = null, timeoutMs = 0, releaseYield = true,
39
+ startTimeoutMs = FRAME_START_LIMIT_MS, readyTimeoutMs = 90_000, pingMs = 1000, pingMissMs = 10_000, tickMs = 250, now = () => Date.now(), win = globalThis, doc = globalThis.document,
40
+ }) {
41
+ const svcMounts = Object.fromEntries(Object.entries(mounts).map(([id, m]) => [id, { path: m.path, ro: !!m.ro }]))
42
+ const run = ++runSeq
43
+ const wish = portsOf(cfg.rt) // how many ports the runtime uses and whether they carry its own file messages (src/edge/runtime.js)
44
+ const ports = vm.edgeFs({ port: p9port, mounts: svcMounts, root, count: wish.count, own: wish.own, job, yieldMs, run, kickAll: !!globalThis.__wmdKickAll })
45
+ const runCfg = { ...cfg, mounts: Object.entries(mounts).map(([id, m]) => [m.at, Number(id), !!m.ro]) }
46
+ return new Promise((resolve, reject) => {
47
+ const f = doc.createElement('iframe')
48
+ frameCounts.created++
49
+ f.allow = 'cross-origin-isolated'
50
+ f.src = origin + '/edge/frame.html'
51
+ let ended = false
52
+ let sawReady = false // the frame's script runs (it posted x5-frame-ready)
53
+ let started = false // the program runs (step ready)
54
+ let lastPong = 0
55
+ let pingSeq = 0
56
+ const timers = []
57
+ const post = (msg, transfer) => {
58
+ try {
59
+ f.contentWindow && f.contentWindow.postMessage(msg, origin, transfer)
60
+ } catch {
61
+ // a frame that is gone takes no messages
62
+ }
63
+ }
64
+ // `control` (an object the caller passes) gets stdin(bytes), stdinEnd() and signal(n) for the running program
65
+ if (control) {
66
+ control.stdin = bytes => post({ x5edge: 'in', in: { stdin: bytes } })
67
+ control.stdinEnd = () => post({ x5edge: 'in', in: { stdinEnd: true } })
68
+ control.signal = n => post({ x5edge: 'in', in: { signal: n } })
69
+ control.abort = () => finish(reject, lost('stopped', 'stopped'))
70
+ control.alive = () => !ended && f.isConnected !== false && !!f.contentWindow
71
+ }
72
+ const finish = (fn, v) => {
73
+ if (ended) return
74
+ ended = true
75
+ for (const t of timers) (win.clearTimeout(t), win.clearInterval(t))
76
+ win.removeEventListener('message', onMessage)
77
+ win.removeEventListener('pagehide', onHide)
78
+ post({ x5edge: 'stop' }) // the frame ends its worker before it goes (check3 finding 6c)
79
+ try {
80
+ f.remove()
81
+ } catch {
82
+ // already out of the page
83
+ }
84
+ frameCounts.removed++
85
+ vm.edgeRelease?.(run) // the service closes this run's ports and open files
86
+ if (releaseYield) vm.edgeYield(0) // the ports are closed: the service's yield goes back to its default
87
+ fn(v)
88
+ }
89
+ const onMessage = ({ data, origin: o, source }) => {
90
+ if (ended || o !== origin || source !== f.contentWindow) return
91
+ if (data === 'x5-frame-ready') {
92
+ if (sawReady) return
93
+ sawReady = true
94
+ lastPong = now()
95
+ post({ x5edge: 'start', cfg: runCfg, ports }, ports)
96
+ return
97
+ }
98
+ if (data === 'x5-pong') return void (lastPong = now())
99
+ try {
100
+ const r = cleanRelay(data && data.x5relay) // every field is checked here: a bad message ends this run, never the machine (check4 F2)
101
+ if (!r) return
102
+ lastPong = now()
103
+ if (r.type === 'done') return finish(resolve, r)
104
+ if (r.type === 'out') return onOut?.(r.kind, r.bytes)
105
+ if (r.type === 'step' && r.name === 'ready') started = true
106
+ onLog(r)
107
+ } catch (e) {
108
+ finish(reject, lost('badmsg', `the frame sent a bad message: ${String((e && e.message) || e).split('\n')[0].slice(0, 200)}`))
109
+ }
110
+ }
111
+ // a page that goes away (reload, navigation, close) ends the run first: Firefox does not finish loading the next page while the frame's Workers still run
112
+ // A page that may come back (pagehide with persisted: true, the back-forward cache) does not end the run: if the frame is gone when it
113
+ // comes back, the ping watch says so. A run ended here says why and gives exit 125, as a lost frame does (check4 F4).
114
+ const onHide = ev => {
115
+ if (ev && ev.persisted) return
116
+ finish(reject, lost('pagehide', 'the page was closed or reloaded'))
117
+ }
118
+ win.addEventListener('message', onMessage)
119
+ win.addEventListener('pagehide', onHide)
120
+ // the watch: a frame that never loads (its server is down), that is taken out of the page, that stops answering, or whose program
121
+ // does not start must end the run now, with the reason, not leave the guest's command waiting
122
+ let lastPing = 0
123
+ // The page's own timers can be slow or stopped (a hidden tab, a frozen one, a laptop that slept) while the frame is healthy. The watch's
124
+ // period is the ping cadence. A timer that fires later than two periods after it was due means the page was not awake: it starts its
125
+ // window again (and a start or ready limit starts again) instead of calling the frame silent for the page's own sleep (check4 F5).
126
+ const period = Math.max(tickMs, pingMs)
127
+ const arm = (ms, fire) => {
128
+ const due = now() + ms
129
+ const t = win.setTimeout(() => {
130
+ if (ended) return
131
+ if (now() - due > 2 * period) return void arm(ms, fire) // the page was asleep: the limit starts again
132
+ fire()
133
+ }, ms)
134
+ timers.push(t)
135
+ }
136
+ arm(startTimeoutMs, () => !sawReady && finish(reject, lost('start', `the frame did not load in ${startTimeoutMs} ms (is its server up?)`)))
137
+ arm(readyTimeoutMs, () => !started && finish(reject, lost('ready', `node did not start in ${readyTimeoutMs} ms`)))
138
+ // no limit on the whole run unless the caller sets one (a node server or a long job runs as long as it does in the guest): the pings are what tell a dead frame
139
+ if (timeoutMs > 0) timers.push(win.setTimeout(() => finish(reject, lost('timeout', `the frame gave no result in ${timeoutMs} ms`)), timeoutMs))
140
+ let lastTick = now()
141
+ timers.push(
142
+ win.setInterval(() => {
143
+ if (ended) return
144
+ const t = now()
145
+ const late = t - lastTick > 2 * period
146
+ lastTick = t
147
+ if (f.isConnected === false) return finish(reject, lost('removed', 'the frame was taken out of the page'))
148
+ if (!sawReady) return
149
+ if (late) {
150
+ lastPong = t // the page was not awake: the frame had no chance to be heard. Ask now and give it a full window.
151
+ lastPing = 0
152
+ }
153
+ if (t - lastPong > pingMissMs) return finish(reject, lost('silent', `the frame has not answered in ${pingMissMs} ms`))
154
+ if (t - lastPing >= pingMs) {
155
+ lastPing = t
156
+ post({ x5edge: 'ping', n: ++pingSeq })
157
+ }
158
+ }, tickMs),
159
+ )
160
+ doc.body.append(f)
161
+ })
162
+ }
@@ -0,0 +1,65 @@
1
+ // X5 part B (switch edge=1): the page's plan for container node outside the guest (docs/plans/x5-browser-node.md section 5).
2
+ // The page takes the path only when every row of the table holds; otherwise it adds no mounts and the container is exactly
3
+ // as without the switch. The runtime (page option rt, src/edge/runtime.js) is part of it: rt=own with no own runtime in the build is a row
4
+ // of its own, and the container runs in the guest.
5
+ // (The edge host answers {fallback:true} for the cases only the hello shows: src/host/edge-host.js.)
6
+ // The rows are the desktop's planEdge (internal/engine/edge.go:403 to 445), with one browser difference: a container that
7
+ // asks for checkpoints still takes the path (the page refuses vm.checkpoint() while an edge program runs).
8
+ import { RT_DEFAULT, unavailable } from './runtime.js'
9
+
10
+ /** Where images keep node, in the order the desktop looks (internal/engine/edge.go nodePaths). */
11
+ export const NODE_PATHS = ['/usr/local/bin/node', '/usr/bin/node']
12
+ /** The Edge.js build's node major: the only one the path runs. */
13
+ export const NODE_MAJOR = '24'
14
+ // the spec mounts of a node outside the guest live in src/host/ctl.js (the bundle builder, which a page with the switch off loads anyway: check5 F8)
15
+ export { EDGE_CONTAINER_DIR, EDGE_GUEST_DIR, EDGE_STUB, edgeSpecMounts } from '../host/ctl.js'
16
+
17
+ const envValue = (env, key) => {
18
+ for (const kv of env || []) if (kv.startsWith(key + '=')) return kv.slice(key.length + 1)
19
+ return undefined
20
+ }
21
+
22
+ /** The major of an image's node from its env's NODE_VERSION ("24.22.3", "v24.1.0"), or ''. */
23
+ export function nodeMajor(env) {
24
+ const v = (envValue(env, 'NODE_VERSION') || '').trim().replace(/^v/, '')
25
+ const major = v.split('.')[0]
26
+ return /^\d+$/.test(major) ? major : ''
27
+ }
28
+
29
+ /**
30
+ * The image's node version as node writes it ("v24.22.3"), from the image's NODE_VERSION as the desktop reads it (internal/engine/edge.go
31
+ * imageNodeVersion); '' when it is not a release version. The frame's node reports it (check5 F5, src/edge/shim.js).
32
+ */
33
+ export function nodeVersion(env) {
34
+ const v = (envValue(env, 'NODE_VERSION') || '').trim().replace(/^v/, '')
35
+ return /^\d+\.\d+\.\d+$/.test(v) ? 'v' + v : ''
36
+ }
37
+
38
+ /**
39
+ * @param {object} o
40
+ * @param {boolean} o.enabled the page switch (edge=1)
41
+ * @param {string[]} [o.env] the container's environment
42
+ * @param {string} [o.user] the container's user ("", "0", "root", "0:0" or other)
43
+ * @param {boolean} [o.readonlyRoot]
44
+ * @param {boolean} [o.hasTmpfs] the container has tmpfs mounts (the desktop refuses them too)
45
+ * @param {boolean} [o.hasJspi] the browser runs the SDK (JSPI, wasm exceptions, SharedArrayBuffer): the page checks at start
46
+ * @param {string} [o.rt] the runtime the page chose (src/edge/runtime.js); default: the default runtime
47
+ * @param {string} [o.nodePath] where the image's node is (an ELF file the page found, one of NODE_PATHS), or ''
48
+ * @returns {{use: boolean, node?: string, reason?: string}}
49
+ */
50
+ export function planEdge(o) {
51
+ const no = reason => ({ use: false, reason })
52
+ if (!o.enabled) return no('the switch is off')
53
+ if (envValue(o.env, 'WMD_EDGE') === '0') return no('the container says WMD_EDGE=0')
54
+ if (o.hasTmpfs) return no('tmpfs mounts')
55
+ if (o.readonlyRoot) return no('read-only root')
56
+ const user = (o.user || '').split(':')[0]
57
+ if (user !== '' && user !== '0' && user !== 'root') return no('not root')
58
+ if (o.hasJspi === false) return no('the browser lacks JSPI, wasm exceptions or SharedArrayBuffer')
59
+ const rtWhy = unavailable(o.rt || RT_DEFAULT)
60
+ if (rtWhy) return no(rtWhy)
61
+ if (!o.nodePath) return no('no node in the image')
62
+ if (nodeMajor(o.env) !== NODE_MAJOR) return no(`image node major ${nodeMajor(o.env) || 'unknown'}, not ${NODE_MAJOR}`)
63
+ return { use: true, node: o.nodePath }
64
+ }
65
+
@@ -0,0 +1,44 @@
1
+ // X5 part B (switch edge=1): path resolution inside a container's root, shared by the file route and the control requests.
2
+ import { ELOOP, ENOTDIR, fail } from '../fs/errno.js'
3
+ import { MAX_SYMLINKS } from '../fs/overlay.js'
4
+ import { S_IFLNK } from '../fs/pack.js'
5
+
6
+ /**
7
+ * The inode `path` leads to, starting at `start`, following symlinks as a process chrooted to `root` would (an
8
+ * absolute target starts at `root`; `..` never leaves it); the last one only when follow is set. Overlay.resolve
9
+ * does the same from the Overlay's root, which is above the container's root when the layers show under
10
+ * `at: 'rootfs'`, so it cannot be used here.
11
+ */
12
+ export function resolveIn(fs, root, start, path, follow = true) {
13
+ let links = 0
14
+ let cur = start
15
+ let parts = path.split('/').filter(s => s !== '')
16
+ let i = 0
17
+ while (i < parts.length) {
18
+ const name = parts[i]
19
+ const last = i === parts.length - 1
20
+ if (!cur.isDir()) fail(ENOTDIR)
21
+ if (name === '.') {
22
+ i++
23
+ continue
24
+ }
25
+ if (name === '..') {
26
+ cur = cur === root ? root : cur.parent || root
27
+ i++
28
+ continue
29
+ }
30
+ const c = fs.lookup(cur, name)
31
+ if (c.type === S_IFLNK && (!last || follow)) {
32
+ if (++links > MAX_SYMLINKS) fail(ELOOP)
33
+ if (c.target.startsWith('/')) cur = root
34
+ parts = c.target.split('/').filter(s => s !== '').concat(parts.slice(i + 1))
35
+ i = 0
36
+ if (parts.length === 0) return cur
37
+ continue
38
+ }
39
+ if (last) return c
40
+ cur = c
41
+ i++
42
+ }
43
+ return cur
44
+ }
@@ -0,0 +1,94 @@
1
+ // X5 part B (switch edge=1): the runtime seam. This is the only module that names a runtime. A runtime is an adapter in its own
2
+ // folder that gives the frame's worker five things (load, start, signal, exit, teardown; see src/edge/sdk/adapter.js for their shapes).
3
+ //
4
+ // rt=own wmd's own runtime (src/edge/own/, built by edge/browser), the default. The frame loads its files from the frame's site:
5
+ // /own/ (the build output) and /edge/own/ (the Worker script).
6
+ // rt=sdk a published SDK, behind an adapter (src/edge/sdk/), a named arm for a test that compares speed. Nothing of the SDK is in
7
+ // this repository or its build: the arm runs only when the page's caller hands it in (handSdk: the page option sdkBase gives
8
+ // the URL the frame's site serves the SDK under). Without one, rt=sdk is the same row as a runtime that is not in the build:
9
+ // node runs in the guest and the page says why (see unavailable()).
10
+ //
11
+ // Nothing else in src/edge names a runtime.
12
+
13
+ const LOADERS = {
14
+ own: () => import('./own/adapter.js'),
15
+ sdk: null, // set by handSdk(), on the page and in the frame
16
+ }
17
+
18
+ export const RT_DEFAULT = 'own'
19
+ export const RT_NAMES = () => Object.keys(LOADERS)
20
+
21
+ /** Where a runtime is put in: a fake adapter in a test, or an arm a caller hands in. loader() resolves to an adapter module. */
22
+ export function registerRuntime(name, loader) {
23
+ LOADERS[name] = loader
24
+ }
25
+
26
+ /**
27
+ * The caller hands the SDK in: `base` is the URL path the frame's site serves the published SDK under (no file of it is in the repository).
28
+ * Returns the config the frame needs for it ({rtBase}).
29
+ */
30
+ export function handSdk(base) {
31
+ if (typeof base !== 'string' || !base.startsWith('/') || !base.endsWith('/')) throw new Error("sdkBase must be a path that starts and ends with '/'")
32
+ LOADERS.sdk = () => import('./sdk/adapter.js')
33
+ return { rtBase: base }
34
+ }
35
+
36
+ /**
37
+ * The page's options as the runtime they choose: `get` reads a page option (q.get). Returns {rt, handIn}: handIn is what a caller handed in
38
+ * (the page option sdkBase for rt=sdk), or null; give it to the bridge, which gives it to the frame's config (runtimeConfig).
39
+ */
40
+ export function pageRuntime(get) {
41
+ const base = get('sdkBase')
42
+ // fsTime=1 (fix5 round 6): the own runtime counts its file calls (off otherwise); it travels in handIn to runtimeConfig
43
+ const fsTime = get('fsTime') === '1'
44
+ return { rt: parseRt(get('rt')), handIn: base || fsTime ? { ...(base ? handSdk(base) : {}), fsTime } : null }
45
+ }
46
+
47
+ /** The page option rt as a runtime name: '' or absent is the default; anything else is returned as given (unavailable() then refuses it). */
48
+ export function parseRt(v) {
49
+ return v == null || v === '' ? RT_DEFAULT : String(v)
50
+ }
51
+
52
+ /** Why this runtime cannot run node in the frame, or '' when it can. */
53
+ export function unavailable(rt) {
54
+ if (!Object.hasOwn(LOADERS, rt)) return `rt=${rt}: no such runtime (rt=${RT_NAMES().join('|')})`
55
+ if (!LOADERS[rt]) return rt === 'sdk' ? "rt=sdk: no SDK was handed in (the page option sdkBase), it is not in this build, node runs in the guest" : `rt=${rt}: the runtime is not in this build, node runs in the guest`
56
+ return ''
57
+ }
58
+
59
+ /**
60
+ * What the page gives the frame's config for runtime `rt` beside its name: the files of the own runtime, the SDK's base path when a caller
61
+ * handed one in. `handIn` is what pageRuntime returned.
62
+ */
63
+ export function runtimeConfig(rt, handIn = null) {
64
+ if (rt === 'own') return { own: { wasmUrl: '/own/wmd_browser_bg.wasm', glueUrl: '/own/wmd_browser.js', workerUrl: '/edge/own/worker.js', ...(handIn && handIn.fsTime ? { fsTime: true } : {}) } }
65
+ if (rt === 'sdk' && handIn && handIn.rtBase) return { rtBase: handIn.rtBase }
66
+ return {}
67
+ }
68
+
69
+ /** The runtime's wishes of the page's side of the file route: how many MessagePorts it uses and whether they speak the own runtime's messages. */
70
+ export function portsOf(rt) {
71
+ return rt === 'own' ? { count: 1, own: true } : { count: 2, own: false }
72
+ }
73
+
74
+ /** The runtime has real children (the guest runs a child through the stub), so the plan does not send a program that needs them to the guest. */
75
+ export const runsChildren = rt => rt === 'own'
76
+
77
+ /** The runtime's file route pages a listing, so a directory over the bridge's reply cap is no reason to send the container to the guest. */
78
+ export const pagesListings = rt => rt === 'own'
79
+ /** True when the runtime hands a signal to the program (a handler runs, or the program ends as node does): the bridge passes the signal's own number (check5 F2 on rt=own: SIGHUP to a handler). */
80
+ export const deliversSignals = rt => rt === 'own'
81
+
82
+ /** The adapter module of runtime `rt` (the frame's worker calls this; `cfg` is the run's config, which carries the SDK's base when one was handed in). */
83
+ export async function loadAdapter(rt, cfg = null) {
84
+ if (rt === 'sdk' && !LOADERS.sdk && cfg && typeof cfg.rtBase === 'string') {
85
+ try {
86
+ handSdk(cfg.rtBase) // the frame is a document of its own: the page's hand-in reaches it in the config
87
+ } catch {
88
+ // a base that is not a path is not taken
89
+ }
90
+ }
91
+ const why = unavailable(rt)
92
+ if (why) throw new Error(why)
93
+ return LOADERS[rt]()
94
+ }