@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,382 @@
1
+ // X5 part B (page switch edge=1 only): the channel service's side of container node outside the guest. The EdgeHost
2
+ // (src/host/edge-host.js) asks `start(hello)` for each node the guest's stub hands over. This looks at the container's tree
3
+ // (it is the Overlay the guest's 9P reads), decides the cases only the tree shows, and asks the page to run node:
4
+ //
5
+ // service -> page {t:'edge', ev:'start', id, hello, mounts: [{at, path}], planMs}
6
+ // {t:'edge', ev:'stdin', id, bytes} | 'stdin-end' | 'signal' {n} | 'signal-taken' {n, handled} | 'gone'
7
+ // page -> service {t:'edge-to', id, ev:'reply', ok:true | fallback:'why'}, {ev:'out', kind, bytes}, {ev:'exit', code, signal?}
8
+ //
9
+ // What the tree decides (section 5 of docs/plans/x5-browser-node.md): a native addon (a `.node` file) in node's search path,
10
+ // and a directory whose listing the SDK's bridge cannot carry (the desktop has neither limit on the second). The page decides
11
+ // the rest (src/edge/plan.js) and the stub the hello's own cases (edge-host.js helloRefusal).
12
+
13
+ import { EdgeFsRoute } from './fs-route.js'
14
+ import { resolveIn } from './resolve.js'
15
+ import { byteStr } from '../fs/pack.js'
16
+ import { parseNodeArgs, parseNodeOptions, programKey } from './node-args.js'
17
+ import { BadMessage, KINDS_OUT, bytesView, exitCodeOf, text } from './msg.js'
18
+ import { pagesListings, runsChildren } from './runtime.js'
19
+ import { guestOption } from './node-guest-opts.js'
20
+
21
+ const utf8 = s => new TextDecoder().decode(Uint8Array.from(s, c => c.charCodeAt(0)))
22
+ /** Container top-level names the SDK has its own for, or the guest mounts over. */
23
+ const SKIP = new Set(['proc', 'sys', 'dev'])
24
+
25
+ /** The container's top-level directories, each as a mount at its own path. [{at: '/usr', path: 'usr'}] */
26
+ export function topLevelMounts(fs, root) {
27
+ const out = []
28
+ const { names, nodes } = fs.listing(root)
29
+ for (let i = 0; i < names.length; i++) {
30
+ const n = utf8(names[i])
31
+ if (SKIP.has(n) || !nodes[i].isDir()) continue // a link at the top (/bin -> usr/bin) is not a directory a mount can stand on
32
+ out.push({ at: '/' + n, path: n })
33
+ }
34
+ return out
35
+ }
36
+
37
+ /**
38
+ * The first native addon (a .node file) in the node_modules directories node would search from `cwd`, as a path, or ''.
39
+ * The desktop swaps known addons for wasm builds (internal/edge/addons.go addonCheck); the browser has no swap, so any addon
40
+ * sends the program to the guest's own node.
41
+ */
42
+ export function findAddon(fs, rootNode, cwd) {
43
+ const parts = String(cwd || '/').split('/').filter(Boolean)
44
+ const seen = new Set()
45
+ for (let i = parts.length; i >= 0; i--) {
46
+ const dir = '/' + parts.slice(0, i).join('/')
47
+ const nm = (dir === '/' ? '' : dir) + '/node_modules'
48
+ if (seen.has(nm)) continue
49
+ seen.add(nm)
50
+ let start
51
+ try {
52
+ start = resolveIn(fs, rootNode, rootNode, byteStr(nm), true)
53
+ } catch {
54
+ continue
55
+ }
56
+ if (!start.isDir()) continue
57
+ const found = walk(fs, start, nm)
58
+ if (found) return found
59
+ }
60
+ return ''
61
+ }
62
+
63
+ function walk(fs, dir, path) {
64
+ const { names, nodes } = fs.listing(dir)
65
+ for (let i = 0; i < names.length; i++) {
66
+ const n = nodes[i]
67
+ const name = utf8(names[i])
68
+ if (name.endsWith('.node') && !n.isDir()) return path + '/' + name
69
+ if (n.isDir()) {
70
+ const f = walk(fs, n, path + '/' + name)
71
+ if (f) return f
72
+ }
73
+ }
74
+ return ''
75
+ }
76
+
77
+ // Children. The runtime in the frame cannot start a process (a spawn is ENOEXEC: web/test/edge-bar/ has the test the next runtime must
78
+ // pass). The desktop's node runs children in the container through the stub's exec streams (guest/container2wasm/cmd/edgestub); the
79
+ // browser's runtime has no such call to forward. So the plan declines the hand-off, and node runs in the guest, for a program that needs
80
+ // children, as far as the tree and the hello show it. How it knows (a program that spawns from deep inside a dependency is not seen):
81
+ // 1. the program is a package manager whose command runs scripts: npm, npx, yarn, pnpm (run, test, start, exec, ...);
82
+ // 2. an npm install-type command (ci, install, rebuild, ...) with lifecycle scripts in play: the project's package.json has one
83
+ // (preinstall, install, postinstall, prepublish, preprepare, prepare, postprepare), the lock marks a package hasInstallScript, there is
84
+ // no lock to look at, or packages are named on the command line; --ignore-scripts or npm_config_ignore_scripts=true says there are none;
85
+ // 3. the program's own file (argv[1], up to 1 MiB) or its -e/-p code mentions child_process.
86
+ const PM = /^(npm|npx|yarn|yarnpkg|pnpm|pnpx|corepack)(-cli|-prefix)?(\.c?js)?$/
87
+ const NPM = /^(npm|npx)(-cli|-prefix)?(\.c?js)?$/
88
+ const NPM_RUNS = new Set(['run', 'run-script', 'rum', 'urn', 'test', 'tst', 't', 'start', 'stop', 'restart', 'exec', 'x', 'create', 'init', 'explore', 'version', 'publish', 'pack', 'link', 'ln'])
89
+ const NPM_INSTALLS = new Set(['ci', 'clean-install', 'ic', 'install', 'i', 'in', 'ins', 'add', 'install-test', 'it', 'update', 'up', 'upgrade', 'rebuild', 'rb', 'dedupe', 'ddp', 'prune'])
90
+ const LIFECYCLE = ['preinstall', 'install', 'postinstall', 'prepublish', 'preprepare', 'prepare', 'postprepare']
91
+ const MAX_SCAN = 1 << 20
92
+
93
+ function readText(fs, rootNode, cwd, path) {
94
+ const from = path.startsWith('/') ? rootNode : resolveIn(fs, rootNode, rootNode, byteStr(cwd || '/'), true)
95
+ const n = resolveIn(fs, rootNode, from, byteStr(path), true)
96
+ if (n.isDir()) return null
97
+ const size = Math.min(fs.size(n), MAX_SCAN + 1)
98
+ return { text: new TextDecoder().decode(fs.read(n, 0, size)), whole: fs.size(n) <= MAX_SCAN }
99
+ }
100
+ const tryText = (fs, rootNode, cwd, path) => {
101
+ try {
102
+ return readText(fs, rootNode, cwd, path)
103
+ } catch {
104
+ return null
105
+ }
106
+ }
107
+
108
+ /** The option that makes node print its own text and run nothing (--version and the like), or ''. */
109
+ export const printsOwnText = hello => parseNodeArgs(hello).printed
110
+
111
+ /** Why this node run needs child processes, or '' (see the list above). */
112
+ export { programKey }
113
+
114
+ /** npm commands that start a process or a browser whatever the project holds (man, a browser, an editor, a shell, a doctor's git and node checks). */
115
+ const NPM_STARTS = new Set(['help', 'help-search', 'docs', 'home', 'bugs', 'repo', 'edit', 'explore', 'doctor', 'login', 'adduser', 'logout', 'completion', 'fund', 'star', 'stars', 'whoami-browser'])
116
+
117
+ /**
118
+ * Why this node run needs child processes, or '' (see the list above). This is the look for a runtime that cannot start one (the SDK's): the
119
+ * options of the command line and of the container's NODE_OPTIONS, the program and each preload file, and for npm the command and the project.
120
+ */
121
+ export function childrenReason(fs, rootNode, hello) {
122
+ const cwd = hello.cwd || '/'
123
+ const { prog, code, rest, run, test, watch, sea, preloads } = parseNodeArgs(hello)
124
+ const fromEnv = parseNodeOptions(hello.env)
125
+ // options that start a process of their own (check5 F2): --run runs a script of package.json in a shell, --test a child per test file, --watch a child that
126
+ // runs the program again, a sea config build the node binary. In NODE_OPTIONS node refuses these; they are looked at too, in case a later node takes them.
127
+ if (run) return `node --run runs the script ${run} of package.json in a shell`
128
+ if (test || fromEnv.test) return 'node --test starts a child process per test file'
129
+ if (watch || fromEnv.watch) return 'node --watch starts a child process that runs the program again'
130
+ if (sea || fromEnv.sea) return 'node --experimental-sea-config runs a build step in a child process'
131
+ if (/child_process/.test(code)) return 'the -e or -p code uses child_process'
132
+ // a preload (-r, --require, --import, --loader, --experimental-loader), from the command line or from the container's NODE_OPTIONS (check5 F3), runs
133
+ // before the program: it is looked at as the program is
134
+ for (const f of [...preloads, ...fromEnv.preloads]) {
135
+ if (!f || f.startsWith('-')) continue
136
+ const t = f.startsWith('.') || f.startsWith('/') ? tryText(fs, rootNode, cwd, f) : null // a bare name is a package: its text is not looked at here
137
+ if (t && /child_process/.test(t.text)) return `the preload ${f} uses child_process`
138
+ }
139
+ if (prog) {
140
+ const base = prog.split('/').pop()
141
+ if (PM.test(base) || /\/node_modules\/(npm|yarn|pnpm)\/(bin|lib)\//.test(prog)) {
142
+ const isNpm = NPM.test(base) || /\/node_modules\/npm\//.test(prog)
143
+ if (!isNpm) return `${base} runs package scripts`
144
+ if (base.startsWith('npx')) return 'npx runs a command in a child process'
145
+ const words = rest.filter(a => !a.startsWith('-'))
146
+ const start = words.find(a => NPM_STARTS.has(a))
147
+ if (start) return `npm ${start} starts a process or a browser`
148
+ const hit = rest.find(a => NPM_RUNS.has(a))
149
+ if (hit) return `npm ${hit} runs a script in a child process`
150
+ const cmd = rest.find(a => NPM_INSTALLS.has(a))
151
+ if (!cmd) return '' // npm ls, npm config, npm pack --dry-run ...: no script runs
152
+ const env = (hello.env || []).includes('npm_config_ignore_scripts=true')
153
+ if (env || rest.includes('--ignore-scripts')) return ''
154
+ if (words.length > words.indexOf(cmd) + 1 && cmd !== 'ci') return `npm ${cmd} with packages named: their install scripts are not known`
155
+ const pkg = tryText(fs, rootNode, cwd, 'package.json')
156
+ let workspaces = false
157
+ if (pkg) {
158
+ try {
159
+ const j = JSON.parse(pkg.text)
160
+ const scripts = j.scripts || {}
161
+ const l = LIFECYCLE.find(k => Object.hasOwn(scripts, k))
162
+ if (l) return `the project's package.json has a ${l} script`
163
+ workspaces = Array.isArray(j.workspaces) ? j.workspaces.length > 0 : !!(j.workspaces && Array.isArray(j.workspaces.packages) && j.workspaces.packages.length)
164
+ } catch {
165
+ return 'package.json does not parse'
166
+ }
167
+ }
168
+ const lock = tryText(fs, rootNode, cwd, 'package-lock.json')
169
+ if (!lock) return `npm ${cmd} with no package-lock.json: the packages' install scripts are not known`
170
+ try {
171
+ const pk = JSON.parse(lock.text).packages || {}
172
+ for (const k of Object.keys(pk)) {
173
+ const e = pk[k]
174
+ if (e && e.hasInstallScript) return `the lock marks ${k || 'the project'} hasInstallScript`
175
+ // npm starts git for a package that comes from a git repository, and runs its prepare script
176
+ if (e && typeof e.resolved === 'string' && /^(git\+|git:|github:|git@)/.test(e.resolved)) return `the lock has ${k || 'a package'} from a git repository: npm starts git`
177
+ // a workspace package's own lifecycle scripts run at the install
178
+ if (workspaces && e && !k.includes('node_modules') && k) {
179
+ const w = tryText(fs, rootNode, cwd, `${k}/package.json`)
180
+ if (w) {
181
+ try {
182
+ const sc = JSON.parse(w.text).scripts || {}
183
+ const l = LIFECYCLE.find(x => Object.hasOwn(sc, x))
184
+ if (l) return `the workspace ${k} has a ${l} script`
185
+ } catch {
186
+ return `the workspace ${k}'s package.json does not parse`
187
+ }
188
+ }
189
+ }
190
+ }
191
+ if (workspaces && !Object.keys(pk).some(k => k && !k.includes('node_modules'))) return 'the project has workspaces that the lock does not list: their scripts are not known'
192
+ } catch {
193
+ return 'package-lock.json does not parse'
194
+ }
195
+ return ''
196
+ }
197
+ const f = tryText(fs, rootNode, cwd, prog)
198
+ if (f && /child_process/.test(f.text)) return `${prog} uses child_process`
199
+ }
200
+ return ''
201
+ }
202
+
203
+ /**
204
+ * @param {object} o
205
+ * @param {import('../fs/overlay.js').Overlay} o.fs
206
+ * @param {string} o.root where the container's root is in the Overlay ('rootfs')
207
+ * @param {(msg: object) => void} o.post to the page
208
+ */
209
+ export class EdgeService {
210
+ constructor({ fs, root = 'rootfs', post, now = () => performance.now(), rt = '' }) {
211
+ this.fs = fs
212
+ this.rt = rt // the page's runtime (src/edge/runtime.js): what it can do decides which cases the look at the tree sends to the guest
213
+ this.root = root
214
+ this.post = post
215
+ this.now = now
216
+ this.next = 1
217
+ this.jobs = new Map() // id -> {resolve, runner}
218
+ this.stats = { starts: 0, planMs: 0, planMsMax: 0, outBytes: { stdout: 0, stderr: 0 }, exitsSeen: 0 } // the look at the tree before each start (addons, listing sizes)
219
+ this.refused = new Map() // programKey -> the command an earlier run of it tried to start in the frame (the frame's runtime cannot start one)
220
+ }
221
+
222
+ /**
223
+ * A raw stream to the exec service of the stub that started run `id` (what the own runtime's child spawner is given), or a throw when the run is
224
+ * not open or its stub is gone.
225
+ */
226
+ openExec(id) {
227
+ const job = this.jobs.get(id)
228
+ if (!job || !job.openExec) throw Object.assign(new Error('no stub for this run'), { code: 'ESRCH' })
229
+ return job.openExec()
230
+ }
231
+
232
+ /** EdgeHost's start(hello, {openExec}). */
233
+ start(hello, ctx = {}) {
234
+ const t0 = this.now()
235
+ this.stats.starts++
236
+ const rootNode = this.fs.resolve(this.root)
237
+ const mounts = topLevelMounts(this.fs, rootNode)
238
+ const addon = findAddon(this.fs, rootNode, hello.cwd)
239
+ const lookMs = () => {
240
+ const d = this.now() - t0
241
+ this.stats.planMs += d
242
+ this.stats.planMsMax = Math.max(this.stats.planMsMax, d)
243
+ }
244
+ if (addon) return lookMs(), Promise.resolve({ fallback: `a native addon in node's search path (${addon})` })
245
+ // Options that print node's own text (its version, help, V8's options) come from the program, which is Edge.js's build and not the image's node
246
+ // (check5 F5): the image's own node answers them.
247
+ const printed = printsOwnText(hello)
248
+ if (printed) return lookMs(), Promise.resolve({ fallback: `node ${printed} prints the node build's own text: the image's node answers it` })
249
+ // Options the frame's node does not run as the image's does (fix7 F5, F17): the image's own node runs them, the reason is counted.
250
+ const odd = guestOption(hello)
251
+ if (odd) return lookMs(), Promise.resolve({ fallback: `node ${odd.name}: ${odd.why}; the image's node runs it` })
252
+ // A runtime whose children run in the guest through the stub (rt=own) needs none of the looks below: a program that starts a process
253
+ // gets it. The SDK's runtime cannot start one, so the tree and the hello decide, as far as they show it.
254
+ const key = programKey(hello)
255
+ if (!runsChildren(this.rt)) {
256
+ let kids = ''
257
+ try {
258
+ kids = childrenReason(this.fs, rootNode, hello)
259
+ } catch {
260
+ kids = '' // a look that fails decides nothing
261
+ }
262
+ if (kids) return lookMs(), Promise.resolve({ fallback: `needs child processes: ${kids}` })
263
+ const earlier = key === null ? undefined : this.refused.get(key) // no key: no process can start (--version, --help)
264
+ if (earlier !== undefined) return lookMs(), Promise.resolve({ fallback: `an earlier run of this program started a process (${earlier}): node in the frame cannot, so it runs in the guest` })
265
+ }
266
+ let big = []
267
+ if (!pagesListings(this.rt)) {
268
+ const byId = Object.fromEntries(mounts.map((m, i) => [i + 1, { path: m.path, ro: false }]))
269
+ big = new EdgeFsRoute(this.fs, { mounts: byId, root: this.root }).oversizeDirs()
270
+ }
271
+ lookMs()
272
+ if (big.length) return Promise.resolve({ fallback: `${big[0].path} has ${big[0].entries} entries; the runtime's file bridge cannot list a directory over its 512 KiB reply cap` })
273
+ const id = this.next++
274
+ const job = { runner: null, key, openExec: ctx.openExec || null }
275
+ this.jobs.set(id, job)
276
+ return new Promise(resolve => {
277
+ job.resolve = resolve
278
+ this.post({ t: 'edge', ev: 'start', id, hello, mounts, planMs: this.now() - t0 })
279
+ })
280
+ }
281
+
282
+ /**
283
+ * A message from the page. Never throws: every field is checked here (the page's bridge sends what a frame made, src/edge/msg.js), and a
284
+ * message that fails, or a callback that throws on it, ends that one run (exit 125, the reason on stderr), never the channel service.
285
+ */
286
+ message(m) {
287
+ let job
288
+ try {
289
+ if (!m || typeof m !== 'object') return
290
+ job = this.jobs.get(m.id)
291
+ if (!job) return
292
+ this.handle(job, m)
293
+ } catch (e) {
294
+ let id
295
+ try {
296
+ id = m.id
297
+ } catch {
298
+ // a message whose id cannot be read belongs to no run
299
+ }
300
+ this.abort(id, e)
301
+ }
302
+ }
303
+
304
+ /** End one run because a message of it was bad or a callback threw: the guest's command gets exit 125 with the reason on stderr. */
305
+ abort(id, err) {
306
+ const job = this.jobs.get(id)
307
+ if (!job) return
308
+ this.jobs.delete(id)
309
+ const why = String((err && err.message) || err).split('\n')[0].slice(0, 200)
310
+ const r = job.runner
311
+ if (!r) return void job.resolve?.({ fallback: `a bad message from the page: ${why}` })
312
+ const end = () => {
313
+ // each call has its own try: a callback that threw on the message may throw again, and the exit must still go out
314
+ try {
315
+ r.onOut?.('stderr', new TextEncoder().encode(`wmd: node's frame ended: a bad message: ${why}\n`))
316
+ } catch {
317
+ // the guest's side may be gone: nothing to tell
318
+ }
319
+ try {
320
+ r.onExit?.({ code: 125 })
321
+ } catch {
322
+ // as above
323
+ }
324
+ }
325
+ if (job.held) job.held.push(end)
326
+ else end()
327
+ try {
328
+ this.post({ t: 'edge', ev: 'gone', id }) // the page ends the frame's run: nobody reads its output now
329
+ } catch {
330
+ // the page is gone
331
+ }
332
+ }
333
+
334
+ handle(job, m) {
335
+ if (m.ev === 'reply') {
336
+ if (job.runner) return // one reply per run
337
+ if (m.fallback !== undefined) {
338
+ const why = text(m.fallback, 'fallback', 500)
339
+ this.jobs.delete(m.id)
340
+ return job.resolve({ fallback: why })
341
+ }
342
+ const id = m.id
343
+ // output that comes before EdgeHost has set onOut and sent its reply waits until it calls begin()
344
+ const held = []
345
+ job.held = held
346
+ job.runner = {
347
+ begin: () => {
348
+ job.held = null
349
+ for (const f of held.splice(0)) f()
350
+ },
351
+ stdin: bytes => this.post({ t: 'edge', ev: 'stdin', id, bytes }),
352
+ stdinEnd: () => this.post({ t: 'edge', ev: 'stdin-end', id }),
353
+ signal: n => this.post({ t: 'edge', ev: 'signal', id, n }),
354
+ gone: () => {
355
+ this.jobs.delete(id)
356
+ this.post({ t: 'edge', ev: 'gone', id })
357
+ },
358
+ }
359
+ return job.resolve({ runner: job.runner })
360
+ }
361
+ const go = f => (job.held ? job.held.push(f) : f())
362
+ if (m.ev === 'out') {
363
+ if (!KINDS_OUT.has(m.kind)) throw new BadMessage('out kind is not stdout or stderr')
364
+ const bytes = bytesView(m.bytes)
365
+ this.stats.outBytes[m.kind] += bytes.length
366
+ go(() => job.runner?.onOut?.(m.kind, bytes))
367
+ } else if (m.ev === 'exit') {
368
+ this.stats.exitsSeen++
369
+ const code = exitCodeOf(m.code)
370
+ const signal = m.signal == null ? undefined : signalOf(m.signal)
371
+ const refused = m.spawnRefused === undefined ? undefined : text(m.spawnRefused, 'spawnRefused', 500)
372
+ this.jobs.delete(m.id)
373
+ if (refused !== undefined && job.key !== null) this.refused.set(job.key, refused)
374
+ go(() => job.runner?.onExit?.({ code, signal }))
375
+ }
376
+ }
377
+ }
378
+
379
+ const signalOf = n => {
380
+ if (!Number.isInteger(n) || n < 1 || n > 64) throw new BadMessage('signal is not an integer from 1 to 64')
381
+ return n
382
+ }
@@ -0,0 +1,245 @@
1
+ // X5 part B (switch edge=1): the channel service's side of the file route. The page gives the
2
+ // service MessagePorts (message {t:'edge-fs', ...} in chan-service.js); node's relay in the isolated
3
+ // frame posts file requests on them. Each request is answered from the machine's Overlay by an
4
+ // EdgeFsRoute, in the service's own event loop between 9P requests.
5
+ //
6
+ // Request: {id, mount, method, args, t0} with t0 the sender's epoch time in ms
7
+ // (performance.timeOrigin + performance.now()) when it posted. Reply: {id, res}.
8
+ // {id, op: 'stats'} replies {id, stats}: the crossings per method, the wait of every request
9
+ // (the time from the sender's post to the first moment this code saw it, so it holds the message's
10
+ // hop and any wait behind the service's 9P spin), the work of every method, and the reply posts.
11
+ // {id, op: 'reset'} zeroes the counters.
12
+ // Nothing here runs unless the page sent 'edge-fs'.
13
+
14
+ import { EdgeFsRoute, METHODS, MAX_HANDLES } from './fs-route.js'
15
+
16
+ export { MAX_HANDLES }
17
+ import { Hist } from './hist.js'
18
+ import { OwnFsRoute } from './own/fs-own-route.js'
19
+ import { ChildHost } from './own/child-host.js'
20
+ import { guestSpawner } from './own/guest-spawner.js'
21
+ import { serveOwnFs } from './own/service-receiver.js'
22
+
23
+ const epochMs = () => performance.timeOrigin + performance.now()
24
+
25
+ const KNOWN = new Set([...METHODS, 'ctl'])
26
+ /** The most plan ops (a walk of every mount) one run may have answered fresh; later ones get the last answer (check4 F9). The runtime asks once. */
27
+ export const MAX_PLAN_OPS = 4
28
+
29
+ export class EdgePorts {
30
+ /**
31
+ * @param {import('../fs/overlay.js').Overlay} fs
32
+ * @param {{mounts: object, root?: string}} o
33
+ * @param {() => void} [onTraffic] called after each request (the service kicks its loop)
34
+ */
35
+ constructor(fs, o, onTraffic) {
36
+ this.fs = fs
37
+ this.route = new EdgeFsRoute(fs, o)
38
+ this.routes = [this.route] // one per distinct mount table
39
+ this.onTraffic = onTraffic
40
+ this.wait = new Hist() // sender's post -> first look
41
+ this.waitByMethod = new Map() // known method (or 'other') -> Hist
42
+ this.runs = new Map() // run id -> {ports, routes}: what a finished run releases
43
+ this.requests = 0
44
+ this.bad = 0 // messages answered as an error or ignored because they were not a request
45
+ this.released = 0
46
+ this.ownRoutes = 0 // routes made for the own runtime's ports
47
+ this.fsSerdes = [] // the serializer lines of the Workers' notes (OwnFsRoute.serdes)
48
+ this.fsRing = [] // the last file calls of the own routes with their answers (see OwnFsRoute.ring)
49
+ this.childStats = { host: {}, spawner: {} } // what the children of the own runtime's routes did: calls and frames, summed over the runs (a hang shows which step is missing)
50
+ }
51
+
52
+ /** Open ports (all runs). */
53
+ get ports() {
54
+ const all = []
55
+ for (const r of this.runs.values()) all.push(...r.ports)
56
+ return all
57
+ }
58
+
59
+ /**
60
+ * The route for a run's mount table. A run's table is the container's top-level directories at its start, numbered in
61
+ * order, so a directory made since the last run moves the numbers: a table of its own, never the first run's. The
62
+ * counters are shared.
63
+ */
64
+ routeFor(o) {
65
+ const key = JSON.stringify([o.root || '', o.mounts])
66
+ for (const r of this.routes) if (JSON.stringify([r.rootPath || '', r.mounts]) === key) return r
67
+ const r = new EdgeFsRoute(this.fs, o)
68
+ r.calls = this.route.calls
69
+ this.routes.push(r)
70
+ return r
71
+ }
72
+
73
+ /** `run`: the owner of the port's handles (release(run) closes them). */
74
+ attach(port, route = this.route, run = 0) {
75
+ let r = this.runs.get(run)
76
+ if (!r) this.runs.set(run, (r = { ports: [], routes: new Set(), plans: 0, lastPlan: { oversize: [] } }))
77
+ r.ports.push(port)
78
+ r.routes.add(route)
79
+ port.onmessage = e => this.#message(port, e && e.data, route, run)
80
+ }
81
+
82
+ /**
83
+ * A port of the own runtime (src/edge/own/): its file calls are `{own: 'fs', ...}` messages, answered by an OwnFsRoute over the same Overlay, and
84
+ * its children run in the guest through `openExec(job)`, a raw stream to the exec service of the stub that started the run (service-host.js
85
+ * openExec). `run`: the owner of the port's handles (release(run) closes them and ends the children).
86
+ */
87
+ attachOwn(port, { run = 0, root = '', job = 0, openExec = null, onTraffic = null, kickAll = false, onSignalTaken = null } = {}) {
88
+ let r = this.runs.get(run)
89
+ if (!r) this.runs.set(run, (r = { ports: [], routes: new Set(), plans: 0, lastPlan: { oversize: [] } }))
90
+ const route = new OwnFsRoute(this.fs, { root })
91
+ route.ring = this.fsRing
92
+ route.serdes = this.fsSerdes
93
+ if (onSignalTaken) route.onSignalTaken = onSignalTaken
94
+ if (openExec) {
95
+ // what the page writes to the stub's exec stream leaves the service only when the machine's doorbell rings (onTraffic): the header of a child is
96
+ // written before any answer to the program exists, so the bell is rung here after every write and close (fix5: the bar's child cases hung).
97
+ const bell = () => {
98
+ try {
99
+ onTraffic?.()
100
+ } catch {
101
+ // a bell that cannot ring is no reason to stop the child
102
+ }
103
+ }
104
+ const kidStats = this.childStats
105
+ route.children = new ChildHost(
106
+ guestSpawner(async () => {
107
+ const s = await openExec(job)
108
+ return {
109
+ read: () => s.read(),
110
+ write: b => {
111
+ const r = s.write(b)
112
+ bell()
113
+ return r
114
+ },
115
+ close: () => {
116
+ s.close()
117
+ bell()
118
+ },
119
+ }
120
+ }, { stats: kidStats.spawner }),
121
+ kidStats.host,
122
+ )
123
+ }
124
+ const srv = serveOwnFs(port, route, { onTraffic: onTraffic || undefined, kickAll, onError: () => void this.bad++ })
125
+ r.ports.push(port)
126
+ ;(r.own ||= []).push({ route, srv })
127
+ this.ownRoutes++
128
+ }
129
+
130
+ /**
131
+ * A finished run: its ports are closed, its open file handles are closed (the files' references go), and the route
132
+ * tables only it used are dropped. Safe to call twice and for a run that never attached.
133
+ */
134
+ release(run) {
135
+ const r = this.runs.get(run)
136
+ if (!r) return false
137
+ this.runs.delete(run)
138
+ for (const p of r.ports) {
139
+ try {
140
+ p.onmessage = null
141
+ p.close?.()
142
+ } catch {
143
+ // a port that is already closed
144
+ }
145
+ }
146
+ for (const o of r.own || []) {
147
+ o.srv.close() // the children the run started end
148
+ o.route.close() // its open files are closed
149
+ }
150
+ for (const rt of r.routes) {
151
+ rt.releaseOwner(run)
152
+ // a route table only this run used is dropped (the first one, made with the service, stays)
153
+ if (rt !== this.route && ![...this.runs.values()].some(o => o.routes.has(rt))) this.routes.splice(this.routes.indexOf(rt), 1)
154
+ }
155
+ this.released++
156
+ return true
157
+ }
158
+
159
+ #reply(port, id, res, transfer) {
160
+ try {
161
+ port.postMessage({ id, res }, transfer)
162
+ } catch {
163
+ // a closed port has no one to answer
164
+ }
165
+ }
166
+
167
+ #message(port, m, route, run) {
168
+ try {
169
+ const t1 = epochMs()
170
+ // the frame runs the container's JavaScript: anything can arrive here, and nothing may throw out of this function
171
+ if (m === null || typeof m !== 'object' || Array.isArray(m)) return void this.bad++
172
+ const id = m.id
173
+ if (m.op !== undefined) {
174
+ if (m.op === 'stats') return port.postMessage({ id, stats: this.stats() })
175
+ if (m.op === 'plan') {
176
+ const own = this.runs.get(run)
177
+ if (own && own.plans >= MAX_PLAN_OPS) return port.postMessage({ id, plan: own.lastPlan, limited: true })
178
+ const plan = { oversize: this.route.oversizeDirs() }
179
+ if (own) (own.plans++, (own.lastPlan = plan))
180
+ return port.postMessage({ id, plan })
181
+ }
182
+ if (m.op === 'reset') {
183
+ this.reset()
184
+ return port.postMessage({ id, reset: true })
185
+ }
186
+ return void this.bad++
187
+ }
188
+ const method = typeof m.method === 'string' && KNOWN.has(m.method) ? m.method : null
189
+ if (method === null) {
190
+ this.bad++
191
+ return this.#reply(port, id, { error: { code: 'ENOSYS', message: 'edge fs: no such method' } })
192
+ }
193
+ this.requests++
194
+ if (typeof m.t0 === 'number' && Number.isFinite(m.t0)) {
195
+ const w = (t1 - m.t0) * 1000
196
+ if (Number.isFinite(w)) {
197
+ // a t0 of 1e308 makes the wait infinite: the statistics keep only waits that are numbers
198
+ this.wait.add(w)
199
+ let h = this.waitByMethod.get(method)
200
+ if (!h) this.waitByMethod.set(method, (h = new Hist()))
201
+ h.add(w)
202
+ }
203
+ }
204
+ const res = route.handle(m.mount, method, m.args, run)
205
+ const v = res.value
206
+ if (v instanceof Uint8Array) this.#reply(port, id, res, [v.buffer])
207
+ else this.#reply(port, id, res)
208
+ this.onTraffic?.()
209
+ } catch (e) {
210
+ this.bad++
211
+ try {
212
+ if (m && typeof m === 'object') port.postMessage({ id: m.id, res: { error: { code: 'EIO', message: 'edge fs route: ' + String((e && e.message) || e).slice(0, 200) } } })
213
+ } catch {
214
+ // nothing to tell
215
+ }
216
+ }
217
+ }
218
+
219
+ reset() {
220
+ this.wait = new Hist()
221
+ this.waitByMethod = new Map()
222
+ this.requests = 0
223
+ this.bad = 0
224
+ const calls = {}
225
+ for (const r of this.routes) r.calls = calls
226
+ }
227
+
228
+ stats() {
229
+ const r = this.route.stats()
230
+ return {
231
+ requests: this.requests,
232
+ bad: this.bad,
233
+ runs: this.runs.size,
234
+ ports: this.ports.length,
235
+ released: this.released,
236
+ children: this.childStats,
237
+ ring: this.fsRing.slice(-120),
238
+ serdes: this.fsSerdes.length ? this.fsSerdes.slice() : undefined,
239
+ handles: this.routes.reduce((a, rt) => a + rt.handles.size, 0) + [...this.runs.values()].reduce((a, r) => a + (r.own || []).reduce((b, o) => b + o.route.handles.size, 0), 0),
240
+ wait: this.wait.summary(),
241
+ waitByMethod: Object.fromEntries([...this.waitByMethod].map(([k, h]) => [k, h.summary()])),
242
+ ...r,
243
+ }
244
+ }
245
+ }