@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.
Files changed (68) hide show
  1. package/README.md +239 -2
  2. package/RELEASE.json +97 -53
  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 +321 -12
  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/boot-setup.js +175 -0
  54. package/src/gowasm/make-pins-module.mjs +35 -0
  55. package/src/gowasm/pins-data.js +162 -0
  56. package/src/gowasm/setup.js +167 -0
  57. package/src/gowasm/twin-fetch.js +27 -0
  58. package/src/host/chan-service.js +33 -6
  59. package/src/host/chan-services.js +29 -4
  60. package/src/host/ckpt.js +78 -0
  61. package/src/host/csp-reason.js +64 -0
  62. package/src/host/ctl.js +30 -8
  63. package/src/host/edge-go.js +94 -4
  64. package/src/host/edge-host.js +58 -3
  65. package/src/host/gowasm-guard.js +11 -1
  66. package/src/host/gowasm-worker.js +90 -35
  67. package/src/host/pinned-fetch.js +436 -0
  68. package/wmdpack.wasm +0 -0
@@ -22,8 +22,9 @@
22
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
23
 
24
24
  import { RT_DEFAULT, deliversSignals, runtimeConfig } from './runtime.js'
25
- import { frameCounts } from './page.js'
25
+ import { frameCounts, useSite } from './page.js'
26
26
  import { addCounts } from './own/wasm-counters.js'
27
+ import { pythonModuleFor } from './python-module.js'
27
28
 
28
29
  const SIGNALS_BY_REASON = { killed: 9, terminated: 15 }
29
30
  /** Counts under a name: the name may come from the frame (`done.reason`), so it never reaches an inherited property (check5 F4). */
@@ -32,7 +33,11 @@ const counter = () => Object.create(null)
32
33
  /** 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
34
  export const SIGNAL_ENDS = new Set([1, 2, 3, 6, 9, 12, 14, 15])
34
35
  export const KILL_GRACE_MS = 3000
36
+ /** The fallback reason of a start that comes after the embedder's close() (X5 fix2 F1). */
37
+ export const EDGE_CLOSED = 'the edge setup was closed'
35
38
  const enc = new TextEncoder()
39
+ /** A umask as the kernel keeps it: an integer from 0 to 0777. The stub's hello carries the caller's (X5 fix3 R1); an older stub sends none and the shim takes 022. */
40
+ const validUmask = u => Number.isInteger(u) && u >= 0 && u <= 0o777
36
41
 
37
42
  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
43
 
@@ -45,8 +50,10 @@ function envObject(env) {
45
50
  return o
46
51
  }
47
52
 
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 = '' }) {
53
+ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT, edgeWasm = '/wasm/edgejs.wasm', linuxSrc = '', yieldMs = YIELD_OPEN_MS, run, onLog = () => {}, parallelism = 2, watch = {}, killGraceMs = KILL_GRACE_MS, site = null, handIn = null, nodeVersion = '', python = null, doc = globalThis.document, owner = null }) {
49
54
  const jobs = new Map()
55
+ // K1: this bridge's machine uses the frame site; when the last machine of the page that uses it ends, its kept frame goes (page.js useSite)
56
+ const releaseSite = useSite(owner || doc, origin)
50
57
  // 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
58
  const stage = (k, v) => {
52
59
  const e = ((stats.stages ||= {})[k] ||= { n: 0, ms: 0 })
@@ -78,13 +85,14 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
78
85
  rt,
79
86
  ...runtimeConfig(rt, handIn), // the runtime's own files (rt=own) or the base the caller handed the SDK in under (rt=sdk)
80
87
  edgeWasm,
88
+ ...(linuxSrc ? { linuxSrc } : {}), // the sandboxed frame hands the shim in under a name (src/edge/sbx/)
81
89
  args: (hello.argv || []).slice(1),
82
90
  env: envObject(hello.env),
83
91
  cwd: hello.cwd || '/',
84
92
  stream: true,
85
93
  stdin: 'pipe',
86
94
  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)
95
+ linux: { ...settings, uid: hello.uid, gid: hello.gid, utc: true, ...(nodeVersion ? { nodeVersion } : {}), ...(validUmask(hello.umask) ? { umask: hello.umask } : {}), ...(typeof hello.argv?.[0] === 'string' && hello.argv[0] ? { argv0: hello.argv[0] } : {}) }, // utc: a container with another TZ never gets here (edge-host.js helloRefusal)
88
96
  }
89
97
  const fallback = why => {
90
98
  if (job.ready || job.ended) return
@@ -93,6 +101,19 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
93
101
  bump(stats.fallbackWhy, why)
94
102
  answer({ id, ev: 'reply', fallback: why })
95
103
  }
