@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.
- package/README.md +23 -2
- package/RELEASE.json +123 -16
- package/guest/arm64/Image +1 -1
- package/guest/arm64/Image-4k +1 -1
- package/guest/arm64/initramfs.cpio.gz +0 -0
- package/package.json +3 -3
- package/src/boot.js +47 -2
- package/src/edge/bridge.js +297 -0
- package/src/edge/codes.js +10 -0
- package/src/edge/ctl.js +199 -0
- package/src/edge/error-kind.js +4 -0
- package/src/edge/frame.html +4 -0
- package/src/edge/frame.js +48 -0
- package/src/edge/fs-route.js +301 -0
- package/src/edge/hist.js +46 -0
- package/src/edge/msg.js +106 -0
- package/src/edge/node-args.js +194 -0
- package/src/edge/node-guest-opts.js +108 -0
- package/src/edge/node-opts.js +82 -0
- package/src/edge/own/adapter.js +271 -0
- package/src/edge/own/capi.js +200 -0
- package/src/edge/own/child-host.js +196 -0
- package/src/edge/own/fs-bridge.js +71 -0
- package/src/edge/own/fs-own-route.js +356 -0
- package/src/edge/own/guest-spawner.js +235 -0
- package/src/edge/own/hub.js +430 -0
- package/src/edge/own/loader.js +81 -0
- package/src/edge/own/memcap.js +95 -0
- package/src/edge/own/payload-size.js +15 -0
- package/src/edge/own/pool.js +160 -0
- package/src/edge/own/procfs.js +84 -0
- package/src/edge/own/serdes-codec.js +317 -0
- package/src/edge/own/service-receiver.js +98 -0
- package/src/edge/own/shim-post.js +185 -0
- package/src/edge/own/stack-fix.js +36 -0
- package/src/edge/own/stdio-pipe.js +80 -0
- package/src/edge/own/v8-serdes.js +970 -0
- package/src/edge/own/wasm-counters.js +144 -0
- package/src/edge/own/worker.js +97 -0
- package/src/edge/page.js +162 -0
- package/src/edge/plan.js +65 -0
- package/src/edge/resolve.js +44 -0
- package/src/edge/runtime.js +94 -0
- package/src/edge/sdk/adapter.js +151 -0
- package/src/edge/sdk/forward.js +80 -0
- package/src/edge/sdk/napi-stub.js +50 -0
- package/src/edge/sdk/relay.js +17 -0
- package/src/edge/service-host.js +382 -0
- package/src/edge/service-port.js +245 -0
- package/src/edge/shim.js +161 -0
- package/src/edge/site.js +106 -0
- package/src/edge/spawn-guard.js +80 -0
- package/src/edge/tz.js +103 -0
- package/src/edge/worker.js +121 -0
- package/src/edge/workers.js +27 -0
- package/src/host/chan-service.js +75 -8
- package/src/host/chan-services.js +77 -3
- package/src/host/ctl.js +26 -5
- package/src/host/edge-go.js +7 -3
- package/src/host/edge-host.js +327 -0
- package/src/host/yamux.js +21 -8
- package/wmdpack.wasm +0 -0
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
// X5 part B (page switch edge=1 only): the page's end of the guest's node starts. The channel service (src/edge/service-host.js)
|
|
2
|
+
// posts {t:'edge', ev:'start', id, hello, mounts} when the guest's edge stub asks for a node run; this runs it in an isolated frame
|
|
3
|
+
// (src/edge/page.js) and answers through `answer` ({id, ev: 'reply'|'out'|'exit', ...}, vm.edgeMessage). Input from the guest
|
|
4
|
+
// (stdin, end of input, signals, "gone") comes as later messages with the same id.
|
|
5
|
+
//
|
|
6
|
+
// const b = edgeBridge({ vm, p9port, origin, settings, yieldMs, run, rt, site }) b.onMessage(m) b.stats()
|
|
7
|
+
// vm: the machine this bridge belongs to ({edgeFs, edgeMessage, edgeYield, edgeRelease}); one bridge per machine, made when its first
|
|
8
|
+
// message comes (a restore makes a new machine and so a new bridge: the old one's machine has ended)
|
|
9
|
+
// settings: what linux.cjs reads (arch, execPath, hostname, cpus, ...), uid and gid come from each hello
|
|
10
|
+
// run: runEdge (replaced in tests)
|
|
11
|
+
// nodeVersion: the image's node version ('v24.22.3', plan.js nodeVersion): the frame's node reports it (check5 F5)
|
|
12
|
+
// rt: the runtime (src/edge/runtime.js); handIn: what the page's caller handed the runtime in (pageRuntime(), rt=sdk only)
|
|
13
|
+
// site: what the page remembers about the frame's site (src/edge/site.js, one per page): a start whose frame never loaded marks it down, and while it is
|
|
14
|
+
// down every node run goes to the guest at once with the reason (check4 F3)
|
|
15
|
+
//
|
|
16
|
+
// Signals from the guest (the program's own process group, `kill`): on rt=own the program gets the signal itself (a handler runs; without one it ends as
|
|
17
|
+
// node does with 128 + n; a program that does not end within the grace period is cut off). On rt=sdk the ones whose default action ends a program end it
|
|
18
|
+
// as in the guest, with the guest's exit code (128 + n; INT gives 130); the ones whose default is to be ignored are dropped, and a handler is not run:
|
|
19
|
+
// that runtime has no such call (the bar tests in web/test/edge-bar/).
|
|
20
|
+
//
|
|
21
|
+
// A run is {ready: false} until the frame's worker says its process runs; then the guest is told ok. A frame that ends before
|
|
22
|
+
// that (a listing the SDK cannot take, a start error) is a fallback: the stub runs the image's node in the guest.
|
|
23
|
+
|
|
24
|
+
import { RT_DEFAULT, deliversSignals, runtimeConfig } from './runtime.js'
|
|
25
|
+
import { frameCounts } from './page.js'
|
|
26
|
+
import { addCounts } from './own/wasm-counters.js'
|
|
27
|
+
|
|
28
|
+
const SIGNALS_BY_REASON = { killed: 9, terminated: 15 }
|
|
29
|
+
/** Counts under a name: the name may come from the frame (`done.reason`), so it never reaches an inherited property (check5 F4). */
|
|
30
|
+
const bump = (o, k) => (o[k] = (Object.hasOwn(o, k) ? o[k] : 0) + 1)
|
|
31
|
+
const counter = () => Object.create(null)
|
|
32
|
+
/** Default action ends the program: HUP, INT, QUIT, ABRT, KILL, USR2, ALRM, TERM. (USR1 starts node's inspector; CHLD, WINCH, URG, CONT are ignored.) */
|
|
33
|
+
export const SIGNAL_ENDS = new Set([1, 2, 3, 6, 9, 12, 14, 15])
|
|
34
|
+
export const KILL_GRACE_MS = 3000
|
|
35
|
+
const enc = new TextEncoder()
|
|
36
|
+
|
|
37
|
+
export const YIELD_OPEN_MS = 0.25 // the channel loop's yield while a run is open (X5 gate 2b stage 1: 10 ms makes every crossing wait for it)
|
|
38
|
+
|
|
39
|
+
function envObject(env) {
|
|
40
|
+
const o = {}
|
|
41
|
+
for (const kv of env || []) {
|
|
42
|
+
const i = kv.indexOf('=')
|
|
43
|
+
if (i > 0) o[kv.slice(0, i)] = kv.slice(i + 1)
|
|
44
|
+
}
|
|
45
|
+
return o
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT, edgeWasm = '/wasm/edgejs.wasm', yieldMs = YIELD_OPEN_MS, run, onLog = () => {}, parallelism = 2, watch = {}, killGraceMs = KILL_GRACE_MS, site = null, handIn = null, nodeVersion = '' }) {
|
|
49
|
+
const jobs = new Map()
|
|
50
|
+
// fix7 (item 8): where the time of a start goes, milliseconds summed over the runs and how many runs had each step (the frame's steps come from adapter.js stats().stages)
|
|
51
|
+
const stage = (k, v) => {
|
|
52
|
+
const e = ((stats.stages ||= {})[k] ||= { n: 0, ms: 0 })
|
|
53
|
+
e.n++
|
|
54
|
+
e.ms += v
|
|
55
|
+
}
|
|
56
|
+
const stats = { started: 0, ready: 0, fallbacks: 0, exits: 0, open: 0, planMs: 0, planMsMax: 0, frameLimitHits: 0, runtimeFailures: 0, outBytes: { stdout: 0, stderr: 0 }, outDropped: 0, fallbackWhy: counter(), lost: counter(), signals: counter() }
|
|
57
|
+
const answer = (m, transfer) => vm.edgeMessage(m, transfer)
|
|
58
|
+
|
|
59
|
+
function start(m) {
|
|
60
|
+
const { id, hello, mounts } = m
|
|
61
|
+
const down = site?.isDown()
|
|
62
|
+
if (down) {
|
|
63
|
+
// the frame's site did not load at an earlier start: no run waits for it again (the page tries it in the background)
|
|
64
|
+
const again = Math.round((site.retryMs || 300000) / 60000)
|
|
65
|
+
const why = down.kind === 'runtime' ? `the runtime did not load (${down.why}); the page tries it again in ${again} minutes` : `the frame's site is down (${down.why}); the page tries it again every ${again} minutes`
|
|
66
|
+
stats.fallbacks++
|
|
67
|
+
bump(stats.fallbackWhy, why)
|
|
68
|
+
return answer({ id, ev: 'reply', fallback: why })
|
|
69
|
+
}
|
|
70
|
+
const job = { id, ready: false, control: {}, ended: false, outBytes: { stdout: 0, stderr: 0 }, t0: performance.now() }
|
|
71
|
+
jobs.set(id, job)
|
|
72
|
+
stats.started++
|
|
73
|
+
stats.planMs += m.planMs || 0 // the service's look at the tree before the page was asked (addons, listing sizes)
|
|
74
|
+
stats.planMsMax = Math.max(stats.planMsMax, m.planMs || 0)
|
|
75
|
+
stats.open++
|
|
76
|
+
const byId = Object.fromEntries(mounts.map((x, i) => [i + 1, { at: x.at, path: x.path, ro: !!x.ro }]))
|
|
77
|
+
const cfg = {
|
|
78
|
+
rt,
|
|
79
|
+
...runtimeConfig(rt, handIn), // the runtime's own files (rt=own) or the base the caller handed the SDK in under (rt=sdk)
|
|
80
|
+
edgeWasm,
|
|
81
|
+
args: (hello.argv || []).slice(1),
|
|
82
|
+
env: envObject(hello.env),
|
|
83
|
+
cwd: hello.cwd || '/',
|
|
84
|
+
stream: true,
|
|
85
|
+
stdin: 'pipe',
|
|
86
|
+
parallelism,
|
|
87
|
+
linux: { ...settings, uid: hello.uid, gid: hello.gid, utc: true, ...(nodeVersion ? { nodeVersion } : {}) }, // utc: a container with another TZ never gets here (edge-host.js helloRefusal)
|
|
88
|
+
}
|
|
89
|
+
const fallback = why => {
|
|
90
|
+
if (job.ready || job.ended) return
|
|
91
|
+
job.ended = true
|
|
92
|
+
stats.fallbacks++
|
|
93
|
+
bump(stats.fallbackWhy, why)
|
|
94
|
+
answer({ id, ev: 'reply', fallback: why })
|
|
95
|
+
}
|
|
96
|
+
run({
|
|
97
|
+
vm,
|
|
98
|
+
job: id, // the service's number of this node run: the file route's port finds the stub's channel for children by it
|
|
99
|
+
p9port,
|
|
100
|
+
origin,
|
|
101
|
+
mounts: byId,
|
|
102
|
+
cfg,
|
|
103
|
+
yieldMs,
|
|
104
|
+
releaseYield: false,
|
|
105
|
+
control: job.control,
|
|
106
|
+
...watch,
|
|
107
|
+
onLog: r => {
|
|
108
|
+
onLog(id, r)
|
|
109
|
+
if (r.type === 'step' && r.name === 'ready' && !job.ready && !job.ended) {
|
|
110
|
+
job.ready = true
|
|
111
|
+
stage('pageReady', performance.now() - job.t0) // fix7 (item 8): from the page's start of the run to the program running in the frame
|
|
112
|
+
site?.markUp() // a frame that runs a program is a site that is up
|
|
113
|
+
stats.ready++
|
|
114
|
+
answer({ id, ev: 'reply', ok: true })
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
onOut: (kind, bytes) => {
|
|
118
|
+
job.outBytes[kind] = (job.outBytes[kind] || 0) + bytes.length
|
|
119
|
+
stats.outBytes[kind] = (stats.outBytes[kind] || 0) + bytes.length
|
|
120
|
+
return answer({ id, ev: 'out', kind, bytes }, bytes.buffer ? [bytes.buffer] : [])
|
|
121
|
+
},
|
|
122
|
+
}).then(
|
|
123
|
+
r => {
|
|
124
|
+
job.ended = true
|
|
125
|
+
if (!job.ready) {
|
|
126
|
+
stats.fallbacks++
|
|
127
|
+
let why = r.fallback ? r.reason || 'fallback' : 'start failed: ' + String(r.error || 'the frame ended without a process').split('\n')[0]
|
|
128
|
+
if (!r.fallback && r.errorKind === 'runtime') {
|
|
129
|
+
// fix7 F12: the runtime's files did not load; the next nodes go to the guest at once instead of fetching them again
|
|
130
|
+
why = 'the runtime did not load: ' + String(r.error || '').split('\n')[0]
|
|
131
|
+
stats.runtimeFailures++
|
|
132
|
+
site?.markDown(why, { kind: 'runtime' })
|
|
133
|
+
}
|
|
134
|
+
bump(stats.fallbackWhy, why)
|
|
135
|
+
return answer({ id, ev: 'reply', fallback: why })
|
|
136
|
+
}
|
|
137
|
+
stats.exits++
|
|
138
|
+
stage('pageTotal', performance.now() - job.t0)
|
|
139
|
+
// fix7 (F1): bytes the frame's worker says it posted and the page did not take: counted, and said on stderr (a lost error text is never silent)
|
|
140
|
+
if (r.stages) for (const [k, v] of Object.entries(r.stages)) if (typeof v === 'number') stage(k, v)
|
|
141
|
+
if (r.setupMs) stage('frameSetup', r.setupMs) // the frame worker's load + start (adapter.js), as it measures itself
|
|
142
|
+
if (r.files) {
|
|
143
|
+
// fix7 (F11): how the runtime's files stood against HASHES.txt, summed over the runs
|
|
144
|
+
const t = (stats.files ||= { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 })
|
|
145
|
+
for (const k of Object.keys(t)) t[k] += Number(r.files[k]) || 0
|
|
146
|
+
}
|
|
147
|
+
if (r.wasm) {
|
|
148
|
+
// fix7 item 15: the WebAssembly objects of each start (compiles, bytes fetched, memories made and still alive when the run ended), summed; the
|
|
149
|
+
// last 40 runs one by one with the time and the frames alive, to read against the browser's memory over time
|
|
150
|
+
const { kinds, ...rest } = r.wasm
|
|
151
|
+
stats.wasm = addCounts(stats.wasm, rest)
|
|
152
|
+
if (kinds && kinds.length) stats.memKinds = kinds // the memories of the last run: what each was asked for and its size at the end
|
|
153
|
+
const f = frameCounts
|
|
154
|
+
const row = { at: Date.now(), framesCreated: f.created, framesLive: f.created - f.removed, compile: r.wasm.compile?.calls | 0, compileBytes: r.wasm.compile?.bytes | 0, memLive: r.wasm.memory?.live | 0, memLiveBytes: r.wasm.memory?.liveBytes | 0, fetchedBytes: Object.values(r.wasm.fetched || {}).reduce((a, x) => a + (x.bytes | 0), 0) }
|
|
155
|
+
;(stats.perRun ||= []).push(row)
|
|
156
|
+
if (stats.perRun.length > 40) stats.perRun.shift()
|
|
157
|
+
}
|
|
158
|
+
if (r.capi) {
|
|
159
|
+
// fix7 (F18): the threads' messages, summed over the runs (the largest values are kept as the largest)
|
|
160
|
+
const t = (stats.capi ||= { messages: 0, bytes: 0, copies: 0, copyBytes: 0, maxMessage: 0, maxRecipients: 0, heldBytes: 0, heldPeak: 0 })
|
|
161
|
+
for (const k of Object.keys(t)) t[k] = ['maxMessage', 'maxRecipients', 'heldPeak'].includes(k) ? Math.max(t[k], Number(r.capi[k]) || 0) : t[k] + (Number(r.capi[k]) || 0)
|
|
162
|
+
}
|
|
163
|
+
if (r.pipes) {
|
|
164
|
+
// what the runtime handed the adapter's pipes, summed over the runs, and the bytes that came after a pipe ended (lost)
|
|
165
|
+
const t = (stats.pipes ||= { out: 0, err: 0, lateOut: 0, lateErr: 0, unreadOut: 0, unreadErr: 0 })
|
|
166
|
+
for (const k of Object.keys(t)) t[k] += Number(r.pipes[k]) || 0
|
|
167
|
+
}
|
|
168
|
+
if (r.outBytes) for (const k of ['stdout', 'stderr']) if (Number(r.outBytes[k]) > job.outBytes[k]) stats.outDropped += Number(r.outBytes[k]) - job.outBytes[k]
|
|
169
|
+
if (job.killedBy && r.reason !== 'exited') return answer({ id, ev: 'exit', code: 128 + job.killedBy, signal: job.killedBy })
|
|
170
|
+
const sig = Object.hasOwn(SIGNALS_BY_REASON, r.reason) ? SIGNALS_BY_REASON[r.reason] : undefined
|
|
171
|
+
if (r.error) {
|
|
172
|
+
const msg = enc.encode(`wmd: node's frame ended with an error: ${String(r.error).split('\n')[0]}\n`)
|
|
173
|
+
answer({ id, ev: 'out', kind: 'stderr', bytes: msg }, [msg.buffer])
|
|
174
|
+
}
|
|
175
|
+
answer({ id, ev: 'exit', code: r.error ? 125 : (r.exitCode ?? (sig ? 128 + sig : 1)), signal: sig, ...(r.spawnRefused !== undefined ? { spawnRefused: r.spawnRefused } : {}) })
|
|
176
|
+
},
|
|
177
|
+
e => {
|
|
178
|
+
const why = String((e && e.message) || e).split('\n')[0]
|
|
179
|
+
if (e && e.why) bump(stats.lost, e.why)
|
|
180
|
+
if (e && e.why === 'start') {
|
|
181
|
+
stats.frameLimitHits++ // fix7 F10: the frame's page did not load within the page's limit (a few seconds)
|
|
182
|
+
site?.markDown(why, { probeNow: true }) // the frame never loaded: remember it, and look again at once in the background (a slow frame is found again)
|
|
183
|
+
}
|
|
184
|
+
if (e && e.why === 'runtime') {
|
|
185
|
+
stats.runtimeFailures++
|
|
186
|
+
site?.markDown(why, { kind: 'runtime' })
|
|
187
|
+
}
|
|
188
|
+
if (!job.ready) return fallback('start failed: ' + why)
|
|
189
|
+
job.ended = true
|
|
190
|
+
stats.exits++
|
|
191
|
+
// a run that ended by a signal of the guest's, or by the guest's own end ('stopped'), is the program's end; any other loss of the
|
|
192
|
+
// frame (taken out of the page, silent, timed out) is the runtime's: say so on stderr, with a code that is nobody's exit code
|
|
193
|
+
if (job.killedBy) return answer({ id, ev: 'exit', code: 128 + job.killedBy, signal: job.killedBy })
|
|
194
|
+
if (e && e.why === 'stopped') return answer({ id, ev: 'exit', code: 1 })
|
|
195
|
+
const msg = enc.encode(`wmd: node's frame ended: ${why}\n`)
|
|
196
|
+
answer({ id, ev: 'out', kind: 'stderr', bytes: msg }, [msg.buffer])
|
|
197
|
+
answer({ id, ev: 'exit', code: 125 })
|
|
198
|
+
},
|
|
199
|
+
).finally(() => {
|
|
200
|
+
clearTimeout(job.force)
|
|
201
|
+
jobs.delete(id)
|
|
202
|
+
if (--stats.open === 0) vm.edgeYield(0) // the last run's ports are closed: the default yield again
|
|
203
|
+
// fix10 (names): the stub drops the guest's kept names and attributes when it gets the exit (edgestub invalidate()). A stub that went away
|
|
204
|
+
// (killed, or it lost the host) never gets it, and the frame may have changed the tree: the page asks the guest for the drop, now that the
|
|
205
|
+
// frame's run has ended (p9DropNames through the machine's control session, boot.js edgeDropNames)
|
|
206
|
+
if (job.stubGone && job.ready && typeof vm.edgeDropNames === 'function') {
|
|
207
|
+
stats.namesDrops = (stats.namesDrops || 0) + 1
|
|
208
|
+
Promise.resolve()
|
|
209
|
+
.then(() => vm.edgeDropNames())
|
|
210
|
+
.catch(() => (stats.namesDropFails = (stats.namesDropFails || 0) + 1))
|
|
211
|
+
}
|
|
212
|
+
})
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// a signal from the guest: see the head of this file
|
|
216
|
+
function signal(job, n) {
|
|
217
|
+
bump(stats.signals, n)
|
|
218
|
+
if (job.ended) return
|
|
219
|
+
if (deliversSignals(rt) && n !== 9) {
|
|
220
|
+
// the runtime gives the program the signal itself: a handler it set runs, else the program ends as node does (exit 128+n). One that has not
|
|
221
|
+
// ended by itself after the grace period is cut off (a program stuck in a loop never looks at its signals), as a signal that ends is by default.
|
|
222
|
+
job.control.signal?.(n)
|
|
223
|
+
if (!SIGNAL_ENDS.has(n)) return
|
|
224
|
+
clearTimeout(job.force)
|
|
225
|
+
const gone = job.control.alive && !job.control.alive()
|
|
226
|
+
job.force = setTimeout(() => ((job.killedBy ||= n), job.control.abort?.()), gone ? 0 : killGraceMs)
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
if (!SIGNAL_ENDS.has(n)) return
|
|
230
|
+
job.killedBy ||= n
|
|
231
|
+
job.control.signal?.(n === 9 ? 9 : 15)
|
|
232
|
+
// the program gets a grace period; a frame that is gone or does not end it is cut off, so the guest's command always ends
|
|
233
|
+
clearTimeout(job.force)
|
|
234
|
+
const dead = job.control.alive && !job.control.alive()
|
|
235
|
+
job.force = setTimeout(() => job.control.abort?.(), n === 9 || dead ? 0 : killGraceMs)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
stats: () => ({ ...stats, frames: { created: frameCounts.created, removed: frameCounts.removed, live: frameCounts.created - frameCounts.removed }, fallbackWhy: { ...stats.fallbackWhy }, lost: { ...stats.lost }, signals: { ...stats.signals }, ...(site ? { site: site.stats() } : {}) }),
|
|
240
|
+
/** True while a run is open (the page refuses vm.checkpoint() then). */
|
|
241
|
+
busy: () => stats.open > 0,
|
|
242
|
+
/** The machine this bridge belongs to has ended: every open run is ended through its control (its output has nowhere to go). */
|
|
243
|
+
close() {
|
|
244
|
+
for (const job of [...jobs.values()]) {
|
|
245
|
+
clearTimeout(job.force)
|
|
246
|
+
job.control.abort?.()
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
onMessage(m) {
|
|
250
|
+
if (m.ev === 'start') return start(m)
|
|
251
|
+
const job = jobs.get(m.id)
|
|
252
|
+
if (!job) return
|
|
253
|
+
if (m.ev === 'stdin') job.control.stdin?.(m.bytes)
|
|
254
|
+
else if (m.ev === 'stdin-end') job.control.stdinEnd?.()
|
|
255
|
+
else if (m.ev === 'signal') signal(job, m.n)
|
|
256
|
+
else if (m.ev === 'signal-taken') {
|
|
257
|
+
// fix7 (F2, F14): the program's shim took the signal and ran a handler: the program is not stuck and goes on as node's does, so the cut-off after
|
|
258
|
+
// the grace period is dropped. (A signal nobody takes is a program that never looks at its signals; one taken with no handler ends itself.)
|
|
259
|
+
if (m.handled) {
|
|
260
|
+
clearTimeout(job.force)
|
|
261
|
+
job.force = null
|
|
262
|
+
stats.signalsHandled = (stats.signalsHandled || 0) + 1
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
else if (m.ev === 'gone') {
|
|
266
|
+
job.stubGone = true // the stub ended: nobody reads the output, and the stub makes no drop (see the run's end)
|
|
267
|
+
job.control.abort?.()
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* One bridge per machine. vm.restore() builds the next machine from the first boot's options, so the page cannot keep "the bridge" in a closure of
|
|
275
|
+
* them: the machine's handle comes with every message, and a message from a machine that is not the current one makes a new bridge with that
|
|
276
|
+
* handle and closes the old one. The messages of a machine that was replaced are dropped (it has ended).
|
|
277
|
+
* const per = bridgesPerMachine(machine => edgeBridge({vm: machine, ...})); per.onMessage(m, machine); per.busy(); per.current()
|
|
278
|
+
*/
|
|
279
|
+
export function bridgesPerMachine(make) {
|
|
280
|
+
let current = null
|
|
281
|
+
let machine = null
|
|
282
|
+
const retired = new WeakSet()
|
|
283
|
+
return {
|
|
284
|
+
current: () => current,
|
|
285
|
+
busy: () => !!current?.busy(),
|
|
286
|
+
onMessage(m, from) {
|
|
287
|
+
if (from !== machine) {
|
|
288
|
+
if (retired.has(from)) return
|
|
289
|
+
if (machine) retired.add(machine)
|
|
290
|
+
current?.close?.()
|
|
291
|
+
machine = from
|
|
292
|
+
current = make(from)
|
|
293
|
+
}
|
|
294
|
+
current.onMessage(m)
|
|
295
|
+
},
|
|
296
|
+
}
|
|
297
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Linux errno numbers (src/fs/errno.js) as the code names node and the SDK's file protocol carry.
|
|
2
|
+
import {
|
|
3
|
+
EACCES, EBADF, EEXIST, EFBIG, EINVAL, EIO, EISDIR, ELOOP, ENAMETOOLONG, ENOENT, ENOSPC, ENOSYS, ENOTDIR, ENOTEMPTY, EPERM, EROFS,
|
|
4
|
+
} from '../fs/errno.js'
|
|
5
|
+
|
|
6
|
+
export const CODES = {
|
|
7
|
+
[EPERM]: 'EPERM', [ENOENT]: 'ENOENT', [EIO]: 'EIO', [EBADF]: 'EBADF', [EACCES]: 'EACCES', [EEXIST]: 'EEXIST', [ENOTDIR]: 'ENOTDIR',
|
|
8
|
+
[EISDIR]: 'EISDIR', [EINVAL]: 'EINVAL', [EFBIG]: 'EFBIG', [ENOSPC]: 'ENOSPC', [EROFS]: 'EROFS', [ENAMETOOLONG]: 'ENAMETOOLONG',
|
|
9
|
+
[ENOSYS]: 'ENOSYS', [ENOTEMPTY]: 'ENOTEMPTY', [ELOOP]: 'ELOOP',
|
|
10
|
+
}
|
package/src/edge/ctl.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// X5 part B (switch edge=1): what the published SDK's host mount cannot carry (mode, owner, link count, links), answered
|
|
2
|
+
// from the machine's Overlay through linux.cjs's control requests, the same JSON requests wmd-edge answers on the desktop
|
|
3
|
+
// (edge/src/ctl.rs). The SDK's file protocol (fs-route.js) has no field for any of these, so they ride on its transport:
|
|
4
|
+
// the frame's Workers define `__wmdCtl(pid, json)` (src/edge/ctl-preload.cjs takes it from the Worker's real global
|
|
5
|
+
// into node's), which is one synchronous call on the SDK's own bridge with the method name `ctl` and mount id 0;
|
|
6
|
+
// fs-route.js hands method `ctl` to handle() here.
|
|
7
|
+
//
|
|
8
|
+
// Requests ({op, path, ...}; paths are the container's, absolute): chmod, lchmod, chown, lchown (checked and ignored, as on
|
|
9
|
+
// the desktop: the program runs as the container's root and changes no owner), stat, lstat (mode with the type bits, uid, gid,
|
|
10
|
+
// size, rdev, nlink, blksize, blocks, ino, times), utimes, lutimes, statvfs, meminfo, and the three the SDK's memory has
|
|
11
|
+
// no way to keep for the guest: symlink {path (the link), target}, link {path (the new name), from}, readlink {path}.
|
|
12
|
+
// The ops the desktop uses for child processes (alloc_exec_id, pending_signal, exitsig, watch_*) answer with nothing to do.
|
|
13
|
+
// A reply is the op's JSON, or {err: 'ENOENT'} (a code name, which linux.cjs's ctlError reads).
|
|
14
|
+
|
|
15
|
+
import { CODES } from './codes.js'
|
|
16
|
+
import { resolveIn } from './resolve.js'
|
|
17
|
+
import { S_IFLNK, S_IFMT, byteStr } from '../fs/pack.js'
|
|
18
|
+
import { MAX_SYMLINKS } from '../fs/overlay.js'
|
|
19
|
+
import { EROFS, ENOENT, ELOOP, EINVAL, fail } from '../fs/errno.js'
|
|
20
|
+
|
|
21
|
+
const NS = 1_000_000_000n
|
|
22
|
+
const ms = ns => Number(ns / 1_000_000n) + Number(ns % 1_000_000n) / 1e6
|
|
23
|
+
|
|
24
|
+
export class EdgeCtl {
|
|
25
|
+
/**
|
|
26
|
+
* @param {import('../fs/overlay.js').Overlay} fs
|
|
27
|
+
* @param {{root?: string, mounts: Object<string, {path: string, ro?: boolean}>}} o `mounts` as the file route has them: the
|
|
28
|
+
* container paths the SDK's mounts show. A path outside every mount is not the frame's to change (ENOENT).
|
|
29
|
+
*/
|
|
30
|
+
constructor(fs, { root = '', mounts }) {
|
|
31
|
+
this.fs = fs
|
|
32
|
+
this.rootPath = root
|
|
33
|
+
this.areas = Object.values(mounts).map(m => ({ prefix: '/' + m.path.replace(/^\/+|\/+$/g, ''), ro: !!m.ro }))
|
|
34
|
+
this.execId = 0
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
#root() {
|
|
38
|
+
return this.rootPath ? this.fs.resolve(this.rootPath) : this.fs.root
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The mount a container path is under: its read-only flag, or null for a path no mount shows. */
|
|
42
|
+
#area(p) {
|
|
43
|
+
let best = null
|
|
44
|
+
for (const a of this.areas) {
|
|
45
|
+
const under = a.prefix === '/' || p === a.prefix || p.startsWith(a.prefix + '/')
|
|
46
|
+
if (under && (!best || a.prefix.length > best.prefix.length)) best = a
|
|
47
|
+
}
|
|
48
|
+
return best
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
#node(p, follow, write) {
|
|
52
|
+
if (!p.startsWith('/')) fail(ENOENT)
|
|
53
|
+
const a = this.#area(p)
|
|
54
|
+
if (!a) fail(ENOENT)
|
|
55
|
+
if (write && a.ro) fail(EROFS)
|
|
56
|
+
const root = this.#root()
|
|
57
|
+
return resolveIn(this.fs, root, root, byteStr(p), follow)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
#realpath(p) {
|
|
61
|
+
const root = this.#root()
|
|
62
|
+
const utf8 = b => new TextDecoder().decode(Uint8Array.from(b, c => c.charCodeAt(0)))
|
|
63
|
+
let parts = byteStr(p).split('/').filter(s => s !== '')
|
|
64
|
+
const out = []
|
|
65
|
+
let cur = root
|
|
66
|
+
let links = 0
|
|
67
|
+
for (let i = 0; i < parts.length; ) {
|
|
68
|
+
const name = parts[i]
|
|
69
|
+
if (name === '.') {
|
|
70
|
+
i++
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
if (name === '..') {
|
|
74
|
+
cur = cur === root ? root : cur.parent || root
|
|
75
|
+
out.pop()
|
|
76
|
+
i++
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
const c = this.fs.lookup(cur, name)
|
|
80
|
+
if (c.type === S_IFLNK) {
|
|
81
|
+
if (++links > MAX_SYMLINKS) fail(ELOOP)
|
|
82
|
+
if (c.target.startsWith('/')) {
|
|
83
|
+
cur = root
|
|
84
|
+
out.length = 0
|
|
85
|
+
}
|
|
86
|
+
parts = c.target.split('/').filter(s => s !== '').concat(parts.slice(i + 1))
|
|
87
|
+
i = 0
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
90
|
+
out.push(name)
|
|
91
|
+
cur = c
|
|
92
|
+
i++
|
|
93
|
+
}
|
|
94
|
+
return '/' + out.map(utf8).join('/')
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** One request (a JSON string or object). Returns the reply object. */
|
|
98
|
+
handle(req) {
|
|
99
|
+
try {
|
|
100
|
+
const r = typeof req === 'string' ? JSON.parse(req) : req
|
|
101
|
+
return this.#op(r)
|
|
102
|
+
} catch (e) {
|
|
103
|
+
return { err: e && e.errno !== undefined ? CODES[e.errno] || 'EIO' : String((e && e.message) || e) }
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
#op(r) {
|
|
108
|
+
const fs = this.fs
|
|
109
|
+
const p = String(r.path ?? '')
|
|
110
|
+
switch (r.op) {
|
|
111
|
+
case 'chmod':
|
|
112
|
+
case 'lchmod': {
|
|
113
|
+
const n = this.#node(p, r.op === 'chmod', true)
|
|
114
|
+
const old = fs.getattr(n)
|
|
115
|
+
fs.setattr(n, { mode: r.mode & 0o7777 })
|
|
116
|
+
return { ok: true, old_mode: old.mode, old_ctimeMs: ms(old.ctime) }
|
|
117
|
+
}
|
|
118
|
+
case 'chown':
|
|
119
|
+
case 'lchown':
|
|
120
|
+
this.#node(p, r.op === 'chown', true)
|
|
121
|
+
return { ok: true }
|
|
122
|
+
case 'stat':
|
|
123
|
+
case 'lstat':
|
|
124
|
+
case 'fstat': {
|
|
125
|
+
const a = fs.getattr(this.#node(p, r.op !== 'lstat', false))
|
|
126
|
+
const split = t => [Number(t / NS), Number(t % NS)]
|
|
127
|
+
const [as, an] = split(a.atime)
|
|
128
|
+
const [ms_, mn] = split(a.mtime)
|
|
129
|
+
const [cs, cn] = split(a.ctime)
|
|
130
|
+
return {
|
|
131
|
+
mode: a.mode, uid: a.uid, gid: a.gid, size: a.size, rdev: a.rdev, nlink: a.nlink, blksize: a.blksize, blocks: a.blocks,
|
|
132
|
+
ino: Number(a.ino & 0xffffffffffffn), dev: 1, atimeMs: ms(a.atime), mtimeMs: ms(a.mtime), ctimeMs: ms(a.ctime),
|
|
133
|
+
atime_ns: an, mtime_ns: mn, ctime_ns: cn, atime_s: as, mtime_s: ms_, ctime_s: cs,
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
case 'utimes':
|
|
137
|
+
case 'lutimes': {
|
|
138
|
+
const n = this.#node(p, r.op === 'utimes', true)
|
|
139
|
+
const s = {}
|
|
140
|
+
if (!r.atime_omit) s.atime = BigInt(r.atime_s) * NS + BigInt(r.atime_ns || 0)
|
|
141
|
+
if (!r.mtime_omit) s.mtime = BigInt(r.mtime_s) * NS + BigInt(r.mtime_ns || 0)
|
|
142
|
+
fs.setattr(n, s)
|
|
143
|
+
return { ok: true }
|
|
144
|
+
}
|
|
145
|
+
case 'statvfs': {
|
|
146
|
+
this.#node(p, true, false)
|
|
147
|
+
const s = fs.statfs()
|
|
148
|
+
return { type: 0x794c7630, bsize: s.bsize, frsize: s.bsize, blocks: s.blocks, bfree: s.bfree, bavail: s.bavail, files: s.files, ffree: s.ffree, favail: s.ffree, flag: 4096 | (this.#area(p).ro ? 1 : 0), namemax: 255 }
|
|
149
|
+
}
|
|
150
|
+
case 'meminfo':
|
|
151
|
+
return { rss: 0 }
|
|
152
|
+
case 'symlink': {
|
|
153
|
+
const parts = this.#split(p, true)
|
|
154
|
+
fs.symlink(parts[0], parts[1], byteStr(String(r.target)), 0, 0)
|
|
155
|
+
return { ok: true }
|
|
156
|
+
}
|
|
157
|
+
case 'link': {
|
|
158
|
+
const from = this.#node(String(r.from), false, true)
|
|
159
|
+
const parts = this.#split(p, true)
|
|
160
|
+
fs.link(parts[0], parts[1], from)
|
|
161
|
+
return { ok: true }
|
|
162
|
+
}
|
|
163
|
+
case 'realpath': {
|
|
164
|
+
// the path with every link followed (the SDK's mount shows a link as the file it leads to and has no readlink, so
|
|
165
|
+
// node's own realpath does not follow it: `/usr/local/bin/npm` would stay where it is and its `../lib` be wrong)
|
|
166
|
+
if (!this.#area(p)) fail(ENOENT)
|
|
167
|
+
return { path: this.#realpath(p) }
|
|
168
|
+
}
|
|
169
|
+
case 'readlink': {
|
|
170
|
+
const n = this.#node(p, false, false)
|
|
171
|
+
if ((n.mode & S_IFMT) !== S_IFLNK) fail(EINVAL)
|
|
172
|
+
const t = fs.readlink(n)
|
|
173
|
+
return { target: new TextDecoder().decode(Uint8Array.from(t, c => c.charCodeAt(0))) }
|
|
174
|
+
}
|
|
175
|
+
case 'alloc_exec_id':
|
|
176
|
+
return { id: ++this.execId }
|
|
177
|
+
case 'pending_signal':
|
|
178
|
+
case 'exitsig':
|
|
179
|
+
case 'set_exitsig':
|
|
180
|
+
case 'watch_poll_all':
|
|
181
|
+
case 'watch_stop':
|
|
182
|
+
return {}
|
|
183
|
+
default:
|
|
184
|
+
return { err: 'ENOSYS' }
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// [the directory a new name goes in, the name] for container path p
|
|
189
|
+
#split(p, write) {
|
|
190
|
+
const parts = p.split('/').filter(s => s !== '')
|
|
191
|
+
if (!parts.length) fail(EINVAL)
|
|
192
|
+
const dirPath = '/' + parts.slice(0, -1).join('/')
|
|
193
|
+
const a = this.#area(p)
|
|
194
|
+
if (!a) fail(ENOENT)
|
|
195
|
+
if (write && a.ro) fail(EROFS)
|
|
196
|
+
const root = this.#root()
|
|
197
|
+
return [resolveIn(this.fs, root, root, byteStr(dirPath), true), byteStr(parts.at(-1))]
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// X5 fix 11 (F-M): which errors of a start say that the runtime's own files did not load. The page remembers such a start (bridge.js: counted as a
|
|
2
|
+
// runtime failure, the next nodes go to the guest until the retry time) and says what failed. An error while load() runs is one; so is an error that
|
|
3
|
+
// carries `runtimeFiles` (src/edge/own/hub.js: the runtime's wasm was not there or did not compile; it comes in start(), after load()).
|
|
4
|
+
export const errorKindOf = (e, loading) => (loading || (e && e.runtimeFiles === true) ? 'runtime' : undefined)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// X5 part B (switch edge=1): the isolated frame, on an origin of its own (one host name per container, a site of its
|
|
2
|
+
// own; docs/plans/x5-browser-node.md section 6). Takes one run config and two MessagePorts to the channel service from
|
|
3
|
+
// the page, starts worker.js (node on the chosen runtime) and passes its messages up. The page takes only log, step, out and
|
|
4
|
+
// done messages from it. It answers the page's pings (a frame that stops answering ends the run: src/edge/page.js).
|
|
5
|
+
const parentOrigin = new URL(document.referrer || 'http://invalid').origin
|
|
6
|
+
let w = null
|
|
7
|
+
let started = false
|
|
8
|
+
// every Worker this frame has started and not yet ended (the registry the tests read; empty once the run is over)
|
|
9
|
+
const live = new Set()
|
|
10
|
+
globalThis.x5live = live
|
|
11
|
+
// X5 fix9 (docs/research/browser-speed-2026-11/x5/gate2b/fix9/fix9.md, the keeper): the Worker ends nothing itself (worker.js done()); the frame
|
|
12
|
+
// terminates it from outside as soon as it says done or fails, and the browser ends the runtime's Workers under it with it. (Until fix9 the Worker
|
|
13
|
+
// terminated them and closed itself in one task, and Chromium kept their threads and memory.) Every path that ends a run empties this registry:
|
|
14
|
+
// done, a Worker error, stop (the page ends the run), pagehide (the frame goes away).
|
|
15
|
+
const endWorker = w => {
|
|
16
|
+
if (!w || !live.delete(w)) return
|
|
17
|
+
try {
|
|
18
|
+
w.terminate()
|
|
19
|
+
} catch {
|
|
20
|
+
// already gone
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const endAll = () => {
|
|
24
|
+
for (const w of [...live]) endWorker(w)
|
|
25
|
+
}
|
|
26
|
+
// the page took the frame away (a lost run) or is going away: the worker ends with it
|
|
27
|
+
addEventListener('pagehide', endAll)
|
|
28
|
+
addEventListener('message', ({ data, origin }) => {
|
|
29
|
+
if (origin !== parentOrigin || !data) return
|
|
30
|
+
if (data.x5edge === 'ping') return parent.postMessage('x5-pong', parentOrigin)
|
|
31
|
+
if (data.x5edge === 'stop') return endAll()
|
|
32
|
+
// later input to the running program: {x5edge: 'in', in: {stdin: Uint8Array} | {stdinEnd: true} | {signal: n}}
|
|
33
|
+
if (data.x5edge === 'in' && w) return w.postMessage({ in: data.in })
|
|
34
|
+
if (started || data.x5edge !== 'start') return
|
|
35
|
+
started = true
|
|
36
|
+
const mine = (w = new Worker('/edge/worker.js', { type: 'module' }))
|
|
37
|
+
live.add(mine)
|
|
38
|
+
mine.onmessage = ({ data: d }) => {
|
|
39
|
+
parent.postMessage({ x5relay: d }, parentOrigin)
|
|
40
|
+
if (d && d.type === 'done') endWorker(mine) // the run is over: done is the Worker's last message
|
|
41
|
+
}
|
|
42
|
+
mine.onerror = e => {
|
|
43
|
+
parent.postMessage({ x5relay: { type: 'done', error: 'worker error: ' + e.message } }, parentOrigin)
|
|
44
|
+
endWorker(mine)
|
|
45
|
+
}
|
|
46
|
+
mine.postMessage({ cfg: data.cfg, ports: data.ports }, data.ports)
|
|
47
|
+
})
|
|
48
|
+
parent.postMessage('x5-frame-ready', parentOrigin)
|