@threadedstack/wmd-web 0.1.38 → 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.
- package/README.md +239 -2
- package/RELEASE.json +97 -53
- 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 +321 -12
- package/src/edge/auto.js +77 -0
- package/src/edge/base.js +10 -0
- package/src/edge/bridge.js +76 -7
- package/src/edge/ctl.js +21 -4
- package/src/edge/error-kind.js +6 -0
- package/src/edge/frame-code.gen.js +6 -0
- package/src/edge/frame.js +58 -15
- package/src/edge/msg.js +3 -0
- package/src/edge/own/adapter.js +208 -19
- package/src/edge/own/exit-now.js +62 -0
- package/src/edge/own/fs-own-route.js +40 -3
- package/src/edge/own/fs-stats.js +11 -0
- package/src/edge/own/hub.js +125 -14
- package/src/edge/own/loader.js +3 -2
- package/src/edge/own/marks.js +158 -0
- package/src/edge/own/net-host.js +873 -0
- package/src/edge/own/node-globals.js +142 -0
- package/src/edge/own/pool.js +30 -1
- package/src/edge/own/service-receiver.js +7 -1
- package/src/edge/own/shim-post.js +38 -0
- package/src/edge/own/worker.js +34 -1
- package/src/edge/page.js +448 -25
- package/src/edge/pins.gen.js +17 -0
- package/src/edge/pins.js +21 -0
- package/src/edge/plan.js +45 -9
- package/src/edge/python-module.js +18 -0
- package/src/edge/python-pins.js +64 -0
- package/src/edge/python-plan.js +280 -0
- package/src/edge/python-source.js +34 -0
- package/src/edge/runtime.js +13 -2
- package/src/edge/sbx/cap.js +36 -0
- package/src/edge/sbx/common.js +186 -0
- package/src/edge/sbx/doc.js +121 -0
- package/src/edge/sbx/files.js +112 -0
- package/src/edge/sbx/frame.js +126 -0
- package/src/edge/sbx/gate.js +115 -0
- package/src/edge/sbx/sha256.js +68 -0
- package/src/edge/sbx/worker-entry.js +36 -0
- package/src/edge/sems.js +113 -0
- package/src/edge/service-host.js +57 -5
- package/src/edge/service-port.js +79 -5
- package/src/edge/setup.js +275 -0
- package/src/edge/shim.js +3 -1
- package/src/edge/watch.js +101 -0
- package/src/edge/worker.js +31 -2
- package/src/gowasm/boot-setup.js +175 -0
- package/src/gowasm/make-pins-module.mjs +35 -0
- package/src/gowasm/pins-data.js +162 -0
- package/src/gowasm/setup.js +167 -0
- package/src/gowasm/twin-fetch.js +27 -0
- package/src/host/chan-service.js +33 -6
- package/src/host/chan-services.js +29 -4
- package/src/host/ckpt.js +78 -0
- package/src/host/csp-reason.js +64 -0
- package/src/host/ctl.js +30 -8
- package/src/host/edge-go.js +94 -4
- package/src/host/edge-host.js +58 -3
- package/src/host/gowasm-guard.js +11 -1
- package/src/host/gowasm-worker.js +90 -35
- package/src/host/pinned-fetch.js +436 -0
- package/wmdpack.wasm +0 -0
package/src/edge/own/adapter.js
CHANGED
|
@@ -18,12 +18,59 @@
|
|
|
18
18
|
// The receiving side is service-receiver.js. What is left to join with the channel service of the fix round: its port handler must
|
|
19
19
|
// pass `own` messages to it (src/edge/service-port.js knows only the SDK's `method` messages).
|
|
20
20
|
import { addCounts } from './wasm-counters.js'
|
|
21
|
+
import { at, stagesOf } from './marks.js'
|
|
21
22
|
import { OwnRuntime } from './hub.js'
|
|
23
|
+
import { NODE_GLOBALS } from './node-globals.js'
|
|
22
24
|
import { shimSource } from '../shim.js'
|
|
23
25
|
import { SHIM_POST } from './shim-post.js'
|
|
24
26
|
|
|
25
27
|
export const name = 'own'
|
|
26
28
|
|
|
29
|
+
/**
|
|
30
|
+
* X5 fix2 F4: a fetch whose answer is not ok is no file: a 404 page's text must never reach the compiler or the shim check. The error names the URL and the
|
|
31
|
+
* status and carries `runtimeFiles`, so the frame reports it as the runtime's (errorKind 'runtime') and the page marks the site down for a while (bridge.js).
|
|
32
|
+
* (A test's fake may leave `ok` out; only an explicit false fails.)
|
|
33
|
+
* X5 fix3p P4: the same for a fetch() that rejects (the network is gone, the site died between two files), a body that fails while it is read, bytes
|
|
34
|
+
* that are not the file (the compiler's error, a settings file that fails its check, a hash that does not match): each error names the URL and what
|
|
35
|
+
* happened and carries `runtimeFiles`.
|
|
36
|
+
*/
|
|
37
|
+
const absUrl = (url) => {
|
|
38
|
+
try {
|
|
39
|
+
return new URL(url, globalThis.location && globalThis.location.href).href
|
|
40
|
+
} catch {
|
|
41
|
+
return url
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const whyOf = (e) => String((e && e.message) || e).split('\n')[0]
|
|
45
|
+
function runtimeFile(text) {
|
|
46
|
+
const e = new Error(text)
|
|
47
|
+
e.runtimeFiles = true
|
|
48
|
+
return e
|
|
49
|
+
}
|
|
50
|
+
async function fetchOk(url) {
|
|
51
|
+
let r
|
|
52
|
+
try {
|
|
53
|
+
r = await deps.fetch(url)
|
|
54
|
+
} catch (e) {
|
|
55
|
+
throw runtimeFile(`${absUrl(url)} could not be fetched: ${whyOf(e)}`)
|
|
56
|
+
}
|
|
57
|
+
if (r.ok === false) {
|
|
58
|
+
const e = new Error(`${r.url || url} answered ${r.status}${r.statusText ? ' ' + r.statusText : ''}`)
|
|
59
|
+
e.runtimeFiles = true
|
|
60
|
+
throw e
|
|
61
|
+
}
|
|
62
|
+
return r
|
|
63
|
+
}
|
|
64
|
+
// the bytes or the text of a file: its fetch and its body read both fail as runtime files
|
|
65
|
+
async function readFile(url, as) {
|
|
66
|
+
const r = await fetchOk(url)
|
|
67
|
+
try {
|
|
68
|
+
return as === 'text' ? await r.text() : new Uint8Array(await r.arrayBuffer())
|
|
69
|
+
} catch (e) {
|
|
70
|
+
throw runtimeFile(`${r.url || absUrl(url)} could not be read: ${whyOf(e)}`)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
27
74
|
const SHIM_PATH = '/.wmd-edge/linux.cjs'
|
|
28
75
|
let deps = { OwnRuntime, fetch: (...a) => fetch(...a), compile: (b) => WebAssembly.compile(b) }
|
|
29
76
|
let rt = null
|
|
@@ -113,6 +160,11 @@ function portRoute(p) {
|
|
|
113
160
|
return route
|
|
114
161
|
}
|
|
115
162
|
|
|
163
|
+
// X5 default1 round 2 (B2.1): this start's marks (own.marks, page option edgeMarks=1), on the clock all Workers share; null when off
|
|
164
|
+
const mark = (name) => {
|
|
165
|
+
if (state && state.marks && state.marks[name] === undefined) state.marks[name] = at()
|
|
166
|
+
}
|
|
167
|
+
|
|
116
168
|
const sha256 = async (u8) => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', u8)), (b) => b.toString(16).padStart(2, '0')).join('')
|
|
117
169
|
|
|
118
170
|
// fix7 (F11): the files that run are the ones the build wrote. edge/browser/build.sh puts HASHES.txt (sha256, size, name) next to them; the wasm and the glue are
|
|
@@ -143,33 +195,141 @@ async function checkFiles(own, files) {
|
|
|
143
195
|
files.unlisted++
|
|
144
196
|
continue
|
|
145
197
|
}
|
|
146
|
-
const bytes =
|
|
198
|
+
const bytes = await readFile(own[key], 'bytes')
|
|
147
199
|
files.checked++
|
|
148
200
|
if (bytes.length !== w.size || (await sha256(bytes)) !== w.hash) {
|
|
149
201
|
files.mismatch++
|
|
150
|
-
throw
|
|
202
|
+
throw runtimeFile(`the runtime's files do not match HASHES.txt: ${name} at ${absUrl(own[key])} (size ${bytes.length}, listed ${w.size}); not run`)
|
|
151
203
|
}
|
|
152
204
|
files.ok++
|
|
153
|
-
if (key === 'wasmUrl')
|
|
205
|
+
if (key === 'wasmUrl') {
|
|
206
|
+
mark('rtc0')
|
|
207
|
+
try {
|
|
208
|
+
out.module = await deps.compile(bytes)
|
|
209
|
+
} catch (e) {
|
|
210
|
+
throw runtimeFile(`${absUrl(own[key])} did not compile as WebAssembly: ${whyOf(e)}`)
|
|
211
|
+
}
|
|
212
|
+
mark('rtc1')
|
|
213
|
+
}
|
|
154
214
|
}
|
|
155
215
|
return out
|
|
156
216
|
}
|
|
157
217
|
|
|
158
|
-
|
|
218
|
+
// X5 default1 round 2 (B2.1): what a start leaves for the next start of the same frame (frame.js keeps it): the runtime's compiled module (its files
|
|
219
|
+
// were checked against HASHES.txt when it was made), the program made ready (hub.js OwnRuntime.prepare: capped bytes in shared memory, sha256,
|
|
220
|
+
// compiled module) and the shim's source text. Off with own.keepMods === false (page option edgeKeepMods=0). keep() gives it to worker.js.
|
|
221
|
+
export function keep() {
|
|
222
|
+
const k = state && state.keep
|
|
223
|
+
return k && (k.rtModule || k.prog) ? { ...k, texts: { ...k.texts } } : null
|
|
224
|
+
}
|
|
225
|
+
const keptFor = (own, kept) => (own.keepMods !== false && kept && kept.wasmUrl === own.wasmUrl && kept.glueUrl === own.glueUrl ? kept : null)
|
|
226
|
+
|
|
227
|
+
// the runtime's module: the kept one (checked against HASHES.txt by the start that compiled it: nothing is fetched, hashed or compiled), or
|
|
228
|
+
// checked and compiled now (checkFiles)
|
|
229
|
+
async function runtimeModule(own) {
|
|
230
|
+
const k = state.kept
|
|
231
|
+
if (k && k.rtModule) {
|
|
232
|
+
state.module = k.rtModule
|
|
233
|
+
state.files.kept = 1
|
|
234
|
+
state.keep.rtModule = k.rtModule
|
|
235
|
+
mark('checked')
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
const tc = performance.now()
|
|
239
|
+
const ok = await checkFiles(own, state.files)
|
|
240
|
+
state.stages.check = performance.now() - tc
|
|
241
|
+
mark('checked')
|
|
242
|
+
state.module = ok.module
|
|
243
|
+
if (state.keep && ok.module) state.keep.rtModule = ok.module
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// the program: the kept ready one, or fetched (and made ready when the frame keeps it: compiled here, where the runtime's main Worker compiled it
|
|
247
|
+
// in Rust before). -> {program} (bytes for the runtime to compile) or {ready}
|
|
248
|
+
async function programOf(module, memoryMaxMiB) {
|
|
249
|
+
const s = state
|
|
250
|
+
let ready = s.kept && s.kept.prog && s.kept.prog.url === module ? s.kept.prog : null
|
|
251
|
+
let program = null
|
|
252
|
+
if (ready) {
|
|
253
|
+
s.stages.keptProgram = 1
|
|
254
|
+
} else {
|
|
255
|
+
program = await readFile(module, 'bytes')
|
|
256
|
+
if (s.keep && deps.OwnRuntime.prepare) {
|
|
257
|
+
try {
|
|
258
|
+
ready = { ...(await deps.OwnRuntime.prepare(program, memoryMaxMiB ? { memoryMaxMiB } : undefined)), url: module }
|
|
259
|
+
} catch (e) {
|
|
260
|
+
throw runtimeFile(`${absUrl(module)} is not a node program the runtime can compile: ${whyOf(e)}`)
|
|
261
|
+
}
|
|
262
|
+
program = null
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (s.keep && ready) s.keep.prog = ready
|
|
266
|
+
return { program, ready }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// the shim's source (kept as fetched; the settings go in per start)
|
|
270
|
+
async function linuxText(src) {
|
|
271
|
+
const s = state
|
|
272
|
+
let raw = s.keep && s.keep.texts[src]
|
|
273
|
+
if (typeof raw !== 'string') {
|
|
274
|
+
raw = await readFile(src, 'text')
|
|
275
|
+
try {
|
|
276
|
+
shimSource(raw, {}, { symlinks: false }) // a text that is not the settings file (a proxy's page) fails its markers here, before any run uses it
|
|
277
|
+
} catch (e) {
|
|
278
|
+
throw runtimeFile(`${absUrl(src)} is not the settings file: ${whyOf(e)}`)
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (s.keep) s.keep.texts[src] = raw
|
|
282
|
+
return raw
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function newState(own, kept, more) {
|
|
286
|
+
const k = keptFor(own, kept)
|
|
287
|
+
state = { own, out: new Pipe(), err: new Pipe(), t0: performance.now(), signals: [], files: { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 }, module: undefined, stages: {}, marks: own.marks ? { ...(globalThis.__wmdFwMarks || {}) } : null, ...more }
|
|
288
|
+
state.kept = k
|
|
289
|
+
state.keep = own.keepMods !== false ? { wasmUrl: own.wasmUrl, glueUrl: own.glueUrl, rtModule: null, prog: null, texts: { ...(k ? k.texts : {}) } } : null
|
|
290
|
+
mark('load0')
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export async function load({ cfg, ports, log, onWorkerError, kept = null }) {
|
|
159
294
|
const own = cfg.own || {}
|
|
160
295
|
if (!own.wasmUrl || !own.glueUrl || !own.workerUrl) throw new Error('rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl')
|
|
161
296
|
if (own.fsTime) globalThis.__wmdFsTime = true // counters of the file calls (hub.js, fs-own-route.js): off unless the page option fsTime=1
|
|
162
297
|
port = ports[0]
|
|
163
298
|
route = portRoute(port)
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const ok = await checkFiles(own, state.files)
|
|
167
|
-
state.stages.check = performance.now() - tc
|
|
168
|
-
state.module = ok.module
|
|
299
|
+
newState(own, kept, { log, onWorkerError })
|
|
300
|
+
await runtimeModule(own)
|
|
169
301
|
return {}
|
|
170
302
|
}
|
|
171
303
|
|
|
172
|
-
|
|
304
|
+
/**
|
|
305
|
+
* X5 default1 round 2 (B2.2): what a start needs that is the same for every start, made before the first one (the page's idle time after boot, page.js
|
|
306
|
+
* prepareEdge): the runtime's module, the program made ready and the shim's source, for keep(). No file route, no runtime Worker. -> {kept: bool}
|
|
307
|
+
*/
|
|
308
|
+
export async function prepare({ cfg, kept = null }) {
|
|
309
|
+
const own = cfg.own || {}
|
|
310
|
+
if (!own.wasmUrl || !own.glueUrl || !own.workerUrl) throw new Error('rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl')
|
|
311
|
+
if (own.keepMods === false) return { kept: false }
|
|
312
|
+
newState(own, kept, {})
|
|
313
|
+
await runtimeModule(own)
|
|
314
|
+
await programOf(cfg.edgeWasm || '/wasm/edgejs.wasm', cfg.memoryMaxMiB)
|
|
315
|
+
if (cfg.linux) await linuxText(cfg.linuxSrc || '/wasm/linux.cjs')
|
|
316
|
+
return { kept: true, stages: { ...state.stages }, files: { ...state.files } }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// X25 gate 1: wmd's python shim (edge/src/linux.py) with the container's settings in place of its config line, as the desktop makes it
|
|
320
|
+
// (edge/src/main.rs python_shim_source). The shim text is kept as fetched.
|
|
321
|
+
async function pythonShimText(src, linux) {
|
|
322
|
+
const s = state
|
|
323
|
+
let raw = s.keep && s.keep.texts[src]
|
|
324
|
+
if (typeof raw !== 'string') raw = await readFile(src, 'text')
|
|
325
|
+
if (s.keep) s.keep.texts[src] = raw
|
|
326
|
+
const marker = '_cfg = {"execPath": "", "arch": "", "hostname": "", "cpus": 0, "uid": 0, "gid": 0} #__WMD_EDGE_CONFIG__#'
|
|
327
|
+
if (!raw.includes(marker)) throw runtimeFile(`${absUrl(src)} is not the python settings file`)
|
|
328
|
+
const cfg = { execPath: linux.execPath, arch: linux.arch || 'arm64', hostname: linux.hostname || 'wmd-web', cpus: linux.cpus || 1, uid: linux.uid | 0, gid: linux.gid | 0 }
|
|
329
|
+
return raw.replace(marker, () => `_cfg = (lambda true, false, null: ${JSON.stringify(cfg)})(True, False, None)`)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export async function start({ module, argv, env, cwd, files = {}, linux, linuxSrc, stdin = 'closed', python }) {
|
|
173
333
|
const s = state
|
|
174
334
|
let tm = performance.now()
|
|
175
335
|
const lap = (name) => {
|
|
@@ -177,17 +337,23 @@ export async function start({ module, argv, env, cwd, files = {}, linux, linuxSr
|
|
|
177
337
|
s.stages[name] = now - tm
|
|
178
338
|
tm = now
|
|
179
339
|
}
|
|
180
|
-
|
|
340
|
+
mark('start0')
|
|
341
|
+
const { program, ready } = await programOf(module, python && python.maxMiB)
|
|
181
342
|
lap('program')
|
|
343
|
+
mark('program')
|
|
182
344
|
let args = argv
|
|
183
345
|
const shim = { ...files }
|
|
184
|
-
if (
|
|
185
|
-
|
|
346
|
+
if (python) {
|
|
347
|
+
// X25 gate 1: CPython runs /.wmd-edge/startup.py before the program (the shim); its arguments are the program's own, no --require
|
|
348
|
+
shim['startup.py'] = await pythonShimText(linuxSrc || '/wasm/linux.py', linux || {})
|
|
349
|
+
} else if (linux) {
|
|
350
|
+
const text = shimSource(await linuxText(linuxSrc || '/wasm/linux.cjs'), linux, { symlinks: false }) + SHIM_POST
|
|
186
351
|
shim['linux.cjs'] = text
|
|
187
352
|
args = ['--require', SHIM_PATH, ...argv]
|
|
188
353
|
}
|
|
189
354
|
await route.handle('shim', [shim], new Uint8Array(0))
|
|
190
355
|
lap('shim')
|
|
356
|
+
mark('shim')
|
|
191
357
|
if (globalThis.__wmdFsTime) await route.handle('timing', ['on'], new Uint8Array(0))
|
|
192
358
|
rt = await deps.OwnRuntime.start({
|
|
193
359
|
wasmUrl: s.own.wasmUrl,
|
|
@@ -195,23 +361,30 @@ export async function start({ module, argv, env, cwd, files = {}, linux, linuxSr
|
|
|
195
361
|
glueUrl: s.own.glueUrl,
|
|
196
362
|
workerUrl: s.own.workerUrl,
|
|
197
363
|
fsRoute: route,
|
|
364
|
+
...(python && python.maxMiB ? { memoryMaxMiB: python.maxMiB } : {}), // X25 gate 2: the cap of the python's memory (default 1024)
|
|
365
|
+
marks: s.own.marks === 2 ? 2 : !!s.marks, // X25 gate 2c item 2: 2 = the call ring too (edgeMarks=2)
|
|
198
366
|
onOut: (fd, b) => {
|
|
199
|
-
if (s.stages.firstOut === undefined && b.length && s.runT0) s.stages.firstOut = performance.now() - s.runT0
|
|
367
|
+
if (s.stages.firstOut === undefined && b.length && s.runT0) (s.stages.firstOut = performance.now() - s.runT0), mark('firstOut')
|
|
200
368
|
;(fd === 2 ? s.err : s.out).push(b)
|
|
201
369
|
},
|
|
202
370
|
onLog: d => s.log?.(typeof d === 'string' ? d : JSON.stringify(d)),
|
|
203
371
|
stack: s.own.stack,
|
|
372
|
+
...(s.own.trace ? { trace: s.own.trace | 0 } : {}), // X5 net: the page option edgeTrace
|
|
373
|
+
nodeGlobals: NODE_GLOBALS, // X5 fix3 R6
|
|
204
374
|
})
|
|
205
375
|
lap('boot')
|
|
376
|
+
mark('booted')
|
|
206
377
|
s.runT0 = performance.now()
|
|
378
|
+
mark('runPost')
|
|
207
379
|
const envList = Object.entries({ HOME: '/root', ...(env || {}) }).map(([k, v]) => `${k}=${v}`)
|
|
208
380
|
runP = rt
|
|
209
|
-
.run({ program, args, env: envList, node:
|
|
381
|
+
.run({ program, ...(ready ? { ready } : {}), args, env: envList, node: !python, cwd, stdin: stdin === 'pipe' ? 'pipe' : 'null', tty: {}, children: s.own.children !== false, net: s.own.net !== false, exec: linux && linux.execPath, shim: !!linux && !python, ...(python ? { argv0: python.argv0 } : {}) })
|
|
210
382
|
.then(
|
|
211
|
-
|
|
383
|
+
// a program the default action of a signal ended: the runtime's code records the signal (wmd_signal.rs `signaled`, 0x4000 + n), the exit is 128 + n
|
|
384
|
+
r => ((r.code & ~0x7f) === 0x4000 ? { exitCode: 128 + (r.code & 0x7f), reason: 'exit', signal: r.code & 0x7f } : { exitCode: r.code, reason: 'exit' }),
|
|
212
385
|
e => ({ exitCode: 1, reason: 'error: ' + String((e && e.message) || e) }),
|
|
213
386
|
)
|
|
214
|
-
.then(r => ((s.stages.run = performance.now() - s.runT0), s.out.end(), s.err.end(), r))
|
|
387
|
+
.then(r => (mark('exitRecv'), (s.stages.run = performance.now() - s.runT0), s.out.end(), s.err.end(), r))
|
|
215
388
|
return {
|
|
216
389
|
readStdout: n => s.out.read(n),
|
|
217
390
|
readStderr: n => s.err.read(n),
|
|
@@ -258,7 +431,13 @@ export async function stats() {
|
|
|
258
431
|
let wasm = null
|
|
259
432
|
try {
|
|
260
433
|
const mine = globalThis.__wmdWasmCounters ? globalThis.__wmdWasmCounters.snapshot() : null
|
|
261
|
-
|
|
434
|
+
// X5 default1 item B: only when the page option edgeCounts=1 asks; the wait (up to 400 ms when a thread is blocked) delayed done and the guest's exit
|
|
435
|
+
let theirs = []
|
|
436
|
+
if (rt && state && state.own.counts) {
|
|
437
|
+
const tc = performance.now()
|
|
438
|
+
theirs = await rt.collectCounts(400)
|
|
439
|
+
state.stages.counts = performance.now() - tc
|
|
440
|
+
}
|
|
262
441
|
let sum = mine
|
|
263
442
|
for (const t of theirs) sum = addCounts(sum, t.c)
|
|
264
443
|
if (sum) wasm = { ...sum, workers: theirs.length }
|
|
@@ -266,6 +445,16 @@ export async function stats() {
|
|
|
266
445
|
} catch {
|
|
267
446
|
// no counters then
|
|
268
447
|
}
|
|
448
|
+
// X5 default1 round 2 (B2.1): the marks (milliseconds after load0) and the stages they give, as m.<stage> next to the other stages
|
|
449
|
+
let marks = null
|
|
450
|
+
if (state && state.marks) {
|
|
451
|
+
const rm = (rt && rt.marks) || { first: {}, n: {} }
|
|
452
|
+
const all = { ...rm.first, ...state.marks }
|
|
453
|
+
for (const [k, v] of Object.entries(stagesOf(all))) state.stages['m.' + k] = v
|
|
454
|
+
const base = state.marks.frame ?? state.marks.load0
|
|
455
|
+
marks = { t: Object.fromEntries(Object.entries(all).map(([k, v]) => [k, Math.round((v - base) * 10) / 10])), n: { ...rm.n }, ...(rm.fs ? { fs: rm.fs } : {}), ...(rm.series && Object.keys(rm.series).length ? { series: Object.fromEntries(Object.entries(rm.series).map(([k, v]) => [k, v.map((x) => Math.round((x - base) * 10) / 10)])) } : {}), ...(rm.memMiB ? { memMiB: rm.memMiB } : {}), ...(rm.calls ? { calls: rm.calls } : {}) }
|
|
456
|
+
}
|
|
269
457
|
// fix7 (F1): what the runtime handed the pipes: a lost error text shows as bytes after the end or as a smaller count than the worker saw
|
|
270
|
-
return {
|
|
458
|
+
return {
|
|
459
|
+
...(marks ? { marks } : {}), service: null, frameRtt: null, ...(wasm ? { wasm } : {}), ...(rt?.capiStats ? { capi: rt.capiStats } : {}), ...(rt && rt.forged ? { forged: rt.forged } : {}), ...(state ? { files: { ...state.files }, stages: { ...state.stages }, pipes: { out: state.out.bytes, err: state.err.bytes, lateOut: state.out.late, lateErr: state.err.late, unreadOut: state.out.bytes - state.out.taken, unreadErr: state.err.bytes - state.err.taken } } : {}) }
|
|
271
460
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// X5 net round 2: the end of a run by process.exit, final.
|
|
2
|
+
//
|
|
3
|
+
// What the engine does (measured: docs/research/browser-speed-2026-11/x5/default1/net/net.md, "Round 2"): process.exit(n) in the engine's core records the exit and asks
|
|
4
|
+
// the embedder to terminate the JavaScript (snapi_bridge_unofficial_terminate_execution). The browser bridge cannot interrupt running JavaScript and answers
|
|
5
|
+
// GENERIC_FAILURE, so the call returns and the program's next statements, callbacks and reactions run; the engine ends the process only when the main context
|
|
6
|
+
// returns (a `while (true) {}` after process.exit(0) never ends). Node's contract is that nothing after process.exit runs but the 'exit' listeners.
|
|
7
|
+
//
|
|
8
|
+
// The main Worker does what the contract needs: shim-post.js calls `__wmdExitNow(code)` as soon as the engine's exit call returned. This function ends the
|
|
9
|
+
// run as the Worker's normal end does (the page gets { type: 'exit', id, code, outs } and ends the Worker with the rest of the runtime when it releases the
|
|
10
|
+
// run) and then stops running JavaScript: the Worker parks for good in Atomics.wait, which no try/catch/finally of the program can intercept.
|
|
11
|
+
//
|
|
12
|
+
// makeExitNow({ runId, post, outs, cleanup, endProcess, park }) -> exitNow(code, pid)
|
|
13
|
+
// pid 1 (or none): the run's first process: the run ends (post) and the Worker parks.
|
|
14
|
+
// another pid: a node started by node inside this runtime ends itself only: endProcess(pid, code) (the runtime finishes that process with the code, as
|
|
15
|
+
// its main context's return would, so a wait on it answers) and the Worker parks; when the runtime does not know the process (false) nothing
|
|
16
|
+
// happens here and the program goes on as it did before this change.
|
|
17
|
+
export function makeExitNow({ runId, post, outs, cleanup = () => {}, endProcess = () => false, park }) {
|
|
18
|
+
let posted = false
|
|
19
|
+
const status = (code) => {
|
|
20
|
+
const n = Number(code)
|
|
21
|
+
return Number.isFinite(n) ? Math.trunc(n) & 255 : 0
|
|
22
|
+
}
|
|
23
|
+
return function exitNow(code, pid = 1) {
|
|
24
|
+
if (pid !== 1) {
|
|
25
|
+
let ended = false
|
|
26
|
+
try {
|
|
27
|
+
ended = endProcess(pid, status(code)) === true
|
|
28
|
+
} catch {
|
|
29
|
+
// the process is not ended by this call
|
|
30
|
+
}
|
|
31
|
+
if (ended) park()
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
if (!posted) {
|
|
35
|
+
posted = true
|
|
36
|
+
try {
|
|
37
|
+
cleanup()
|
|
38
|
+
} catch {
|
|
39
|
+
// the end of the run is posted whatever the cleanup did
|
|
40
|
+
}
|
|
41
|
+
post({ type: 'exit', id: runId(), code: status(code), outs: outs() })
|
|
42
|
+
}
|
|
43
|
+
park()
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Blocks this Worker for good (an engine that cannot Atomics.wait here has no SharedArrayBuffer, and the runtime does not run without one). */
|
|
48
|
+
export function parkForever() {
|
|
49
|
+
const cell = new Int32Array(new SharedArrayBuffer(4))
|
|
50
|
+
for (;;) Atomics.wait(cell, 0, 0)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The page's side: the end of a run as a Worker posted it. The main Worker names its run (`id`); a thread Worker, where the program's own JavaScript
|
|
55
|
+
* runs (the main context is a thread job of the pool), does not know it, so the earliest run still waiting is the one (a runtime serves one run at a
|
|
56
|
+
* time in the frame; a message of a run that is not waiting finds nobody). -> the message with `id`, or null when there is no run to end.
|
|
57
|
+
*/
|
|
58
|
+
export function exitOfRun(data, waiting) {
|
|
59
|
+
if (data.id != null) return data
|
|
60
|
+
const first = waiting.keys().next()
|
|
61
|
+
return first.done ? null : { ...data, id: first.value }
|
|
62
|
+
}
|
|
@@ -23,6 +23,7 @@ import { EBADF, EEXIST, EINVAL, EISDIR, ENOENT, ENOTDIR, ENOSYS, EROFS, fail } f
|
|
|
23
23
|
import { S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFSOCK, byteStr, bytesOf } from '../../fs/pack.js'
|
|
24
24
|
|
|
25
25
|
const SHIM_DIR = '/.wmd-edge'
|
|
26
|
+
const CTL_FILE = /^\/\.wmd-edge\/ctl\.\d+\.\d+$/ // X25 gate 1: python's control file (edge/src/linux.py `_ctl`)
|
|
26
27
|
const utf8 = s => new TextDecoder().decode(bytesOf(s))
|
|
27
28
|
const enc = new TextEncoder()
|
|
28
29
|
// A typed array that is a small view of a big buffer is copied before it is sent: a message to the other side carries the whole buffer of a view
|
|
@@ -36,7 +37,20 @@ const KIND = { [S_IFDIR]: 'd', [S_IFLNK]: 'l', [S_IFCHR]: 'c', [S_IFBLK]: 'b', [
|
|
|
36
37
|
/** Every method the route serves (the runtime's file calls, the page's shim and signal calls, ctl, the child calls): a name that is not here is ENOSYS. */
|
|
37
38
|
const RING_MAX = 120
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
// X25 gate 2c: what changes the container's tree. A run that made none of these changed nothing the guest has cached (the exit says `clean`, so the
|
|
41
|
+
// stub does not make the guest drop its kept names). The calls by name; a write to a file, an open that creates or truncates, and a ctl request that
|
|
42
|
+
// changes a mode, an owner, a time or a link are counted where they are served. A failed call counts too (it may have changed part of it).
|
|
43
|
+
const MUT_METHODS = new Set(['ftruncate', 'futimes', 'mkdir', 'unlink', 'rmdir', 'rename', 'symlink', 'link'])
|
|
44
|
+
const MUT_CTL = new Set(['chmod', 'lchmod', 'chown', 'lchown', 'utimes', 'lutimes', 'symlink', 'link'])
|
|
45
|
+
const ctlMutates = text => {
|
|
46
|
+
try {
|
|
47
|
+
return MUT_CTL.has(JSON.parse(String(text)).op)
|
|
48
|
+
} catch {
|
|
49
|
+
return false
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const METHODS = new Set(['shim', 'sigq', 'ctl', 'stat', 'readdir', 'open', 'read', 'write', 'fstat', 'ftruncate', 'futimes', 'close', 'mkdir', 'unlink', 'rmdir', 'rename', 'symlink', 'link', 'readlink', 'child_start', 'child_stdin', 'child_read', 'child_signal', 'net_connect', 'net_listen', 'net_resolve', 'net_udp', 'net_send', 'net_sendto', 'net_ack', 'net_close', 'net_shutdown', 'net_ctl', 'net_poll', 'note', 'peek', 'timing'])
|
|
40
54
|
|
|
41
55
|
export class OwnFsRoute {
|
|
42
56
|
/**
|
|
@@ -49,11 +63,14 @@ export class OwnFsRoute {
|
|
|
49
63
|
this.handles = new Map()
|
|
50
64
|
this.next = 1
|
|
51
65
|
this.ring = null // an array the owner keeps: the last calls and answers
|
|
66
|
+
this.ringMax = RING_MAX // how many it keeps (the owner sets it: EdgePorts.ringMax)
|
|
52
67
|
this.serdes = null // an array the owner keeps: the serializer lines of the Workers (fix5 round 6, only with the page's serdesNote)
|
|
53
68
|
this.shim = new Map(Object.entries(shimFiles).map(([k, v]) => [SHIM_DIR + '/' + k, enc.encode(v)]))
|
|
54
69
|
this.ctl = new EdgeCtl(fs, { root, mounts: { 1: { path: '' } } })
|
|
70
|
+
this.mut = 0 // the calls that changed (or may have changed) the tree: see MUT_METHODS
|
|
55
71
|
this.calls = Object.create(null) // counted by the method's name, which is the frame's (check5 F4): no inherited property
|
|
56
72
|
this.children = null // a ChildHost (child-host.js), set by the page that owns the children
|
|
73
|
+
this.net = null // a NetHost (net-host.js): the container's network for the frame's node, set by the page that owns the stub's session
|
|
57
74
|
this.sigs = new Map() // signals waiting for the program (id 0) or one of its node children, taken by the shim's pending_signal
|
|
58
75
|
}
|
|
59
76
|
|
|
@@ -115,6 +132,7 @@ export class OwnFsRoute {
|
|
|
115
132
|
}
|
|
116
133
|
const c = (this.calls[method] ||= { n: 0, errors: 0 })
|
|
117
134
|
c.n++
|
|
135
|
+
if (MUT_METHODS.has(method)) this.mut++
|
|
118
136
|
let res
|
|
119
137
|
const tm = this.timing
|
|
120
138
|
const t0 = tm ? performance.now() : 0
|
|
@@ -138,14 +156,15 @@ export class OwnFsRoute {
|
|
|
138
156
|
}
|
|
139
157
|
res = e && e.errno !== undefined ? err(CODES[e.errno] || 'EIO', e.message) : err('EIO', String((e && e.message) || e))
|
|
140
158
|
}
|
|
141
|
-
if (this.ring && (!method.startsWith('child_') || method === 'child_start' || method === 'child_signal') && method !== 'sigq' && method !== 'note') {
|
|
159
|
+
if (this.ring && !method.startsWith('net_') && (!method.startsWith('child_') || method === 'child_start' || method === 'child_signal') && method !== 'sigq' && method !== 'note') {
|
|
142
160
|
// the last calls with their paths and answers (a ring the owner keeps; a difference of the frame from the guest shows which call answered what)
|
|
143
161
|
const a0 = method.startsWith('child_') ? (args && args[0] && args[0].path) || String(Array.isArray(args) ? args[0] : args) : Array.isArray(args) ? args[0] : args
|
|
144
162
|
const a1 = Array.isArray(args) ? args[1] : undefined
|
|
145
163
|
const e = res && res.error
|
|
146
164
|
const rd = method === 'read' && Array.isArray(args) ? ` h${args[0]}@${args[1]}+${args[2]}=${res && res.value && res.value.length !== undefined ? res.value.length : (res && res.bytes ? res.bytes.length : '?')}` : ''
|
|
147
165
|
this.ring.push(`${method} ${typeof a0 === 'string' ? a0.slice(0, 80) : rd}${typeof a1 === 'string' ? ' ' + a1.slice(0, 80) : ''}${e ? ' -> ' + e.code : ''}`)
|
|
148
|
-
|
|
166
|
+
const max = this.ringMax
|
|
167
|
+
if (this.ring.length > max) this.ring.splice(0, this.ring.length - max)
|
|
149
168
|
}
|
|
150
169
|
return res
|
|
151
170
|
}
|
|
@@ -165,6 +184,7 @@ export class OwnFsRoute {
|
|
|
165
184
|
this.shim = new Map(Object.entries(a[0] || {}).map(([k, v]) => [SHIM_DIR + '/' + k, enc.encode(v)]))
|
|
166
185
|
return reply(null)
|
|
167
186
|
}
|
|
187
|
+
if (method.startsWith('net_')) return this.net ? this.net.handle(method, a, data) : err('ENOSYS', 'no network host on this page')
|
|
168
188
|
if (method.startsWith('child_')) return this.children ? this.children.handle(method, a, data) : err('ENOSYS', 'no child host on this page')
|
|
169
189
|
if (method === 'note') {
|
|
170
190
|
if (this.serdes && String(a[0]).startsWith('SERDES ')) {
|
|
@@ -192,6 +212,7 @@ export class OwnFsRoute {
|
|
|
192
212
|
return reply('{}')
|
|
193
213
|
}
|
|
194
214
|
if (q && q.op === 'pending_signal') return reply(JSON.stringify({ signals: this.sigs.get(Number(q.id) || 0)?.splice(0) || [] }))
|
|
215
|
+
if (ctlMutates(a[0])) this.mut++
|
|
195
216
|
return reply(JSON.stringify(this.ctl.handle(String(a[0] ?? ''))))
|
|
196
217
|
}
|
|
197
218
|
if (method === 'stat' || method === 'readdir' || method === 'open') {
|
|
@@ -214,6 +235,7 @@ export class OwnFsRoute {
|
|
|
214
235
|
case 'open': {
|
|
215
236
|
const f = a[1] || {}
|
|
216
237
|
const create = !!(f.c || f.cn)
|
|
238
|
+
if (create || f.t) this.mut++
|
|
217
239
|
let n
|
|
218
240
|
try {
|
|
219
241
|
n = this.#node(path(), true)
|
|
@@ -243,7 +265,13 @@ export class OwnFsRoute {
|
|
|
243
265
|
}
|
|
244
266
|
case 'write': {
|
|
245
267
|
const e = this.#h(a[0])
|
|
268
|
+
if (e.ctl) {
|
|
269
|
+
if (ctlMutates(new TextDecoder().decode(data))) this.mut++
|
|
270
|
+
e.bytes = enc.encode(JSON.stringify(this.ctl.handle(new TextDecoder().decode(data))) + '\n')
|
|
271
|
+
return reply({ n: data.length, p: data.length })
|
|
272
|
+
}
|
|
246
273
|
if (e.bytes) fail(EROFS)
|
|
274
|
+
this.mut++
|
|
247
275
|
const off = a[2] ? fs.size(e.n) : Number(a[1] ?? 0)
|
|
248
276
|
const n = fs.write(e.n, off, data)
|
|
249
277
|
return reply({ n, p: off + n })
|
|
@@ -323,6 +351,8 @@ export class OwnFsRoute {
|
|
|
323
351
|
|
|
324
352
|
#shimServe(method, p, a) {
|
|
325
353
|
if (method === 'stat') {
|
|
354
|
+
// X25 gate 1: python's control file exists for stat as it does for open (below); the runtime stats a path before it opens it
|
|
355
|
+
if (CTL_FILE.test(p)) return reply({ k: 'f', s: 0, a: '0', m: '0', c: '0', i: 3, nl: 1, md: 0o100644, u: 0, g: 0, rd: 0 })
|
|
326
356
|
const s = this.#shimStat(p)
|
|
327
357
|
if (!s) fail(ENOENT)
|
|
328
358
|
return reply(s)
|
|
@@ -335,6 +365,13 @@ export class OwnFsRoute {
|
|
|
335
365
|
return reply({ l, d: true })
|
|
336
366
|
}
|
|
337
367
|
const f = a[1] || {}
|
|
368
|
+
// X25 gate 1: python's shim talks to the control through a file it opens read-write, /.wmd-edge/ctl.<pid>.<thread> (edge/src/linux.py `_ctl`):
|
|
369
|
+
// a write is one request, and what is read back from it is the answer (src/edge/ctl.js, the same requests node's shim makes)
|
|
370
|
+
if (method === 'open' && CTL_FILE.test(p)) {
|
|
371
|
+
const h = this.next++
|
|
372
|
+
this.handles.set(h, { ctl: true, bytes: new Uint8Array(0), path: p })
|
|
373
|
+
return reply({ h })
|
|
374
|
+
}
|
|
338
375
|
if (f.w || f.c || f.cn || f.t || f.a) fail(EROFS)
|
|
339
376
|
const bytes = this.shim.get(p)
|
|
340
377
|
if (!bytes) fail(p === SHIM_DIR ? EISDIR : ENOENT)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// X25 gate 2b: the file-route round trips of a python run, counted by the runtime (edge/browser/src/fsroute.rs FSSTAT, ten u64 words):
|
|
2
|
+
// calls and microseconds in total, of `stat`, of `ctl`, of every other method; then the first call's start and the last call's end (microseconds, timeOrigin + now). The hub reads the table from the runtime's memory.
|
|
3
|
+
|
|
4
|
+
/** {n, us, stat, ctl, other} from the table at `addr` (8-aligned) of `buffer`, or null when there is none there. */
|
|
5
|
+
export function readFsStats(buffer, addr) {
|
|
6
|
+
if (!buffer || !addr || addr % 8 !== 0 || addr + 80 > buffer.byteLength) return null
|
|
7
|
+
const w = new BigUint64Array(buffer, addr, 10)
|
|
8
|
+
const v = i => Number(Atomics.load(w, i))
|
|
9
|
+
return { n: v(0), us: v(1), stat: { n: v(2), us: v(3) }, ctl: { n: v(4), us: v(5) }, other: { n: v(6), us: v(7) },
|
|
10
|
+
firstMs: v(8) ? v(8) / 1000 : null, lastMs: v(9) ? v(9) / 1000 : null }
|
|
11
|
+
}
|