104
+ // X25 gate 2: a start of the image's python (the page's plan took it: src/edge/plan.js planPython; the service decided this start: service-host.js)
105
+ // runs the frame's CPython of the image's version with the container's standard library through the file route, and python's shim (edge/src/linux.py)
106
+ if (/^python/.test(String(hello.argv?.[0] || '').split('/').pop())) {
107
+ if (!python) return fallback('python in the frame is off for this container')
108
+ const mod = pythonModuleFor(python.version)
109
+ if (!mod) return fallback(`image python ${python.version} has no module here`)
110
+ const sbx = String(linuxSrc).startsWith('sbx:') // the sandboxed frame: the page hands the files in under their names (src/edge/sbx/worker-entry.js)
111
+ cfg.edgeWasm = sbx ? `sbx:${mod.file}` : mod.url
112
+ cfg.linuxSrc = sbx ? 'sbx:linux.py' : '/wasm/linux.py'
113
+ cfg.args = hello.argv.slice(1)
114
+ cfg.python = { argv0: python.path, execPath: python.path, ...(python.maxMiB ? { maxMiB: python.maxMiB } : {}) }
115
+ cfg.linux = { ...cfg.linux, execPath: python.path }
116
+ }
96
117
  run({
97
118
  vm,
98
119
  job: id, // the service's number of this node run: the file route's port finds the stub's channel for children by it
@@ -132,6 +153,7 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
132
153
  site?.markDown(why, { kind: 'runtime' })
133
154
  }
134
155
  bump(stats.fallbackWhy, why)
156
+ stage('fallbackMs', performance.now() - job.t0) // fix round item 4 (F5a): the page's time from the start's arrival to its answer 'run it in the guest'
135
157
  return answer({ id, ev: 'reply', fallback: why })
136
158
  }
137
159
  stats.exits++
@@ -139,6 +161,11 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
139
161
  // 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
162
  if (r.stages) for (const [k, v] of Object.entries(r.stages)) if (typeof v === 'number') stage(k, v)
141
163
  if (r.setupMs) stage('frameSetup', r.setupMs) // the frame worker's load + start (adapter.js), as it measures itself
164
+ if (r.marks) {
165
+ // X5 default1 round 2 (B2.1): the last 40 runs' marks (page option edgeMarks=1, own/marks.js), with the time the page waited for the run
166
+ ;(stats.marksRuns ||= []).push({ ...r.marks, pageTotal: Math.round(performance.now() - job.t0), helloAbs: performance.timeOrigin + job.t0, exitAbs: performance.timeOrigin + performance.now() })
167
+ if (stats.marksRuns.length > 40) stats.marksRuns.shift()
168
+ }
142
169
  if (r.files) {
143
170
  // fix7 (F11): how the runtime's files stood against HASHES.txt, summed over the runs
144
171
  const t = (stats.files ||= { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 })
@@ -160,6 +187,7 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
160
187
  const t = (stats.capi ||= { messages: 0, bytes: 0, copies: 0, copyBytes: 0, maxMessage: 0, maxRecipients: 0, heldBytes: 0, heldPeak: 0 })
161
188
  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
189
  }
190
+ if (Number(r.forged) > 0) stats.forgedMessages = (stats.forgedMessages || 0) + Number(r.forged) // X5 fix3p P3: messages of the runtime's Workers that were of no known kind (dropped)
163
191
  if (r.pipes) {
164
192
  // what the runtime handed the adapter's pipes, summed over the runs, and the bytes that came after a pipe ended (lost)
165
193
  const t = (stats.pipes ||= { out: 0, err: 0, lateOut: 0, lateErr: 0, unreadOut: 0, unreadErr: 0 })
@@ -167,6 +195,10 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
167
195
  }
168
196
  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
197
  if (job.killedBy && r.reason !== 'exited') return answer({ id, ev: 'exit', code: 128 + job.killedBy, signal: job.killedBy })
198
+ // X5 fix3 R4: a program that ended by an unhandled signal of the guest's dies of that signal (the shell's `wait` and its job message are the same
199
+ // as for node in the guest); one that handled it and chose 128+n itself, or ended with another code, exits with its code
200
+ if (job.diedBy && (r.reason === 'exit' || r.reason === 'exited') && r.exitCode === 128 + job.diedBy) return answer({ id, ev: 'exit', code: r.exitCode, signal: job.diedBy })
201
+ if (r.signal) return answer({ id, ev: 'exit', code: 128 + r.signal, signal: r.signal }) // python: the default action of a signal ended it (adapter.js)
170
202
  const sig = Object.hasOwn(SIGNALS_BY_REASON, r.reason) ? SIGNALS_BY_REASON[r.reason] : undefined
