@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,275 @@
1
+ // X5 (item 3 of default1 round 2): node in the frame for a page that embeds the package. src/boot.js edgeSetup() decides the cases that need
2
+ // none of these modules (the switch off, no site) and loads this module for the rest; web/page/ckpt.js is one such page.
3
+ //
4
+ // const e = await edgeSetup({ origin, env }) (src/boot.js; the frame site's origin is the one thing a page must give)
5
+ // containerBundle({ ..., edgeNode: e.edgeNode }) undefined when node runs in the guest: the bundle is as without the switch
6
+ // bootWmd({ ..., edge: e.bootOption() }) one per boot (a restore's too); undefined when node runs in the guest
7
+ // e.prepare() after the boot: the frame is made and the runtime compiled when the page is idle
8
+ // e.close() the last booted machine ended (not one a restore replaces): the runs of every machine
9
+ // that got a boot option of this setup end, the kept frame goes; a node start of any of
10
+ // them that comes later is answered with the counted fallback (the stub runs node in the guest)
11
+ // e.use, e.reason the plan (src/edge/plan.js): node in the frame, or why it runs in the guest
12
+ // e.bridge(), e.site, e.prepared the current machine's bridge (its stats()), the site (src/edge/site.js), the prepare's result
13
+ //
14
+ // The site's origin must serve the frame's files with the headers of web/README.md "The frame's site", and the page's own server must serve
15
+ // /wasm/edgejs.wasm and allow the site in its frame-src. A site that does not answer is found by the frame's load (src/edge/page.js
16
+ // FRAME_LOAD_GRACE_MS): the run, and every later one while the site is down, gives the guest's node with the reason counted.
17
+ import { NODE_PATHS, nodeMajor, nodeVersion, planEdge, planPython, pythonSpecTools } from './plan.js'
18
+ import { bridgesPerMachine, edgeBridge } from './bridge.js'
19
+ import { RT_DEFAULT, runtimeConfig } from './runtime.js'
20
+ import { frameSite, iframeProbe } from './site.js'
21
+ import { SANDBOX } from './sbx/common.js'
22
+ import { filesGate } from './sbx/gate.js'
23
+ import { pythonModuleFor } from './python-module.js'
24
+ import { pythonCapMiB } from './python-plan.js'
25
+ import { FRAME_CAP_WHY, frameCapOf, hintOf } from './sbx/cap.js'
26
+
27
+ // The Worker form the first sandboxed frame of this page found (src/edge/sbx/common.js probeStrategy); the page's later frames try it first.
28
+ let wmHint = ''
29
+
30
+ /** What the browser needs for node in the frame: SharedArrayBuffer in a cross-origin isolated page, and wasm exceptions. */
31
+ export function edgeBrowserOk(g = globalThis) {
32
+ return typeof g.SharedArrayBuffer === 'function' && g.crossOriginIsolated === true && typeof g.WebAssembly?.Exception === 'function'
33
+ }
34
+
35
+ /** The reason of a setup that asked for a frame site another live container of the page already has (X5 check 2, F2). */
36
+ export const SITE_IN_USE = 'the frame site is in use'
37
+ /**
38
+ * X5 check 2, F2: a frame site has one live setup in a page. Two containers on one site are one browser origin: a program of one answers a
39
+ * BroadcastChannel message of the other and reads its storage, so the page keeps the rule "one origin per container" (D-582) itself. A setup
40
+ * holds its site from edgeSetupIn() (and again from a bootOption() after a close()) until close(). `share` (the option shareSite) lets
41
+ * containers that trust each other live on one site, and only when every one of them asked for it.
42
+ */
43
+ const sitesOf = new WeakMap() // page (its document) -> Map(origin -> {owners: Set, shared})
44
+ const NO_DOC = {}
45
+ const originKey = origin => {
46
+ try {
47
+ return new URL(origin).origin
48
+ } catch {
49
+ return String(origin)
50
+ }
51
+ }
52
+ function claimSite(doc, origin, owner, share) {
53
+ const page = doc || NO_DOC
54
+ const sites = sitesOf.get(page) || sitesOf.set(page, new Map()).get(page)
55
+ const key = originKey(origin)
56
+ const held = sites.get(key)
57
+ if (!held) return sites.set(key, { owners: new Set([owner]), shared: !!share }), true
58
+ if (held.owners.has(owner)) return true
59
+ if (!held.shared || !share) return false
60
+ return held.owners.add(owner), true
61
+ }
62
+ function releaseSite(doc, origin, owner) {
63
+ const sites = sitesOf.get(doc || NO_DOC)
64
+ const key = originKey(origin)
65
+ const held = sites?.get(key)
66
+ if (held?.owners.delete(owner) && !held.owners.size) sites.delete(key)
67
+ }
68
+
69
+ const idleOf = g => (typeof g.requestIdleCallback === 'function' ? f => g.requestIdleCallback(f, { timeout: 2000 }) : f => g.setTimeout(f, 0))
70
+
71
+ /**
72
+ * @param {object} o
73
+ * @param {string} [o.origin] the frame site's origin; none: the library makes the frame itself (a sandboxed frame) and the page fetches the files from o.base
74
+ * @param {object[]} [o.sources] the places the files of node come from when there is no origin, tried in order: {kind: 'tgz', url} | {kind: 'file', base} | {kind: 'url', url}
75
+ * @param {string|string[]} [o.base] the short form: one file base (or a list of them) is [{kind: 'file', base}]; with neither, the default of src/edge/base.js
76
+ * @param {{pins: object[], pkg: object|null}} [o.pinned] the pins of the files and the package they name (src/edge/pins.js loadEdgePins; boot.js edgeSetup loads it)
77
+ * @param {function} [o.fetchFiles] test hook: replaces the page's fetch of the files ({files, ...} or {error})
78
+ * @param {string[]} [o.env] the container's environment (its NODE_VERSION picks the node major; WMD_EDGE=0 turns it off)
79
+ * @param {string} [o.user] the container's user; [o.readonlyRoot], [o.hasTmpfs] as in planEdge
80
+ * @param {number} [o.p9port] the 9P service's port of the container's files (564) and [o.root] its `at` ('rootfs')
81
+ * @param {object} [o.settings] what linux.cjs reads (arch, hostname, cpus)
82
+ * @param {string} [o.rt] the runtime (src/edge/runtime.js, 'own'); [o.handIn] what the caller hands it
83
+ * @param {object} [o.watch] the frame watch's limits (src/edge/page.js runEdge); keepFrame defaults to true
84
+ * @param {boolean} [o.shareSite] true: this container may live on one frame site with others that say the same (they are not kept apart)
85
+ * @param {number} [o.frameCap] the most frames of node this page has alive at once (default by browser, src/edge/sbx/cap.js); a start that needs a new one over it runs in the guest
86
+ * @param {boolean} [o.prepare] false: no frame is made before the first node command (default true, with keepFrame)
87
+ * @param {function} [o.onLog] (id, record) of each run, and the site's events ({type: 'site', ...})
88
+ * @param {function} [o.onBridge] (bridge) when a machine's bridge is made
89
+ * @param {{on: number, off: object}} counts the plan's decisions, counted (src/boot.js edgePlanCounts)
90
+ */
91
+ export function edgeSetupIn(o, counts) {
92
+ const { origin: siteOrigin, sources, base, pinned = null, fetchFiles: fetchFilesOpt, fetchOpts = {}, filesWaitMs, filesRetryMs, filesProgressMs, frameCap: frameCapOpt, python: pythonAsk, imagePython, pythonMaxMiB, fetchPython: fetchPythonOpt, ramMiB = 0, main = [], memoryMB = 0, swapMB = 0, env = [], user = '', readonlyRoot = false, hasTmpfs = false, p9port = 564, root = 'rootfs', settings = {}, rt = RT_DEFAULT, handIn = null, watch = {}, prepare = true, shareSite = false, edgeWasm = '/wasm/edgejs.wasm', onLog = () => {}, onBridge = () => {}, doc = globalThis.document, win = globalThis } = o
93
+ const sandbox = !siteOrigin
94
+ const origin = sandbox ? SANDBOX : siteOrigin
95
+ // X25: python in the frame follows the switch of node (`edge`) and has its own, `python: false`; the page's plan for the image's python is planPython
96
+ // (src/edge/plan.js; `imagePython` is what the caller found in the image: src/edge/python-plan.js findPython and imagePythonVersion)
97
+ const common = { enabled: true, env, user, readonlyRoot, hasTmpfs, hasJspi: edgeBrowserOk(win), rt }
98
+ const nodePlan = planEdge({ ...common, nodePath: NODE_PATHS[0] })
99
+ const plan = nodePlan
100
+ const capMiB = pythonMaxMiB || pythonCapMiB({ memoryMB, swapMB, ramMiB }) // the python's memory cap follows the machine (page option pymax decides when given)
101
+ const pyPlan = imagePython ? planPython({ ...common, python: pythonAsk, imagePython, memoryMB, swapMB, ramMiB }) : { use: false, reason: 'no python asked for' }
102
+ const off = reason => {
103
+ counts.off[reason] = (counts.off[reason] || 0) + 1
104
+ return { use: false, reason, edgeNode: undefined, edgeTools: [], bootOption: () => undefined, prepare: () => null, close: () => {}, bridge: () => null, site: null, prepared: null }
105
+ }
106
+ if (!nodePlan.use && !pyPlan.use) {
107
+ // neither: the reason is the one of the runtime the image is for (a node image says node's; an image with no NODE_VERSION says python's)
108
+ return off(imagePython && !nodeMajor(env) ? pyPlan.reason : nodePlan.reason)
109
+ }
110
+ // a cap of none (a page's own `frameCap: 0`, src/edge/sbx/cap.js): node and python run in the guest, one calm reason, nothing fetched or made
111
+ if (sandbox && frameCapOf(win.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? '', frameCapOpt) === 0) return off(FRAME_CAP_WHY(0))
112
+ if (imagePython && !pyPlan.use && nodePlan.use && pythonAsk !== false) counts.off[`python: ${pyPlan.reason}`] = (counts.off[`python: ${pyPlan.reason}`] || 0) + 1
113
+ // the module the idle prepare compiles: node's when node is on (as before), else the image python's (python only for an image that has no node)
114
+ const mainIsPython = pyPlan.use && /^python/.test(String(main[0] || '').split('/').pop())
115
+ const pyMod = pyPlan.use ? pythonModuleFor(pyPlan.version) : null
116
+ const nodeWasm = sandbox ? 'sbx:edgejs.wasm' : edgeWasm
117
+ const prepWasm = nodePlan.use && !mainIsPython ? nodeWasm : sandbox ? `sbx:${pyMod.file}` : pyMod.url
118
+ const owner = {} // this setup's token: its kept frames, its users of the site and its hold of the site are its own (src/edge/page.js, P1)
119
+ if (!sandbox && !claimSite(doc, origin, owner, shareSite)) {
120
+ onLog(0, { type: 'site', inUse: true, origin })
121
+ return off(SITE_IN_USE)
122
+ }
123
+ counts.on++
124
+ const keepFrame = watch.keepFrame !== false
125
+ // the sandboxed frame: the page fetches and checks the files (src/edge/sbx/files.js) and hands them in; the frame's code is generated text (frame-code.gen.js)
126
+ let codeP = null
127
+ let hookP = null // the test hook's one fetch (a result with an error is not kept)
128
+ const copyAll = f => Object.fromEntries(Object.entries(f).map(([k, v]) => [k, v.slice(0)]))
129
+ const sbx = !sandbox ? null : {
130
+ code: null,
131
+ loadCode: () => (codeP ||= import('./frame-code.gen.js').then(m => (sbx.code = m.FRAME_CODE))),
132
+ hint: () => wmHint || hintOf(win.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? ''), // what this page's first frame found, else the engine's usual form (an order: the probe still decides)
133
+ frameCap: frameCapOf(win.navigator?.userAgent ?? globalThis.navigator?.userAgent ?? '', frameCapOpt), // the most frames this page has alive at once (src/edge/sbx/cap.js)
134
+ onCaps: c => void (c && c.worker && (wmHint = c.worker)),
135
+ // one fetch for the page's life (src/edge/sbx/files.js fetchEdgeFilesOnce): the prepare frame and the run frame ask for the same files, and every
136
+ // asker gets its own copy of the bytes (a frame takes its files by transfer, which empties what it was given). The gate (src/edge/sbx/gate.js)
137
+ // owns the download: it starts once, a node start waits for it at most FILES_WAIT_MS, and its events tell the page what it did.
138
+ files: async () => {
139
+ const r = await gate.join()
140
+ if (r.error) return r
141
+ const files = copyAll(r.files)
142
+ // python's module goes with them once it is in (a start that needs it waits for the gate below; a failed gate leaves python in the guest)
143
+ if (pyGate && pyGate.state() === 'ready') {
144
+ const pr = await pyGate.join()
145
+ if (!pr.error) Object.assign(files, copyAll(pr.files))
146
+ }
147
+ return { ...r, files }
148
+ },
149
+ }
150
+ const gate = !sandbox
151
+ ? null
152
+ : filesGate({
153
+ get: onProgress =>
154
+ fetchFilesOpt
155
+ ? (hookP ||= Promise.resolve().then(fetchFilesOpt).then(r => (r && r.error && (hookP = null), r), e => ((hookP = null), Promise.reject(e))))
156
+ : import('./sbx/files.js').then(m => m.fetchEdgeFilesOnce({ ...fetchOpts, sources, base, pins: pinned && pinned.pins, pkg: pinned && pinned.pkg, onProgress })),
157
+ onEvent: e => onLog(0, e),
158
+ ...(filesWaitMs !== undefined ? { waitMs: filesWaitMs } : {}),
159
+ ...(filesRetryMs !== undefined ? { retryMs: filesRetryMs } : {}),
160
+ ...(filesProgressMs !== undefined ? { progressMs: filesProgressMs } : {}),
161
+ })
162
+ // X25: python's module is a second package (@threadedstack/wmd-python, the pins of src/edge/python-pins.js), fetched by its own gate and handed to the frame
163
+ // with the other files. Only when the page's plan took the image's python; `python: false` makes no gate and no request.
164
+ const pyGate = !sandbox || !pyPlan.use
165
+ ? null
166
+ : filesGate({
167
+ get: () =>
168
+ fetchPythonOpt
169
+ ? Promise.resolve().then(fetchPythonOpt)
170
+ : import('./python-source.js').then(m => m.fetchPythonModule(pyPlan.version)).then(r => (r.error ? r : { files: { python: r.bytes }, source: r.source, reasons: r.reasons })),
171
+ onEvent: e => onLog(0, { ...e, python: true }),
172
+ ...(filesWaitMs !== undefined ? { waitMs: filesWaitMs } : {}),
173
+ ...(filesRetryMs !== undefined ? { retryMs: filesRetryMs } : {}),
174
+ ...(filesProgressMs !== undefined ? { progressMs: filesProgressMs } : {}),
175
+ })
176
+ const site = frameSite({ origin, probe: sandbox ? () => sbx.files().then(r => !r.error) : iframeProbe({ doc, win }), onEvent: e => onLog(0, e) })
177
+ // what a start waits for: node's files (the gate of item 12); and when the page planned python, python's module too. A start that is python's goes to the guest while
178
+ // python's module is loading or when its fetch failed; a start of node goes to the guest only while it is loading (a failed fetch leaves python in the guest).
179
+ const gateFor = async job => {
180
+ if (!sandbox) return null
181
+ const g = await gate.forStart()
182
+ if (g || !pyGate) return g
183
+ const isPython = !!(job && job.cfg && job.cfg.python)
184
+ const pg = await pyGate.forStart()
185
+ if (pg && (isPython || pyGate.state() === 'loading')) return { ...pg, reason: String(pg.reason).replace("node's files", "python's module") }
186
+ if (isPython) {
187
+ const r = await gate.join()
188
+ if (!r.error && !(r.files && r.files.linuxpy)) return { fallback: true, reason: "the pins of the frame's files have no linux.py (the shim of python)" }
189
+ }
190
+ return null
191
+ }
192
+ let current = null
193
+ const pers = new Set() // every boot option's bridges: close() reaches all of them (X5 fix3p P5)
194
+ // one bridge per machine (src/edge/bridge.js bridgesPerMachine), made when its first message comes; each boot option has its own (a second
195
+ // machine of the page, booted with its own options, keeps its own bridges), and the site is the page's: a restore keeps what it knows
196
+ const bootOption = () => {
197
+ const mine = bridgesPerMachine(machine => {
198
+ current = edgeBridge({
199
+ site,
200
+ vm: machine,
201
+ p9port,
202
+ origin,
203
+ ...(sandbox ? { linuxSrc: 'sbx:linux.cjs' } : {}),
204
+ python: pyPlan.use ? { path: pyPlan.python, version: pyPlan.version, maxMiB: capMiB } : null,
205
+ settings: { arch: 'arm64', hostname: 'wmd-web', cpus: 1, ...settings, execPath: plan.node },
206
+ rt,
207
+ handIn: sandbox ? { ...handIn, sbx: true } : handIn,
208
+ edgeWasm: sandbox ? 'sbx:edgejs.wasm' : edgeWasm,
209
+ nodeVersion: nodeVersion(env), // the image's node version: the frame's node reports it (check5 F5)
210
+ watch: { ...watch, keepFrame },
211
+ // a sandboxed frame needs the files first: a start that finds them still loading after FILES_WAIT_MS runs in the guest (the bridge answers a result with
212
+ // `fallback` so; it is no failure of the frame)
213
+ run: (...a) => gateFor(a[0]).then(g => g || Promise.all([import('./page.js'), sandbox ? sbx.loadCode() : null]).then(([{ runEdge }]) => runEdge({ ...a[0], owner, ...(sandbox ? { sbx } : {}) }, ...a.slice(1)))),
214
+ onLog,
215
+ doc,
216
+ owner,
217
+ })
218
+ onBridge(current)
219
+ return current
220
+ })
221
+ pers.add(mine)
222
+ // F2: a boot after close() takes the site again; when another container took it meanwhile this option only refuses (the guest runs node)
223
+ if (!sandbox && !claimSite(doc, origin, owner, shareSite)) mine.close()
224
+ return {
225
+ port: p9port,
226
+ root,
227
+ rt, // the runtime decides what the service looks at before a start (children, listing size: src/edge/runtime.js)
228
+ busy: () => mine.busy(),
229
+ onMessage: (m, machine) => mine.onMessage(m, machine),
230
+ }
231
+ }
232
+ const e = {
233
+ use: true,
234
+ reason: '',
235
+ edgeNode: nodePlan.use ? plan.node : undefined,
236
+ prepares: prepWasm, // the module the idle prepare compiles: node's, unless the image has no node or its main program is python
237
+ edgeTools: pyPlan.use ? pythonSpecTools(pyPlan.python) : [], // the stub over the image's python (containerBundle's edge.tools)
238
+ python: pyPlan.use ? { path: pyPlan.python, version: pyPlan.version } : undefined,
239
+ bootOption,
240
+ site,
241
+ bridge: () => current,
242
+ prepared: null,
243
+ pythonReady: () => (pyGate ? pyGate.begin() : Promise.resolve(null)), // python's module: the one download (the prepare starts it too); tests and the page's progress read it
244
+ files: sbx ? sbx.files : undefined, // the page's fetch of the files of node (shared by the frames of this page)
245
+ /**
246
+ * X5 default1 round 2 (B2.2): the frame of the site is made when the page is idle and fetches and compiles the runtime and node
247
+ * (src/edge/page.js prepareEdge), so that the first node command compiles nothing. Once per setup; none without kept frames. A frame
248
+ * whose page loads without the frame's script (nothing answers at the site) marks the site down: node commands then run in the guest at
249
+ * once, with the reason.
250
+ */
251
+ prepare() {
252
+ if (!prepare || !keepFrame || e.prepared) return e.prepared
253
+ const p = (e.prepared = { asked: Math.round(performance.now()) })
254
+ const go = async () => {
255
+ if (sandbox) pyGate?.begin() // python's module comes with them
256
+ if (sandbox) gate.begin() // the files come while the frame is made (a node start finds them in, or waits at most FILES_WAIT_MS)
257
+ const { prepareEdge } = await import('./page.js')
258
+ if (sandbox) await sbx.loadCode()
259
+ const cfg = { rt, ...runtimeConfig(rt, sandbox ? { ...handIn, sbx: true } : handIn), edgeWasm: prepWasm, ...(sandbox ? { linuxSrc: 'sbx:linux.cjs' } : {}), linux: {}, ...(pyPlan.use && prepWasm !== nodeWasm ? { memoryMaxMiB: capMiB } : {}) }
260
+ p.started = Math.round(performance.now())
261
+ const r = await prepareEdge({ origin, cfg, doc, win, owner, ...(sandbox ? { sbx } : {}) })
262
+ Object.assign(p, r, { ended: Math.round(performance.now()) })
263
+ if (r.down) site.markDown(r.error)
264
+ else if (r.errorKind === 'runtime') site.markDown(r.error, { kind: 'runtime' }) // X5 fix2 F4: a file of the runtime, the program or the settings did not load
265
+ }
266
+ idleOf(win)(() => go().catch(err => (p.error = String((err && err.message) || err).slice(0, 200))))
267
+ return p
268
+ },
269
+ close() {
270
+ pers.forEach(per => per.close())
271
+ if (!sandbox) releaseSite(doc, origin, owner)
272
+ },
273
+ }
274
+ return e
275
+ }
package/src/edge/shim.js CHANGED
@@ -143,7 +143,9 @@ const SIG_EMIT_TO = ` if (process.listenerCount(name) > 0) {
143
143
  process.emit(name, name, sig);
144
144
  } else if (SIG_IGNORED.has(sig)) {
145
145
  // the default action of this signal leaves the program running
146
- } else {`
146
+ } else {
147
+ // the default action ends the program: the page learns it, so that the stub dies of the signal as node in the guest does (R4)
148
+ try { ctl({ op: 'signal_taken', n: sig, handled: false }); } catch (_) {}`
147
149
 
148
150
  export function shimSource(src, settings, { symlinks = true } = {}) {
149
151
  for (const [name, text] of [['settings marker', SETTINGS_MARKER], ['__wmdCtl take', TAKE], ['ctlError', LINKS_MARKER], ['signal table', SIG_TABLE_FROM], ['signal emit', SIG_EMIT_FROM]]) {
@@ -0,0 +1,101 @@
1
+ // X5 fix3 R5: the watchers of the frame's fs.watch (linux.cjs's FSWatcher: watch_start, watch_poll_all, watch_stop). WASIX has no inotify and the page
2
+ // has no event from the machine's Overlay, so the page compares scans of it: the names below the watched directory (or the watched file) with the
3
+ // last scan, and reports what node's inotify watcher reports: `rename` for a name that came, went or is another inode now, `change` for a file whose
4
+ // size or mtime changed and for a regular file that was made (its first write or touch). The files of the guest and of the frame are the same Overlay, so a write by either shows. The scan runs at most every
5
+ // max(MIN_SCAN_MS, 5 times what the last scan cost) ms for each watcher (the shim asks every 10 ms), and a scan reads at most MAX_ENTRIES names.
6
+
7
+ import { S_IFDIR, S_IFMT, S_IFREG } from '../fs/pack.js'
8
+
9
+ export const MIN_SCAN_MS = 50
10
+ export const MAX_ENTRIES = 50_000
11
+ export const MAX_WATCHERS = 1024
12
+ const utf8 = b => new TextDecoder().decode(Uint8Array.from(b, c => c.charCodeAt(0)))
13
+
14
+ export class PathWatches {
15
+ /** @param {import('../fs/overlay.js').Overlay} fs @param {() => number} now milliseconds */
16
+ constructor(fs, now) {
17
+ this.fs = fs
18
+ this.now = now
19
+ this.list = new Map()
20
+ this.nextId = 0
21
+ }
22
+
23
+ /** Start watching a node (a directory or a file). Returns the id, or null when there are too many watchers. */
24
+ start(node, name, recursive) {
25
+ if (this.list.size >= MAX_WATCHERS) return null
26
+ const w = { id: ++this.nextId, node, name, recursive: !!recursive, isDir: this.#isDir(node), snap: null, last: 0, interval: MIN_SCAN_MS, gone: false }
27
+ this.#rescan(w)
28
+ this.list.set(w.id, w)
29
+ return w.id
30
+ }
31
+
32
+ stop(id) {
33
+ this.list.delete(Number(id))
34
+ }
35
+
36
+ /** The events of every watcher whose turn it is: [{id, eventType, filename}]. */
37
+ poll() {
38
+ const events = []
39
+ for (const w of this.list.values()) {
40
+ const t = this.now()
41
+ if (t - w.last < w.interval) continue
42
+ const before = w.snap
43
+ this.#rescan(w)
44
+ const oldInodes = new Set([...before.values()].map(v => v.split(':', 1)[0]))
45
+ for (const [name, sig] of w.snap) {
46
+ const old = before.get(name)
47
+ if (old === undefined) {
48
+ events.push({ id: w.id, eventType: 'rename', filename: name })
49
+ // a file made (not one moved in from another name) has been written or touched too: inotify's IN_MODIFY / IN_ATTRIB, which node reports as `change`
50
+ const [ino, type] = sig.split(':')
51
+ if (!oldInodes.has(ino) && Number(type) === S_IFREG) events.push({ id: w.id, eventType: 'change', filename: name })
52
+ } else if (old !== sig) events.push({ id: w.id, eventType: old.split(':', 2).join(':') !== sig.split(':', 2).join(':') ? 'rename' : 'change', filename: name })
53
+ }
54
+ for (const name of before.keys()) if (!w.snap.has(name)) events.push({ id: w.id, eventType: 'rename', filename: name })
55
+ }
56
+ return events
57
+ }
58
+
59
+ #isDir(n) {
60
+ return (this.fs.getattr(n).mode & S_IFMT) === S_IFDIR
61
+ }
62
+
63
+ // sig: "ino:type" for what makes a name another thing, then ":size:mtime" for a file
64
+ #sig(n) {
65
+ const a = this.fs.getattr(n)
66
+ const type = a.mode & S_IFMT
67
+ return type === S_IFDIR ? `${a.ino}:${type}` : `${a.ino}:${type}:${a.size}:${a.mtime}`
68
+ }
69
+
70
+ #rescan(w) {
71
+ const t0 = this.now()
72
+ const snap = new Map()
73
+ if (!w.isDir) {
74
+ // a file: its own name; a file with no name left is gone (one `rename`, then nothing)
75
+ const a = this.fs.getattr(w.node)
76
+ if (a.nlink > 0 && !w.gone) snap.set(w.name, this.#sig(w.node))
77
+ else w.gone = true
78
+ } else {
79
+ let budget = MAX_ENTRIES
80
+ const walk = (dir, prefix) => {
81
+ let l
82
+ try {
83
+ l = this.fs.listing(dir)
84
+ } catch {
85
+ return
86
+ }
87
+ for (let i = 0; i < l.names.length && budget > 0; i++, budget--) {
88
+ const name = prefix + utf8(l.names[i])
89
+ const n = l.nodes[i]
90
+ snap.set(name, this.#sig(n))
91
+ if (w.recursive && (this.fs.getattr(n).mode & S_IFMT) === S_IFDIR) walk(n, name + '/')
92
+ }
93
+ }
94
+ walk(w.node, '')
95
+ }
96
+ w.snap = snap
97
+ const t1 = this.now()
98
+ w.interval = Math.max(MIN_SCAN_MS, 5 * (t1 - t0))
99
+ w.last = t1
100
+ }
101
+ }
@@ -14,6 +14,14 @@ import { SPAWN_EXIT, markScanner, newSpawnMark } from './spawn-guard.js'
14
14
 
15
15
  installWasmCounters(globalThis) // fix7 item 15
16
16
  const log = text => postMessage({ type: 'log', text })
17
+ // X5 fix2 F4 (hold 1): the text of an error that ends a run. The page shows its first line (a fallback's reason). Chromium's stack starts with the message;
18
+ // Firefox's and Safari's list frames only, so the message goes first and the stack after it.
19
+ const errorText = e => {
20
+ const stack = e && e.stack ? String(e.stack) : ''
21
+ const msg = e && e.message !== undefined ? `${e.name || 'Error'}: ${e.message}` : ''
22
+ if (!msg) return stack || String(e)
23
+ return stack.startsWith(msg) ? stack : stack ? msg + '\n' + stack : msg
24
+ }
17
25
  const dec = new TextDecoder()
18
26
  const enc = new TextEncoder()
19
27
  let adapter = null
@@ -37,8 +45,24 @@ async function input(m) {
37
45
  else if (m.signal) await adapter.signal(proc, m.signal) // the page sends only the signals that end a program (src/edge/bridge.js)
38
46
  }
39
47
 
40
- onmessage = async ({ data: { cfg, ports, in: inp } }) => {
48
+ onmessage = async ({ data: { cfg, ports, in: inp, tf, kept, prepare } }) => {
41
49
  if (inp) return input(inp)
50
+ if (prepare) {
51
+ // X5 default1 round 2 (B2.2): no program runs; the adapter makes ready what the frame keeps for the starts to come (frame.js, page.js prepareEdge)
52
+ try {
53
+ const t0 = performance.now()
54
+ adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg)
55
+ const r = adapter.prepare ? await adapter.prepare({ cfg, kept }) : { kept: false }
56
+ const k = adapter.keep ? adapter.keep() : null
57
+ if (k) postMessage({ type: 'keep', keep: k })
58
+ return done({ prepared: !!k, prepareMs: Math.round(performance.now() - t0), ...(r.stages ? { stages: r.stages } : {}) })
59
+ } catch (e) {
60
+ const kind = errorKindOf(e, false) // X5 fix2 F4: a prepare that finds the runtime's files missing says so (the page marks the site down)
61
+ return done({ error: String((e && e.message) || e).slice(0, 300), ...(kind ? { errorKind: kind } : {}) })
62
+ }
63
+ }
64
+ // X5 default1 round 2 (B2.1): when the frame made this Worker and when its script ran (the adapter takes them with the option marks)
65
+ if (typeof tf === 'number') globalThis.__wmdFwMarks = { frame: tf, fw: performance.timeOrigin + performance.now() }
42
66
  const res = {}
43
67
  let loading = true // fix7 F12: an error while the runtime's files load is told to the page as such (it remembers it)
44
68
  try {
@@ -47,6 +71,7 @@ onmessage = async ({ data: { cfg, ports, in: inp } }) => {
47
71
  const loaded = await adapter.load({
48
72
  cfg,
49
73
  ports,
74
+ kept, // X5 default1 round 2 (B2.1): what an earlier start of this frame left (frame.js); an adapter that keeps nothing ignores it
50
75
  log,
51
76
  onWorkerError: why => done({ error: 'the runtime lost a Worker: ' + why }),
52
77
  })
@@ -63,11 +88,15 @@ onmessage = async ({ data: { cfg, ports, in: inp } }) => {
63
88
  files: cfg.files,
64
89
  linux: cfg.linux,
65
90
  linuxSrc: cfg.linuxSrc,
91
+ python: cfg.python, // X25 gate 1
66
92
  stdin: cfg.stdin || 'closed',
67
93
  timeoutMs: cfg.timeoutMs,
68
94
  parallelism: cfg.parallelism,
69
95
  })
70
96
  res.setupMs = performance.now() - t0
97
+ // X5 default1 round 2 (B2.1): the compiled modules and the program's bytes for the frame to keep (frame.js; never relayed to the page)
98
+ const k = adapter.keep ? adapter.keep() : null
99
+ if (k) postMessage({ type: 'keep', keep: k })
71
100
  log('process started after ' + res.setupMs.toFixed(0) + ' ms')
72
101
  const t1 = performance.now()
73
102
  postMessage({ type: 'step', name: 'ready', ms: res.setupMs }) // the process runs: the page may tell the guest it has started
@@ -113,7 +142,7 @@ onmessage = async ({ data: { cfg, ports, in: inp } }) => {
113
142
  Object.assign(res, await adapter.stats())
114
143
  // no adapter.teardown(): the runtime's Workers end when the frame terminates this one (fix9, see done)
115
144
  } catch (e) {
116
- res.error = String((e && e.stack) || e)
145
+ res.error = errorText(e)
117
146
  const kind = errorKindOf(e, loading) // fix 11 (F-M): the runtime's wasm that is missing is found in start(), after load()
118
147
  if (kind) res.errorKind = kind
119
148
  }
@@ -4,7 +4,7 @@
4
4
  // planOf({ sources, pins, packages, limits }) the table made in memory from the pins (src/gowasm/pins-data.js, a JS module: no request) and the
5
5
  // ordered sources (src/host/pinned-fetch.js: tgz of the npm registry, file under a base, url)
6
6
  // tableFromPins(pins, packages, sources) the table
7
- // GOWASM_SOURCES_DEFAULT ONE constant: the sources used when the embedder names none. null for now: with none, the twin is off
7
+ // GOWASM_SOURCES_DEFAULT ONE constant: the sources used when the embedder names none (the registry, jsDelivr, unpkg)
8
8
  // The twin's module is fetched by the twin's Worker on first use from the first source that gives the pinned sha256, and kept in Cache Storage.
9
9
  // `gowasmSetup({ table: '/own/tools.json' })` is the override that reads a table an app serves itself, with its own modules.
10
10
  // The module imports the table's guard and the pins alone, none of the twin's machine code (edge-go.js, its error texts, yamux): the twin's code is
@@ -13,12 +13,15 @@ import { loadToolsTable, normalizeTable, toolsTableProblem } from '../host/gowas
13
13
  import { PACKAGES, PINS } from './pins-data.js'
14
14
 
15
15
  /**
16
- * The sources the twin's modules are fetched from when the embedder names none: ONE constant. `null` for now (the public package does not exist yet): with no
17
- * sources and no table the twin is off, silently for a boot that named nothing. The flip sets it to the ordered list, the npm registry first:
18
- * [{ kind: 'tgz', url: 'https://registry.npmjs.org/{name}/-/{file}-{version}.tgz' }, { kind: 'file', base: 'https://cdn.jsdelivr.net/npm/{name}@{version}' },
19
- * { kind: 'file', base: 'https://unpkg.com/{name}@{version}' }]. Only the pins (pins-data.js PACKAGES) say which package and version.
16
+ * The sources the twin's modules are fetched from when the embedder names none: ONE constant, the ordered list, the npm registry first (CORS open, the
17
+ * official place), then two CDNs of the same package (jsDelivr refuses files over 50 MB, so it is a second place for the twin and not for X5's big files).
18
+ * An embedder that passes `gowasm: false` has the twin off. Only the pins (pins-data.js PACKAGES) say which package and version.
20
19
  */
21
- export const GOWASM_SOURCES_DEFAULT = null
20
+ export const GOWASM_SOURCES_DEFAULT = [
21
+ { kind: 'tgz', url: 'https://registry.npmjs.org/{name}/-/{file}-{version}.tgz' },
22
+ { kind: 'file', base: 'https://cdn.jsdelivr.net/npm/{name}@{version}' },
23
+ { kind: 'file', base: 'https://unpkg.com/{name}@{version}' },
24
+ ]
22
25
 
23
26
  /** Why a list of sources cannot be used, or null. A list is [{kind: 'tgz', url} | {kind: 'file', base} | {kind: 'url', url}]; https and http only. */
24
27
  export function sourcesProblem(sources) {
@@ -157,10 +157,11 @@ self.onmessage = e => {
157
157
  case 'edge-fs': {
158
158
  // X5 (edge=1 only): node's file requests, answered between 9P requests
159
159
  if (!host) throw new Error('the channel service has not started')
160
- edge ||= new EdgePorts(host.fsFor(m.port9p), { mounts: m.mounts, root: m.root || '' })
160
+ edge ||= new EdgePorts(host.fsFor(m.port9p), { mounts: m.mounts, root: m.root || '', ringMax: m.ringMax })
161
+ if (m.ringMax > 0) edge.ringMax = Math.floor(m.ringMax) // every run says it: the routes it makes keep that many calls
161
162
  if (m.own) {
162
163
  // the own runtime's port (src/edge/own/): its file messages and its children (a raw stream to the stub of this run)
163
- for (const p of m.ports || []) edge.attachOwn(p, { run: m.run || 0, root: m.root || '', job: m.job || 0, openExec: id => edgeSvc.openExec(id), onTraffic: kick, kickAll: !!m.kickAll, onSignalTaken: (n, handled) => edgeSvc.post({ t: 'edge', ev: 'signal-taken', id: m.job || 0, n, handled }) })
164
+ for (const p of m.ports || []) edge.attachOwn(p, { run: m.run || 0, root: m.root || '', job: m.job || 0, openExec: id => edgeSvc.openExec(id), net: id => edgeSvc.netFor(id), onTraffic: kick, kickAll: !!m.kickAll, onSignalTaken: (n, handled) => edgeSvc.post({ t: 'edge', ev: 'signal-taken', id: m.job || 0, n, handled }) })
164
165
  } else {
165
166
  const route = edge.routeFor({ mounts: m.mounts, root: m.root || '' }) // this run's own table (see EdgePorts.routeFor)
166
167
  for (const p of m.ports || []) edge.attach(p, route, m.run || 0)
@@ -284,15 +285,17 @@ async function init(m) {
284
285
  const restore = {}
285
286
  for (const svc of m.services || []) if (svc.restore) restore[svc.port] = new Uint8Array(svc.restore)
286
287
  let edgeAccept = null
288
+ let edgeFlushedHook = null
287
289
  if (m.edge) {
288
290
  const [port, service, hosted] = await Promise.all([import('../edge/service-port.js'), import('../edge/service-host.js'), import('./edge-host.js')])
289
291
  ;({ EdgePorts } = port)
290
292
  ;({ EdgeService } = service)
291
293
  ;({ EdgeHost, checkpointRefusal } = hosted)
292
294
  // X5 (edge=1 only): streams the guest opens on the control session are node starts (src/host/edge-host.js)
293
- edgeSvc = new EdgeService({ fs: fs[m.edge.port9p], root: m.edge.root || '', rt: m.edge.rt || '', post: msg => self.postMessage(msg) })
295
+ edgeSvc = new EdgeService({ fs: fs[m.edge.port9p], root: m.edge.root || '', rt: m.edge.rt || '', post: msg => self.postMessage(msg), cleanOf: id => !!edge?.jobClean(id) })
294
296
  const eh = (edgeHost = new EdgeHost({ start: (h, ctx) => edgeSvc.start(h, ctx) }))
295
297
  edgeAccept = s => (eh.accept(s), kick())
298
+ edgeFlushedHook = t => eh.flushed(t)
296
299
  }
297
300
  // X6 (default off): the compiler hand-off, for the 9P service that has a gowasm table
298
301
  const goSvc = m.gowasmPort ? (m.services || []).find(s => s.gowasm && fs[s.port]) : null
@@ -346,7 +349,7 @@ async function init(m) {
346
349
  }
347
350
  // edge-go.js not loadable: no host for the stub, which then runs its own compile (the state of any restore without a twin before this part)
348
351
  }
349
- host = new ChanHost(sab, { fs, consoleInputBytes: m.consoleInputBytes, yamuxPorts, netPost, restore, edge: goEdge, edgeAccept })
352
+ host = new ChanHost(sab, { fs, consoleInputBytes: m.consoleInputBytes, yamuxPorts, netPost, restore, edge: goEdge, edgeAccept, edgeFlushed: edgeFlushedHook })
350
353
  if (m.lockName && self.navigator?.locks?.request) {
351
354
  self.navigator.locks.request(m.lockName, () => {
352
355
  self.postMessage({ t: 'locked' })
@@ -423,7 +426,7 @@ function bindGoPort(p) {
423
426
 
424
427
  let twinOffWhy = null // fix 11 (F-N): why the twin's module did not load (noTwin), for the stats
425
428
  let lastStats = ''
426
- const withSpin = s => ({ ...s, spin: { ...spin, curUs: spinCur }, ...(twinOffWhy ? { gowasmOff: twinOffWhy } : {}), ...(edgeHost ? { edge: { ...edgeHost.stats, fallbackWhy: { ...edgeHost.stats.fallbackWhy }, look: { ...edgeSvc.stats }, route: edge ? (({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes }) => ({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes }))(edge.stats()) : null } } : {}) })
429
+ const withSpin = s => ({ ...s, spin: { ...spin, curUs: spinCur }, ...(twinOffWhy ? { gowasmOff: twinOffWhy } : {}), ...(edgeHost ? { edge: { ...edgeHost.stats, fallbackWhy: { ...edgeHost.stats.fallbackWhy }, look: { ...edgeSvc.stats }, route: edge ? (({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes, net, ownCalls }) => ({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes, net, ownCalls }))(edge.stats()) : null } } : {}) })
427
430
  let lastStatsAt = 0
428
431
  function maybePostStats() {
429
432
  const t = nowMs()
@@ -30,7 +30,7 @@
30
30
  import {
31
31
  CHAN_CONSOLE, CHAN_CONTROL, CHAN_NET, CHAN_P9, CONSOLE_IN_LIMIT, G2H, H2G, H_CIN_TAKEN, H_CLOSES, H_GONE, H_P9COUNT, KIND_NAMES, P9C_LOWER,
32
32
  P9C_NONE, P9C_UPPER, R_GONE, R_SHUT, RTT_BUCKETS, S_GEN, S_PORT, S_STATE, ST_CLOSING, ST_FREE, ST_OPEN, chanPorts, chanView, histSummary,
33
- p9cServed, ringAvail, ringKick, ringRead, ringSpace, ringWrite, rttBucket, stageNote,
33
+ p9cServed, ringAvail, ringBell, ringKick, ringRead, ringSpace, ringWrite, rttBucket, stageNote,
34
34
  } from './chan.js'
35
35
  import { NinePServer } from '../fs/9p/server.js'
36
36
  import { adoptServer, dumpService, loadService } from '../fs/svc-snapshot.js'
@@ -295,7 +295,7 @@ class ControlSession {
295
295
  ctl.epoch++
296
296
  this.epoch = ctl.epoch
297
297
  this.yamux = new YamuxClient({
298
- send: u8 => sess.out.push(u8),
298
+ send: u8 => (sess.out.push(u8), host.queuedOut()),
299
299
  keepAliveMs: host.ctlKeepAliveMs,
300
300
  onClose: why => host.ctlSessionDown(this, why),
301
301
  // streams the guest init opens ({"op":"edge"}): X6's compiler hand-off (default off) and X5's node host (edge=1 only)
@@ -417,7 +417,7 @@ export class ChanHost {
417
417
  * @param {number} [o.consoleInputBytes] console input (page -> guest) held at most (CONSOLE_IN_LIMIT)
418
418
  * @param {{accept: (s: object) => void, snapshot: () => object}} [o.edge] X6: takes the streams the guest opens on the control session (edge-go.js GoEdge)
419
419
  */
420
- constructor(sab, { fs = {}, onConsole, consoleInputBytes = CONSOLE_IN_LIMIT, yamuxPorts = [], ctlKeepAliveMs = 5000, netPost = null, restore = {}, edge = null, edgeAccept = null } = {}) {
420
+ constructor(sab, { fs = {}, onConsole, consoleInputBytes = CONSOLE_IN_LIMIT, yamuxPorts = [], ctlKeepAliveMs = 5000, netPost = null, restore = {}, edge = null, edgeAccept = null, edgeFlushed = null } = {}) {
421
421
  this.v = chanView(sab)
422
422
  this.edge = edge
423
423
  // P-B10: the network Worker (postMessage to it), and the net channel's session
@@ -431,6 +431,7 @@ export class ChanHost {
431
431
  this.restoredServers.set(Number(port), loadService(bytes, fs[port]))
432
432
  }
433
433
  this.yamuxPorts = new Set(yamuxPorts)
434
+ this.edgeFlushed = edgeFlushed // X25 gate 2e: called with the page's clock when a flush of the control session put bytes into the guest's ring (edge-host.js flushed)
434
435
  this.edgeAccept = edgeAccept // X5 (edge=1 only): called with each stream the guest opens on the control session; none: refused
435
436
  this.ctlKeepAliveMs = ctlKeepAliveMs
436
437
  // P-B11: the control session and the page's streams on it (k -> YamuxStream)
@@ -451,6 +452,17 @@ export class ChanHost {
451
452
  errors: [],
452
453
  }
453
454
  this.stopped = false
455
+ this.stepping = false // inside step(): what is queued for the guest is flushed by this step
456
+ }
457
+
458
+ /**
459
+ * Bytes were queued for the guest. Inside a step the step flushes them. Outside one (a promise job: the edge host's answer to a
460
+ * stub's hello after its owner decided, X5 B2.3) nothing would take them to the guest until the guest next rang the doorbell or the
461
+ * service's 500 ms wait ran out (chan-service.js loop()), and the guest waited idle for them: ring the doorbell, so the service's
462
+ * next step sends them.
463
+ */
464
+ queuedOut() {
465
+ if (!this.stepping) ringBell(this.v)
454
466
  }
455
467
 
456
468
  /** Queue an event for the page (chan-service.js posts ctlEvents after each step). */
@@ -677,6 +689,15 @@ export class ChanHost {
677
689
 
678
690
  /** One pass over every channel. Returns true if anything moved. */
679
691
  step() {
692
+ this.stepping = true
693
+ try {
694
+ return this.#step()
695
+ } finally {
696
+ this.stepping = false
697
+ }
698
+ }
699
+
700
+ #step() {
680
701
  const v = this.v
681
702
  const i32 = v.i32
682
703
  if (Atomics.load(i32, H_GONE)) {
@@ -736,13 +757,16 @@ export class ChanHost {
736
757
  sess.impl.tick?.()
737
758
  const before = sess.out.bytes
738
759
  let wrote = sess.out.flush(v, h)
760
+ if (wrote && sess.kind === CHAN_CONTROL) this.edgeFlushed?.()
739
761
  if (sess.kind === CHAN_CONSOLE && wrote) Atomics.add(v.i32, H_CIN_TAKEN, wrote) // console input taken by the ring
740
762
  if (!sess.broken && sess.impl.pending() && sess.out.bytes < OUT_LIMIT) {
741
763
  // requests held back while the replies were not read
742
764
  const n = sess.impl.pending()
743
765
  sess.impl.process(sess)
744
766
  if (sess.impl.pending() !== n) work = true
745
- wrote += sess.out.flush(v, h)
767
+ const w1 = sess.out.flush(v, h)
768
+ if (w1 && sess.kind === CHAN_CONTROL) this.edgeFlushed?.()
769
+ wrote += w1
746
770
  }
747
771
  if (wrote) {
748
772
  ks.bytesOut += wrote
@@ -764,6 +788,7 @@ export class ChanHost {
764
788
  work = true
765
789
  sess.impl.data(sess, this.inbuf.subarray(0, n))
766
790
  const w2 = sess.out.flush(v, h)
791
+ if (w2 && sess.kind === CHAN_CONTROL) this.edgeFlushed?.()
767
792
  if (sess.kind === CHAN_CONSOLE && w2) Atomics.add(v.i32, H_CIN_TAKEN, w2)
768
793
  ks.bytesOut += w2
769
794
  }