@threadedstack/wmd-web 0.1.39 → 0.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +236 -1
  2. package/RELEASE.json +84 -49
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +231 -4
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +208 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +125 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +13 -2
  38. package/src/edge/sbx/cap.js +36 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +275 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/setup.js +9 -6
  54. package/src/host/chan-service.js +8 -5
  55. package/src/host/chan-services.js +29 -4
  56. package/src/host/edge-host.js +58 -3
  57. package/wmdpack.wasm +0 -0
@@ -0,0 +1,115 @@
1
+ // X5 option A part 3, item 12: a node start never waits long for a download. The files of node are 65 MB. A start whose files are not in waits at most
2
+ // FILES_WAIT_MS for them; past that it runs in the guest with one calm reason (FILES_STILL), which is not a failure: nothing is counted against the frame,
3
+ // the site is not marked down, and no alarming event is made. The download goes on in the background, once; one event says when the files are in
4
+ // ({type: 'files', ready: true, bytes, ms, source}), progress events come at most one per progressMs, and when every source failed one event holds the
5
+ // reason of each source ({type: 'files', failed: true, reasons}). After a failure the page tries again no sooner than retryMs (the site's retry time),
6
+ // and the start that brings the retry goes to the guest at once: no start waits for a retry.
7
+ //
8
+ // const g = filesGate({ get, onEvent }) get(onProgress) -> Promise<{files, source, reasons} | {error, reasons}> (src/edge/sbx/files.js)
9
+ // g.begin() starts the download when none is in flight (a prepare, a start, the site's probe); returns the one promise of the result
10
+ // g.forStart() -> null (the files are in, run in the frame) | {fallback: true, reason} (run in the guest)
11
+ import { SITE_RETRY_MS } from '../site.js'
12
+
13
+ /**
14
+ * How long one node start waits for the files before it runs in the guest (ms). The reasoning, from item 10's marks on a loopback link (a fast link, the
15
+ * 65 MB come from the page's own machine): the page has the files checked and handed in 0.66 s (Chromium), 1.1 s (Firefox) and 0.94 s (WebKit) after the
16
+ * command, medians of three, the slowest 1.13 s. 2.5 s is more than twice the slowest, so a start on a fast link finds them within the bound; and on a link
17
+ * that is not fast the start costs at most this much more than the guest alone (the guest's `node -v` takes about 0.3 s), once: later starts go to the
18
+ * guest at once until the files are in.
19
+ */
20
+ export const FILES_WAIT_MS = 2500
21
+ /** The reason of a start that went to the guest because the files were not there yet. */
22
+ export const FILES_STILL = "node's files are still loading"
23
+ /** At most one progress event in this many ms ("a few per second"). */
24
+ export const FILES_PROGRESS_MS = 500
25
+
26
+ const text = r => {
27
+ const list = Array.isArray(r.reasons) ? r.reasons : []
28
+ const per = list.map(x => `${x.source}: ${x.why}`).join('; ')
29
+ return per || String(r.error || 'no source gave the files')
30
+ }
31
+
32
+ export function filesGate({ get, waitMs = FILES_WAIT_MS, retryMs = SITE_RETRY_MS, progressMs = FILES_PROGRESS_MS, onEvent = () => {}, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout }) {
33
+ let state = 'idle' // idle | loading | ready | failed
34
+ let p = null
35
+ let t0 = 0
36
+ let late = false // a start gave up waiting: the starts that come while the files load go to the guest at once
37
+ let failedAt = 0
38
+ let failure = ''
39
+ let lastFail = null
40
+ // progress: the source's counter restarts at each file; the events carry the sum
41
+ let base = 0
42
+ let last = 0
43
+ let sentAt = -Infinity
44
+ const onProgress = got => {
45
+ if (got < last) base += last
46
+ last = got
47
+ const t = now()
48
+ if (t - sentAt < progressMs) return
49
+ sentAt = t
50
+ onEvent({ type: 'files', progress: true, bytes: base + got, ms: t - t0 })
51
+ }
52
+ const done = r => {
53
+ const ms = now() - t0
54
+ if (r.error) {
55
+ state = 'failed'
56
+ failedAt = now()
57
+ failure = text(r)
58
+ lastFail = r
59
+ onEvent({ type: 'files', failed: true, why: String(r.error), reasons: Array.isArray(r.reasons) ? r.reasons : [], ms })
60
+ return r
61
+ }
62
+ state = 'ready'
63
+ late = false
64
+ // the cache holds the checked files: the gate keeps its state only, and a later asker reads them back from the cache (src/edge/sbx/files.js, item 15)
65
+ if (r.cached) p = null
66
+ const bytes = Object.entries(r.files || {}).reduce((n, [k, v]) => n + (k === 'hashes' ? 0 : (v && v.byteLength) || 0), 0)
67
+ onEvent({ type: 'files', ready: true, bytes, ms, source: r.source })
68
+ return r
69
+ }
70
+ const begin = () => {
71
+ if (state === 'loading' || (state === 'ready' && p)) return p
72
+ if (state === 'ready') {
73
+ // read back from the cache (the files are checked again there); nothing changes in the gate
74
+ return Promise.resolve()
75
+ .then(() => get(onProgress))
76
+ .catch(e => ({ error: String((e && e.message) || e).split('\n')[0], reasons: [] }))
77
+ }
78
+ state = 'loading'
79
+ t0 = now()
80
+ late = false
81
+ base = last = 0
82
+ sentAt = -Infinity
83
+ p = Promise.resolve()
84
+ .then(() => get(onProgress))
85
+ .then(done, e => done({ error: String((e && e.message) || e).split('\n')[0], reasons: [] }))
86
+ return p
87
+ }
88
+ // what a frame that wants the files (the prepare frame, a run frame, the site's probe) asks: the one download in flight, the files, or the failure as it
89
+ // was; only a start after the retry time, or the first begin(), starts a download
90
+ const join = () => (state === 'failed' ? Promise.resolve(lastFail) : begin())
91
+ const guest = reason => ({ fallback: true, reason })
92
+ const failedAnswer = () => guest(`node's files could not be fetched (${failure})`)
93
+ async function forStart() {
94
+ if (state === 'ready' && p) return null
95
+ if (state === 'failed') {
96
+ const age = now() - failedAt
97
+ if (age < retryMs) return guest(`node's files could not be fetched (${failure}); the page tries again in ${Math.max(1, Math.ceil((retryMs - age) / 60000))} minute(s)`)
98
+ begin() // the retry is a background fetch: this start does not wait for it
99
+ late = true
100
+ return guest(FILES_STILL)
101
+ }
102
+ const mine = begin()
103
+ if (late && state !== 'ready') return guest(FILES_STILL)
104
+ let timer
105
+ const never = Symbol('bound')
106
+ const r = await Promise.race([mine, new Promise(res => (timer = setTimer(() => res(never), waitMs)))])
107
+ clearTimer(timer)
108
+ if (r === never) {
109
+ if (state !== 'ready') late = true
110
+ return guest(FILES_STILL)
111
+ }
112
+ return r.error ? failedAnswer() : null
113
+ }
114
+ return { begin, join, forStart, state: () => state, holds: () => state === 'ready' && p !== null }
115
+ }
@@ -0,0 +1,68 @@
1
+ // SHA-256 in plain JavaScript, for a Worker of the sandboxed frame whose engine gives it no crypto.subtle (Chromium: an opaque origin is not a secure
2
+ // context, measured in docs/research/browser-speed-2026-11/x5/sandbox/product/product.md item 1). The page checks every downloaded file with the
3
+ // engine's own digest (src/host/pinned-fetch.js); this is for the runtime's own hashes of bytes it already holds (own/adapter.js, own/hub.js).
4
+ const K = new Int32Array([
5
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
6
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
7
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
8
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
9
+ ])
10
+
11
+ /** @param {Uint8Array} data @returns {Uint8Array} the 32-byte digest */
12
+ export function sha256(data) {
13
+ const n = data.length
14
+ const total = (((n + 9 + 63) >> 6) << 6)
15
+ const tail = new Uint8Array(total - (n - (n % 64))) // the last partial block and the padding
16
+ tail.set(data.subarray(n - (n % 64)))
17
+ tail[n % 64] = 0x80
18
+ const dv = new DataView(tail.buffer)
19
+ dv.setUint32(tail.length - 8, Math.floor(n / 0x20000000), false)
20
+ dv.setUint32(tail.length - 4, (n << 3) >>> 0, false)
21
+ const h = new Int32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19])
22
+ const w = new Int32Array(64)
23
+ const block = (b, o) => {
24
+ for (let i = 0; i < 16; i++) w[i] = (b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]
25
+ for (let i = 16; i < 64; i++) {
26
+ const a = w[i - 15]
27
+ const c = w[i - 2]
28
+ const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3)
29
+ const s1 = ((c >>> 17) | (c << 15)) ^ ((c >>> 19) | (c << 13)) ^ (c >>> 10)
30
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0
31
+ }
32
+ let a = h[0], b1 = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]
33
+ for (let i = 0; i < 64; i++) {
34
+ const t1 = (hh + (((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0
35
+ const t2 = ((((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))) + ((a & b1) ^ (a & c) ^ (b1 & c))) | 0
36
+ hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b1; b1 = a; a = (t1 + t2) | 0
37
+ }
38
+ h[0] = (h[0] + a) | 0; h[1] = (h[1] + b1) | 0; h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0
39
+ h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0; h[6] = (h[6] + g) | 0; h[7] = (h[7] + hh) | 0
40
+ }
41
+ const whole = n - (n % 64)
42
+ for (let o = 0; o < whole; o += 64) block(data, o)
43
+ for (let o = 0; o < tail.length; o += 64) block(tail, o)
44
+ const out = new Uint8Array(32)
45
+ const ov = new DataView(out.buffer)
46
+ for (let i = 0; i < 8; i++) ov.setInt32(4 * i, h[i], false)
47
+ return out
48
+ }
49
+
50
+ /**
51
+ * Gives `g.crypto.subtle.digest('SHA-256', bytes)` to a scope that has no crypto.subtle (a Worker of a frame with an opaque origin in Chromium).
52
+ * Nothing is changed where the engine has one. -> true when the fallback was put in.
53
+ */
54
+ export function installDigestFallback(g = globalThis) {
55
+ if (g.crypto && g.crypto.subtle) return false
56
+ const digest = async (alg, data) => {
57
+ if (String(alg && alg.name ? alg.name : alg).toUpperCase() !== 'SHA-256') throw new Error('only SHA-256 is available here')
58
+ const u = data instanceof ArrayBuffer || (typeof SharedArrayBuffer === 'function' && data instanceof SharedArrayBuffer) ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
59
+ return sha256(u).buffer
60
+ }
61
+ const subtle = { digest }
62
+ try {
63
+ Object.defineProperty(g.crypto, 'subtle', { value: subtle, configurable: true })
64
+ } catch {
65
+ return false
66
+ }
67
+ return true
68
+ }
@@ -0,0 +1,36 @@
1
+ // The entry of the edge Worker in the sandboxed frame (bundled to one text, scripts/build-frame-code.mjs): ../worker.js with the runtime's
2
+ // files taken from what the frame handed in (the message's `x5sbx`) instead of fetched, and the runtime's own Workers made in the frame's form.
3
+ import { OwnRuntime } from '../own/hub.js'
4
+ import { setDeps } from '../own/adapter.js'
5
+ import '../worker.js'
6
+ import { makeFactory, urlsFor } from './common.js'
7
+ import { installDigestFallback } from './sha256.js'
8
+
9
+ installDigestFallback(globalThis) // Chromium: an opaque-origin Worker has no crypto.subtle (the runtime hashes bytes it holds)
10
+
11
+ const real = globalThis.onmessage
12
+ const dec = new TextDecoder()
13
+ globalThis.onmessage = e => {
14
+ const d = e && e.data
15
+ if (d && d.x5sbx) setup(d.x5sbx)
16
+ return real.call(globalThis, e)
17
+ }
18
+
19
+ function setup({ strategy, ownWorker, files }) {
20
+ const mk = makeFactory(strategy)
21
+ const urls = urlsFor(mk, { glue: files.glue, snippet: files.snippet, acorn: files.acorn, ownWorker })
22
+ const name = u => String(u).replace(/^sbx:/, '')
23
+ setDeps({
24
+ // the adapter's file reads: 'sbx:<name>' is a file the page handed in
25
+ fetch: async u => {
26
+ const b = files[{ 'wmd_browser_bg.wasm': 'wasm', 'wmd_browser.js': 'glue', 'edgejs.wasm': 'edgejs', 'linux.cjs': 'linux', 'HASHES.txt': 'hashes', 'python-3.12.wasm': 'python', 'linux.py': 'linuxpy' }[name(u)]]
27
+ if (!b) return { ok: false, status: 404, statusText: 'not handed in', url: String(u) }
28
+ return { ok: true, status: 200, url: String(u), arrayBuffer: async () => b, text: async () => dec.decode(b) }
29
+ },
30
+ OwnRuntime: {
31
+ // data: Workers (WebKit) keep about 7 MiB each until they are ended: idle thread Workers beyond the spare ones are ended after 1.5 s (src/edge/own/pool.js idleMs)
32
+ start: o => OwnRuntime.start({ ...o, glueUrl: urls.glue, workerUrl: urls.worker, ...(urls.glueScript ? { glueScript: urls.glueScript } : {}), create: mk.make, ...(strategy === 'data' && o.poolIdleMs === undefined ? { poolIdleMs: 1500 } : {}) }),
33
+ prepare: (...a) => OwnRuntime.prepare(...a),
34
+ },
35
+ })
36
+ }
@@ -0,0 +1,113 @@
1
+ // Named semaphores shared by every process of one frame run (python's multiprocessing locks), as edge/src/sems.rs on the desktop: the same
2
+ // requests and error names. The python shim reaches them through the control file (ctl.js `sem_*`). Every operation returns at once; a waiter
3
+ // retries from the program with short sleeps, so a wait never holds a thread another process needs.
4
+ // Not ported: the per-process handle limit and the close of a process's handles when it ends (the control request carries no pid here);
5
+ // the run's own limit below keeps a program that opens handles in a loop from growing the page without end.
6
+
7
+ export const VALUE_MAX = 2 ** 31 - 1 // SEM_VALUE_MAX on Linux
8
+ const NAME_MAX = 251 // glibc's longest name, less its "sem." prefix
9
+ const NAMES_MAX = 16384 // the named semaphores Docker's /dev/shm holds: 64 MiB of 4 KiB pages
10
+ const HANDLES_MAX = 65530 // vm.max_map_count
11
+
12
+ class SemError extends Error {
13
+ constructor(code) {
14
+ super(code)
15
+ this.code = code
16
+ }
17
+ }
18
+
19
+ const checkName = name => {
20
+ const rest = name.replace(/^\/+/, '')
21
+ if (rest === '' || rest.includes('/')) throw new SemError('EINVAL')
22
+ if (new TextEncoder().encode(rest).length > NAME_MAX) throw new SemError('ENAMETOOLONG')
23
+ }
24
+
25
+ export class Sems {
26
+ #names = new Map()
27
+ #handles = new Map()
28
+ #next = 0
29
+
30
+ #handle(sem) {
31
+ if (this.#handles.size >= HANDLES_MAX) throw new SemError('ENOMEM')
32
+ const h = ++this.#next
33
+ this.#handles.set(h, sem)
34
+ return h
35
+ }
36
+
37
+ #get(handle) {
38
+ const s = this.#handles.get(Number(handle))
39
+ if (!s) throw new SemError('EINVAL')
40
+ return s
41
+ }
42
+
43
+ /** sem_open: with `create` a new semaphore of `value` (EEXIST if `excl` and the name is taken), without the named one (ENOENT). No name: an unnamed one. */
44
+ open(name, create, excl, value) {
45
+ if (value > VALUE_MAX) throw new SemError('EINVAL')
46
+ if (name == null) return this.#handle({ value })
47
+ checkName(name)
48
+ let sem = this.#names.get(name)
49
+ if (sem && create && excl) throw new SemError('EEXIST')
50
+ if (!sem) {
51
+ if (!create) throw new SemError('ENOENT')
52
+ if (this.#names.size >= NAMES_MAX) throw new SemError('ENOSPC')
53
+ sem = { value }
54
+ this.#names.set(name, sem)
55
+ }
56
+ return this.#handle(sem)
57
+ }
58
+
59
+ tryWait(handle) {
60
+ const s = this.#get(handle)
61
+ if (s.value === 0) return false
62
+ s.value--
63
+ return true
64
+ }
65
+
66
+ post(handle) {
67
+ const s = this.#get(handle)
68
+ if (s.value >= VALUE_MAX) throw new SemError('EOVERFLOW')
69
+ s.value++
70
+ }
71
+
72
+ value(handle) {
73
+ return this.#get(handle).value
74
+ }
75
+
76
+ /** sem_unlink: the name goes, open handles keep the semaphore. */
77
+ unlink(name) {
78
+ checkName(name)
79
+ if (!this.#names.delete(name)) throw new SemError('ENOENT')
80
+ }
81
+
82
+ close(handle) {
83
+ this.#handles.delete(Number(handle))
84
+ }
85
+ }
86
+
87
+ /** The reply of one `sem_*` request, or undefined when `r.op` is not one. */
88
+ export function semOp(sems, r) {
89
+ try {
90
+ switch (r.op) {
91
+ case 'sem_open':
92
+ return { handle: sems.open(typeof r.name === 'string' ? r.name : null, !!r.create, !!r.excl, Number(r.value) || 0) }
93
+ case 'sem_trywait':
94
+ return { ok: sems.tryWait(r.handle) }
95
+ case 'sem_post':
96
+ sems.post(r.handle)
97
+ return { ok: true }
98
+ case 'sem_getvalue':
99
+ return { value: sems.value(r.handle) }
100
+ case 'sem_unlink':
101
+ sems.unlink(String(r.name ?? ''))
102
+ return { ok: true }
103
+ case 'sem_close':
104
+ sems.close(r.handle)
105
+ return { ok: true }
106
+ default:
107
+ return undefined
108
+ }
109
+ } catch (e) {
110
+ if (e instanceof SemError) return { err: e.code }
111
+ throw e
112
+ }
113
+ }
@@ -17,6 +17,10 @@ import { parseNodeArgs, parseNodeOptions, programKey } from './node-args.js'
17
17
  import { BadMessage, KINDS_OUT, bytesView, exitCodeOf, text } from './msg.js'
18
18
  import { pagesListings, runsChildren } from './runtime.js'
19
19
  import { guestOption } from './node-guest-opts.js'
20
+ import { pythonStartReason } from './python-plan.js'
21
+
22
+ /** A start of the image's python (the stub stands over it only when the page's plan took it). */
23
+ export const isPythonStart = hello => /^python/.test(String((hello.argv || [])[0] || '').split('/').pop())
20
24
 
21
25
  const utf8 = s => new TextDecoder().decode(Uint8Array.from(s, c => c.charCodeAt(0)))
22
26
  /** Container top-level names the SDK has its own for, or the guest mounts over. */
@@ -207,7 +211,9 @@ export function childrenReason(fs, rootNode, hello) {
207
211
  * @param {(msg: object) => void} o.post to the page
208
212
  */
209
213
  export class EdgeService {
210
- constructor({ fs, root = 'rootfs', post, now = () => performance.now(), rt = '' }) {
214
+ constructor({ fs, root = 'rootfs', post, now = () => performance.now(), rt = '', settleCapMs = 2500, cleanOf = null }) {
215
+ this.cleanOf = cleanOf // X25 gate 2c: (job) => whether the run changed nothing in the container's tree (service-port.js jobClean); null: never said
216
+ this.settleCapMs = settleCapMs // the most an exit waits for the run's sockets to hand on their bytes (X5 net)
211
217
  this.fs = fs
212
218
  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
219
  this.root = root
@@ -229,18 +235,42 @@ export class EdgeService {
229
235
  return job.openExec()
230
236
  }
231
237
 
232
- /** EdgeHost's start(hello, {openExec}). */
238
+ /** X5 net: the stub's session of run `id` for its sockets: {openStream(): a raw yamux stream, setAccepted(fn): where the stub's `accepted` streams go}. */
239
+ netFor(id) {
240
+ const job = this.jobs.get(id)
241
+ if (!job || !job.openStream) throw Object.assign(new Error('no stub for this run'), { code: 'ESRCH' })
242
+ // setSettle(fn): fn() answers when the run's sockets handed on what the program wrote; the run's exit waits for it (at most settleCapMs)
243
+ return { openStream: () => job.openStream(), setAccepted: fn => job.setAccepted?.(fn), setSettle: fn => (job.settle = fn) }
244
+ }
245
+
246
+ /** EdgeHost's start(hello, {openExec, openStream, setAccepted}). */
233
247
  start(hello, ctx = {}) {
234
248
  const t0 = this.now()
235
249
  this.stats.starts++
236
250
  const rootNode = this.fs.resolve(this.root)
237
251
  const mounts = topLevelMounts(this.fs, rootNode)
238
- const addon = findAddon(this.fs, rootNode, hello.cwd)
239
252
  const lookMs = () => {
240
253
  const d = this.now() - t0
241
254
  this.stats.planMs += d
242
255
  this.stats.planMsMax = Math.max(this.stats.planMsMax, d)
243
256
  }
257
+ if (isPythonStart(hello)) {
258
+ // X25 gate 2, item 1: the image's python. The command line, the start's environment and the native extensions where this python imports from (the
259
+ // desktop's pythonReason, src/edge/python-plan.js); the looks that are node's (an addon, children, the listing) are not made for it: the runtime
260
+ // starts children through the stub, and its file route pages its listings
261
+ let why = ''
262
+ try {
263
+ why = pythonStartReason(this.fs, rootNode, hello)
264
+ } catch {
265
+ why = 'the look at the container\'s python files failed' // a look that fails sends the start to the guest, where nothing is lost
266
+ }
267
+ this.stats.pythonLookMs = (this.stats.pythonLookMs || 0) + (this.now() - t0)
268
+ this.stats.pythonLooks = (this.stats.pythonLooks || 0) + 1
269
+ lookMs()
270
+ if (why) return Promise.resolve({ fallback: why })
271
+ return this.#ask(hello, ctx, mounts, null, t0)
272
+ }
273
+ const addon = findAddon(this.fs, rootNode, hello.cwd)
244
274
  if (addon) return lookMs(), Promise.resolve({ fallback: `a native addon in node's search path (${addon})` })
245
275
  // 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
276
  // (check5 F5): the image's own node answers them.
@@ -270,8 +300,13 @@ export class EdgeService {
270
300
  }
271
301
  lookMs()
272
302
  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` })
303
+ return this.#ask(hello, ctx, mounts, key, t0)
304
+ }
305
+
306
+ /** The start is the page's to run: a job, and the page asked. */
307
+ #ask(hello, ctx, mounts, key, t0) {
273
308
  const id = this.next++
274
- const job = { runner: null, key, openExec: ctx.openExec || null }
309
+ const job = { runner: null, key, openExec: ctx.openExec || null, openStream: ctx.openStream || null, setAccepted: ctx.setAccepted || null }
275
310
  this.jobs.set(id, job)
276
311
  return new Promise(resolve => {
277
312
  job.resolve = resolve
@@ -371,7 +406,24 @@ export class EdgeService {
371
406
  const refused = m.spawnRefused === undefined ? undefined : text(m.spawnRefused, 'spawnRefused', 500)
372
407
  this.jobs.delete(m.id)
373
408
  if (refused !== undefined && job.key !== null) this.refused.set(job.key, refused)
374
- go(() => job.runner?.onExit?.({ code, signal }))
409
+ // X5 net: the stub exits on the exit frame, so the bytes the program wrote to its sockets go first (net-host.js settled)
410
+ let clean = false
411
+ try {
412
+ clean = !!this.cleanOf?.(m.id)
413
+ } catch {
414
+ clean = false
415
+ }
416
+ const exit = () => go(() => job.runner?.onExit?.(clean ? { code, signal, clean } : { code, signal }))
417
+ if (typeof job.settle === 'function') {
418
+ let one = false
419
+ const finish = () => (one ? undefined : ((one = true), exit()))
420
+ const timer = setTimeout(finish, this.settleCapMs)
421
+ timer.unref?.()
422
+ Promise.resolve()
423
+ .then(() => job.settle())
424
+ .catch(() => {})
425
+ .then(() => (clearTimeout(timer), finish()))
426
+ } else exit()
375
427
  }
376
428
  }
377
429
  }
@@ -18,6 +18,7 @@ import { Hist } from './hist.js'
18
18
  import { OwnFsRoute } from './own/fs-own-route.js'
19
19
  import { ChildHost } from './own/child-host.js'
20
20
  import { guestSpawner } from './own/guest-spawner.js'
21
+ import { NetHost, netTotals } from './own/net-host.js'
21
22
  import { serveOwnFs } from './own/service-receiver.js'
22
23
 
23
24
  const epochMs = () => performance.timeOrigin + performance.now()
@@ -43,8 +44,11 @@ export class EdgePorts {
43
44
  this.requests = 0
44
45
  this.bad = 0 // messages answered as an error or ignored because they were not a request
45
46
  this.released = 0
47
+ this.cleanJobs = new Map() // stub job number -> the run changed nothing in the tree (jobClean)
46
48
  this.ownRoutes = 0 // routes made for the own runtime's ports
49
+ this.ownCalls = Object.create(null) // fix round item 2: the file calls the own routes of released runs answered, by method name (the live routes' are added in stats())
47
50
  this.fsSerdes = [] // the serializer lines of the Workers' notes (OwnFsRoute.serdes)
51
+ this.ringMax = Math.max(1, Math.floor(Number(o?.ringMax) || 120)) // how many of the route's last calls the ring keeps (X25 gate 2e: asked by the 'edge-fs' message, `ringMax`)
48
52
  this.fsRing = [] // the last file calls of the own routes with their answers (see OwnFsRoute.ring)
49
53
  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
54
  }
@@ -82,13 +86,14 @@ export class EdgePorts {
82
86
  /**
83
87
  * 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
88
  * 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).
89
+ * openExec). `net(job)` gives {openStream, setAccepted} of that stub's session (service-host.js netFor): the run's sockets (X5 net). `run`: the owner of the port's handles (release(run) closes them and ends the children).
86
90
  */
87
- attachOwn(port, { run = 0, root = '', job = 0, openExec = null, onTraffic = null, kickAll = false, onSignalTaken = null } = {}) {
91
+ attachOwn(port, { run = 0, root = '', job = 0, openExec = null, net = null, onTraffic = null, kickAll = false, onSignalTaken = null } = {}) {
88
92
  let r = this.runs.get(run)
89
93
  if (!r) this.runs.set(run, (r = { ports: [], routes: new Set(), plans: 0, lastPlan: { oversize: [] } }))
90
94
  const route = new OwnFsRoute(this.fs, { root })
91
95
  route.ring = this.fsRing
96
+ route.ringMax = this.ringMax
92
97
  route.serdes = this.fsSerdes
93
98
  if (onSignalTaken) route.onSignalTaken = onSignalTaken
94
99
  if (openExec) {
@@ -121,12 +126,68 @@ export class EdgePorts {
121
126
  kidStats.host,
122
127
  )
123
128
  }
124
- const srv = serveOwnFs(port, route, { onTraffic: onTraffic || undefined, kickAll, onError: () => void this.bad++ })
129
+ if (net) {
130
+ // X5 net: the container's network for the frame's node: sockets are streams on this run's stub session (src/edge/own/net-host.js)
131
+ let n = null
132
+ try {
133
+ n = net(job)
134
+ } catch {
135
+ n = null // no stub for this run: the route has no network (ENOSYS), as before
136
+ }
137
+ if (n) {
138
+ route.net = new NetHost({ openStream: n.openStream, onTraffic })
139
+ n.setAccepted((st, hdr, rest) => route.net.accepted(st, hdr, rest))
140
+ n.setSettle?.(() => route.net.settled())
141
+ }
142
+ }
143
+ const srv = serveOwnFs(port, route, { onTraffic: onTraffic || undefined, kickAll, onError: () => void this.bad++, onCall: (method, args) => this.#countOwn(method, args) })
125
144
  r.ports.push(port)
126
- ;(r.own ||= []).push({ route, srv })
145
+ ;(r.own ||= []).push({ route, srv, job })
127
146
  this.ownRoutes++
128
147
  }
129
148
 
149
+ // X25 gate 2: the own runtime's calls by method, counted as waitByMethod's entries `own:<method>` (n is the count; the waits are zero)
150
+ #countOwn(method, args) {
151
+ this.requests++
152
+ const k = 'own:' + (KNOWN.has(method) ? method : 'other')
153
+ let h = this.waitByMethod.get(k)
154
+ if (!h) this.waitByMethod.set(k, (h = new Hist()))
155
+ h.add(0)
156
+ // the directory of a path call (at most 40 kinds): where the calls of a start go
157
+ if ((method === 'stat' || method === 'readdir' || method === 'open') && this.waitByMethod.size < 80) {
158
+ const segs = String(args?.[0] ?? '').split('/').slice(0, 6)
159
+ if (segs.length > 2 && segs.at(-1).includes('.')) segs.pop() // a file: its directory
160
+ const d = k + ' ' + segs.join('/')
161
+ let g = this.waitByMethod.get(d)
162
+ if (!g) this.waitByMethod.set(d, (g = new Hist()))
163
+ g.add(0)
164
+ }
165
+ }
166
+
167
+ // X25 gate 2c: the runs whose route changed nothing, by the stub's job number, kept past the run's release (the exit may come after it)
168
+ #noteClean(job, clean) {
169
+ this.cleanJobs.set(job, (this.cleanJobs.get(job) ?? true) && clean)
170
+ while (this.cleanJobs.size > 64) this.cleanJobs.delete(this.cleanJobs.keys().next().value)
171
+ }
172
+
173
+ /** Whether every route of the stub's job `job` changed nothing in the tree (a job nobody attached for is not clean). */
174
+ jobClean(job) {
175
+ let seen = false
176
+ let clean = true
177
+ for (const r of this.runs.values())
178
+ for (const o of r.own || [])
179
+ if (o.job === job) {
180
+ seen = true
181
+ clean = clean && o.route.mut === 0
182
+ }
183
+ const done = this.cleanJobs.get(job)
184
+ if (done !== undefined) {
185
+ seen = true
186
+ clean = clean && done
187
+ }
188
+ return seen && clean
189
+ }
190
+
130
191
  /**
131
192
  * A finished run: its ports are closed, its open file handles are closed (the files' references go), and the route
132
193
  * tables only it used are dropped. Safe to call twice and for a run that never attached.
@@ -144,6 +205,8 @@ export class EdgePorts {
144
205
  }
145
206
  }
146
207
  for (const o of r.own || []) {
208
+ if (o.job) this.#noteClean(o.job, o.route.mut === 0)
209
+ for (const [k, c] of Object.entries(o.route.calls || {})) this.ownCalls[k] = (this.ownCalls[k] || 0) + c.n
147
210
  o.srv.close() // the children the run started end
148
211
  o.route.close() // its open files are closed
149
212
  }
@@ -223,6 +286,15 @@ export class EdgePorts {
223
286
  this.bad = 0
224
287
  const calls = {}
225
288
  for (const r of this.routes) r.calls = calls
289
+ this.ownCalls = Object.create(null)
290
+ for (const r of this.runs.values()) for (const o of r.own || []) o.route.calls = Object.create(null)
291
+ }
292
+
293
+ /** The file calls the own runtime's routes answered since this port was made, by method: the released runs' and the live ones' (counts the route keeps anyway). */
294
+ #ownCallTotals() {
295
+ const t = { ...this.ownCalls }
296
+ for (const r of this.runs.values()) for (const o of r.own || []) for (const [k, c] of Object.entries(o.route.calls || {})) t[k] = (t[k] || 0) + c.n
297
+ return t
226
298
  }
227
299
 
228
300
  stats() {
@@ -234,9 +306,11 @@ export class EdgePorts {
234
306
  ports: this.ports.length,
235
307
  released: this.released,
236
308
  children: this.childStats,
237
- ring: this.fsRing.slice(-120),
309
+ ownCalls: this.#ownCallTotals(),
310
+ ring: this.fsRing.slice(-this.ringMax),
238
311
  serdes: this.fsSerdes.length ? this.fsSerdes.slice() : undefined,
239
312
  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),
313
+ net: netTotals(),
240
314
  wait: this.wait.summary(),
241
315
  waitByMethod: Object.fromEntries([...this.waitByMethod].map(([k, h]) => [k, h.summary()])),
242
316
  ...r,