171
203
  if (r.error) {
172
204
  const msg = enc.encode(`wmd: node's frame ended with an error: ${String(r.error).split('\n')[0]}\n`)
@@ -236,15 +268,26 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
236
268
  }
237
269
 
238
270
  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() } : {}) }),
271
+ stats: () => ({ ...stats, frames: { created: frameCounts.created, removed: frameCounts.removed, live: frameCounts.created - frameCounts.removed, kept: frameCounts.kept, reused: frameCounts.reused, stale: frameCounts.stale, released: frameCounts.released, capped: frameCounts.capped || 0 }, fallbackWhy: { ...stats.fallbackWhy }, lost: { ...stats.lost }, signals: { ...stats.signals }, ...(site ? { site: site.stats() } : {}) }),
240
272
  /** True while a run is open (the page refuses vm.checkpoint() then). */
241
273
  busy: () => stats.open > 0,
274
+ /**
275
+ * X5 fix2 F1: a start that comes after this bridge was closed while its machine still runs (the embedder's edge.close() came early): no run is made
276
+ * and no frame; the stub is told to run the image's node itself, and the fallback is counted with its reason. Any other event has no job to reach.
277
+ */
278
+ refuse(m, why) {
279
+ if (!m || m.ev !== 'start') return
280
+ stats.fallbacks++
281
+ bump(stats.fallbackWhy, why)
282
+ answer({ id: m.id, ev: 'reply', fallback: why })
283
+ },
242
284
  /** The machine this bridge belongs to has ended: every open run is ended through its control (its output has nowhere to go). */
243
285
  close() {
244
286
  for (const job of [...jobs.values()]) {
245
287
  clearTimeout(job.force)
246
288
  job.control.abort?.()
247
289
  }
290
+ releaseSite()
248
291
  },
249
292
  onMessage(m) {
250
293
  if (m.ev === 'start') return start(m)
@@ -260,6 +303,9 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
260
303
  clearTimeout(job.force)
261
304
  job.force = null
262
305
  stats.signalsHandled = (stats.signalsHandled || 0) + 1
306
+ } else if (SIGNAL_ENDS.has(m.n)) {
307
+ // X5 fix3 R4: no handler, and the signal's default action ends the program: it ends itself with 128+n (the shim), and the stub is told it died of n
308
+ job.diedBy = m.n
263
309
  }
264
310
  }
265
311
  else if (m.ev === 'gone') {
@@ -273,25 +319,48 @@ export function edgeBridge({ vm, p9port, origin, settings = {}, rt = RT_DEFAULT,
273
319
  /**
274
320
  * 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
321
  * 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).
322
+ * handle and closes the old one. The messages of a machine that was replaced are dropped (it has ended: nobody reads an answer).
323
+ * A machine whose bridge was closed by close() while the machine goes on (the embedder's edge.close() came early) is not that case: its stub
324
+ * still waits for an answer to each node start, so a start of it goes to the bridge it had, which answers it with the fallback (X5 fix2 F1).
325
+ * X5 fix3p P5: a machine that sent nothing before close() gets a bridge made only to refuse (counted) and release at once. close() is final for
326
+ * this option; a new boot gets a new option (setup.js bootOption), and setup.close() closes every option of the setup.
277
327
  * const per = bridgesPerMachine(machine => edgeBridge({vm: machine, ...})); per.onMessage(m, machine); per.busy(); per.current()
278
328
  */
279
329
  export function bridgesPerMachine(make) {
280
330
  let current = null
281
331
  let machine = null
282
- const retired = new WeakSet()
332
+ const retired = new WeakSet() // machines a restore replaced
333
+ const closedWith = new WeakMap() // machine -> the bridge it had when close() came
334
+ let closed = false // X5 fix3p P5: close() came; a machine this option has not seen yet is refused too
283
335
  return {
284
336
  current: () => current,
285
337
  busy: () => !!current?.busy(),
286
338
  onMessage(m, from) {
339
+ if (closed && !closedWith.has(from) && !retired.has(from)) {
340
+ // a machine that sent nothing before close(): it gets a bridge made only to count and answer the refusal, and released at once
341
+ const b = make(from)
342
+ b.close?.()
343
+ closedWith.set(from, b)
344
+ }
287
345
  if (from !== machine) {
346
+ if (closedWith.has(from)) return closedWith.get(from)?.refuse?.(m, EDGE_CLOSED)
288
347
  if (retired.has(from)) return
289
348
  if (machine) retired.add(machine)
349
+ // the next machine's bridge first, then the old one ends: the site keeps a user throughout and its kept frame stays (K1)
350
+ const next = make(from)
290
351
  current?.close?.()
291
352
  machine = from
292
- current = make(from)
353
+ current = next
293
354
  }
294
355
  current.onMessage(m)
295
356
  },
357
+ /** K1: the current machine ended (no restore follows): its bridge ends its runs and releases the frame site. */
358
+ close() {
359
+ closed = true
360
+ if (machine) closedWith.set(machine, current)
361
+ current?.close?.()
362
+ current = null
363
+ machine = null
364
+ },
296
365
  }
297
366
  }
package/src/edge/ctl.js CHANGED
@@ -9,10 +9,13 @@
9
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
10
  // size, rdev, nlink, blksize, blocks, ino, times), utimes, lutimes, statvfs, meminfo, and the three the SDK's memory has
11
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.
12
+ // The ops the desktop uses for child processes (alloc_exec_id, pending_signal, exitsig) answer with nothing to do; watch_start, watch_poll_all and
13
+ // watch_stop are the watchers of fs.watch (watch.js, X5 fix3 R5).
13
14
  // A reply is the op's JSON, or {err: 'ENOENT'} (a code name, which linux.cjs's ctlError reads).
14
15
 
15
16
  import { CODES } from './codes.js'
17
+ import { Sems, semOp } from './sems.js'
18
+ import { PathWatches } from './watch.js'
16
19
  import { resolveIn } from './resolve.js'
17
20
  import { S_IFLNK, S_IFMT, byteStr } from '../fs/pack.js'
18
21
  import { MAX_SYMLINKS } from '../fs/overlay.js'
@@ -27,11 +30,13 @@ export class EdgeCtl {
27
30
  * @param {{root?: string, mounts: Object<string, {path: string, ro?: boolean}>}} o `mounts` as the file route has them: the
28
31
  * container paths the SDK's mounts show. A path outside every mount is not the frame's to change (ENOENT).
29
32
  */
30
- constructor(fs, { root = '', mounts }) {
33
+ constructor(fs, { root = '', mounts, now = () => performance.now() }) {
31
34
  this.fs = fs
35
+ this.watches = new PathWatches(fs, now)
32
36
  this.rootPath = root
33
37
  this.areas = Object.values(mounts).map(m => ({ prefix: '/' + m.path.replace(/^\/+|\/+$/g, ''), ro: !!m.ro }))
34
38
  this.execId = 0
39
+ this.sems = new Sems() // named semaphores of the run's processes (python's multiprocessing), sems.js
35
40
  }
36
41
 
37
42
  #root() {
@@ -107,6 +112,7 @@ export class EdgeCtl {
107
112
  #op(r) {
108
113
  const fs = this.fs
109
114
  const p = String(r.path ?? '')
115
+ if (typeof r.op === 'string' && r.op.startsWith('sem_')) return semOp(this.sems, r) ?? { err: 'ENOSYS' }
110
116
  switch (r.op) {
111
117
  case 'chmod':
112
118
  case 'lchmod': {
@@ -174,11 +180,22 @@ export class EdgeCtl {
174
180
  }
175
181
  case 'alloc_exec_id':
176
182
  return { id: ++this.execId }
183
+ case 'watch_start': {
184
+ // X5 fix3 R5: compared scans of the Overlay (src/edge/watch.js), not an error that ends a dev server
185
+ const n = this.#node(p, true, false)
186
+ const id = this.watches.start(n, p.split('/').filter(x => x !== '').at(-1) ?? '', r.recursive)
187
+ return id === null ? { err: 'ENOSPC' } : { id }
188
+ }
189
+ case 'watch_poll_all': {
190
+ const events = this.watches.poll()
191
+ return events.length ? { events } : {}
192
+ }
193
+ case 'watch_stop':
194
+ this.watches.stop(r.id)
195
+ return {}
177
196
  case 'pending_signal':
178
197
  case 'exitsig':
179
198
  case 'set_exitsig':
180
- case 'watch_poll_all':
181
- case 'watch_stop':
182
199
  return {}
183
200
  default:
184
201
  return { err: 'ENOSYS' }
@@ -2,3 +2,9 @@
2
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
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
4
  export const errorKindOf = (e, loading) => (loading || (e && e.runtimeFiles === true) ? 'runtime' : undefined)
5
+ /**
6
+ * X5 fix2 F4: the words an errorKind may be when it travels (frame -> page): the page and the frame both keep a value only when it is one of these, never
7
+ * free text that decides behaviour. 'runtime': the runtime's, the program's or the settings file's fetch failed (a missing file, an answer that is not ok).
8
+ */
9
+ export const ERROR_KINDS = new Set(['runtime'])
10
+ export const kindWord = k => (typeof k === 'string' && ERROR_KINDS.has(k) ? k : undefined)