@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.
Files changed (62) hide show
  1. package/README.md +23 -2
  2. package/RELEASE.json +123 -16
  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 +47 -2
  8. package/src/edge/bridge.js +297 -0
  9. package/src/edge/codes.js +10 -0
  10. package/src/edge/ctl.js +199 -0
  11. package/src/edge/error-kind.js +4 -0
  12. package/src/edge/frame.html +4 -0
  13. package/src/edge/frame.js +48 -0
  14. package/src/edge/fs-route.js +301 -0
  15. package/src/edge/hist.js +46 -0
  16. package/src/edge/msg.js +106 -0
  17. package/src/edge/node-args.js +194 -0
  18. package/src/edge/node-guest-opts.js +108 -0
  19. package/src/edge/node-opts.js +82 -0
  20. package/src/edge/own/adapter.js +271 -0
  21. package/src/edge/own/capi.js +200 -0
  22. package/src/edge/own/child-host.js +196 -0
  23. package/src/edge/own/fs-bridge.js +71 -0
  24. package/src/edge/own/fs-own-route.js +356 -0
  25. package/src/edge/own/guest-spawner.js +235 -0
  26. package/src/edge/own/hub.js +430 -0
  27. package/src/edge/own/loader.js +81 -0
  28. package/src/edge/own/memcap.js +95 -0
  29. package/src/edge/own/payload-size.js +15 -0
  30. package/src/edge/own/pool.js +160 -0
  31. package/src/edge/own/procfs.js +84 -0
  32. package/src/edge/own/serdes-codec.js +317 -0
  33. package/src/edge/own/service-receiver.js +98 -0
  34. package/src/edge/own/shim-post.js +185 -0
  35. package/src/edge/own/stack-fix.js +36 -0
  36. package/src/edge/own/stdio-pipe.js +80 -0
  37. package/src/edge/own/v8-serdes.js +970 -0
  38. package/src/edge/own/wasm-counters.js +144 -0
  39. package/src/edge/own/worker.js +97 -0
  40. package/src/edge/page.js +162 -0
  41. package/src/edge/plan.js +65 -0
  42. package/src/edge/resolve.js +44 -0
  43. package/src/edge/runtime.js +94 -0
  44. package/src/edge/sdk/adapter.js +151 -0
  45. package/src/edge/sdk/forward.js +80 -0
  46. package/src/edge/sdk/napi-stub.js +50 -0
  47. package/src/edge/sdk/relay.js +17 -0
  48. package/src/edge/service-host.js +382 -0
  49. package/src/edge/service-port.js +245 -0
  50. package/src/edge/shim.js +161 -0
  51. package/src/edge/site.js +106 -0
  52. package/src/edge/spawn-guard.js +80 -0
  53. package/src/edge/tz.js +103 -0
  54. package/src/edge/worker.js +121 -0
  55. package/src/edge/workers.js +27 -0
  56. package/src/host/chan-service.js +75 -8
  57. package/src/host/chan-services.js +77 -3
  58. package/src/host/ctl.js +26 -5
  59. package/src/host/edge-go.js +7 -3
  60. package/src/host/edge-host.js +327 -0
  61. package/src/host/yamux.js +21 -8
  62. package/wmdpack.wasm +0 -0
@@ -0,0 +1,151 @@
1
+ // X5 part B (switch edge=1): the SDK adapter, the first implementation of the runtime seam (src/edge/runtime.js).
2
+ // Everything that is the Wasmer SDK's, and nothing else, is here and in this folder: the SDK's host-file bridge (forward.js,
3
+ // relay.js), the stub for the one N-API import it lacks (napi-stub.js) and wmd-edge's shim as the SDK's node needs it (shim.js).
4
+ // No file of the SDK is in the repository: the frame's server serves the published package under cfg.rtBase ('/sdk/').
5
+ //
6
+ // The seam (what any runtime gives the frame's worker):
7
+ // load({cfg, ports, log, onWorkerError}) -> {fallback?: {reason, ...}} fetch and set up; ports: [file route port, second port]
8
+ // start({module, argv, env, cwd, mounts, files, linux, linuxSrc, stdin, timeoutMs, parallelism, spawnMark}) -> proc
9
+ // spawnMark: the text this run's spawn guard prints in front of the command a program tried to start (the worker makes it: spawn-guard.js)
10
+ // module: URL of the node core; mounts: [[path, id, readOnly]]; stdin: 'pipe' | 'closed'; stdout and stderr are pipes
11
+ // proc: {readStdout(n), readStderr(n), writeStdin(bytes), closeStdin()}
12
+ // signal(proc, n) 9 ends the program at once, 2 and 15 end it after a grace period; others are not sent
13
+ // exit(proc) -> Promise<{exitCode, reason}>
14
+ // teardown() -> closes the sandbox and the runtime
15
+ // stats() -> {service, frameRtt} the file route's counters, once
16
+ // release() (optional) terminates every Worker the adapter made that is still alive; called on every way a run ends
17
+ import { Forwarder } from './forward.js'
18
+ import { shimSource } from '../shim.js'
19
+ import { withUtcClock } from '../tz.js'
20
+ import { workerRegistry } from '../workers.js'
21
+ import { withSpawnGuard } from '../spawn-guard.js'
22
+
23
+ export const name = 'sdk'
24
+
25
+ const HOST_FS_MESSAGE = 'wasmer-filesystem-rpc'
26
+ const enc = new TextEncoder()
27
+ let fwd = null
28
+ let relay = null
29
+ let wasmer = null
30
+ let sb = null
31
+ let pkg = null
32
+ let core = null
33
+ let baseUrl = '/sdk/'
34
+ let RealWorker = null
35
+ const workers = workerRegistry() // every Worker made here: the SDK's thread Workers (wrapWorkers) and the relay
36
+
37
+ // Every Worker this module makes (the SDK's thread Workers among them): its file calls are taken here, and a Worker that cannot load
38
+ // (the server went away, a blocked script) is reported, so the run ends with an error and not a wait.
39
+ function wrapWorkers(onWorkerError) {
40
+ if (RealWorker) return
41
+ RealWorker = globalThis.Worker
42
+ globalThis.Worker = class extends RealWorker {
43
+ constructor(...a) {
44
+ super(...a)
45
+ workers.track(this)
46
+ this.addEventListener('message', e => {
47
+ const m = e.data
48
+ if (m && m.type === HOST_FS_MESSAGE && m.response && fwd) {
49
+ e.stopImmediatePropagation()
50
+ fwd.send(m)
51
+ }
52
+ })
53
+ this.addEventListener('error', e => onWorkerError?.(String((e && e.message) || 'a Worker failed to load or crashed')))
54
+ }
55
+ }
56
+ }
57
+
58
+ export async function load({ cfg, ports, log, onWorkerError }) {
59
+ baseUrl = cfg.rtBase || '/sdk/'
60
+ wrapWorkers(onWorkerError)
61
+ const t0 = performance.now()
62
+ const hf = await import(baseUrl + 'dist/host-filesystem.js')
63
+ fwd = new Forwarder(ports[0], hf.respondToHostFileSystem)
64
+ relay = workers.track(new RealWorker('/edge/sdk/relay.js', { type: 'module' }))
65
+ relay.addEventListener('error', e => onWorkerError?.('the relay Worker failed: ' + String((e && e.message) || '')))
66
+ await new Promise(r => {
67
+ relay.onmessage = () => r()
68
+ relay.postMessage({ port: ports[1] }, [ports[1]])
69
+ })
70
+ // this Worker's own file calls (the sandbox's cwd check) go to the relay and block here until it answers
71
+ hf.installHostFileSystemWorkerBridge(msg => (relay.postMessage(msg), true))
72
+ // before anything starts: a directory the bridge cannot list sends the container to the guest (docs/plans/x5-browser-node.md risk 9)
73
+ const plan = await fwd.plan()
74
+ if (plan.oversize.length) return { fallback: { reason: 'listing-too-large', oversize: plan.oversize.slice(0, 20) } }
75
+ const { Wasmer } = await import(baseUrl + 'dist/index.js')
76
+ wasmer = new Wasmer({ cache: 'memory', parallelism: cfg.parallelism || 2 })
77
+ core = await wasmer.getCore()
78
+ log('sdk loaded after ' + (performance.now() - t0).toFixed(0) + ' ms')
79
+ return {}
80
+ }
81
+
82
+ export async function start({ module, argv, env, cwd, mounts, files = {}, linux, linuxSrc, stdin = 'closed', timeoutMs, parallelism, spawnMark }) {
83
+ const edge = new Uint8Array(await (await fetch(module)).arrayBuffer())
84
+ const fileBytes = Object.fromEntries(Object.entries(files).map(([p, t]) => [p, enc.encode(t)]))
85
+ let args = argv
86
+ // identity: wmd-edge's shim, preloaded as on the desktop, with the container's settings written in place of its config object
87
+ if (linux) {
88
+ const shim = '/.wmd-edge/linux.cjs'
89
+ const src = await (await fetch(linuxSrc || '/wasm/linux.cjs')).text()
90
+ const text = shimSource(src, linux)
91
+ // the container's zone is UTC (src/edge/tz.js); a spawn ends the run with a clear line and exit 126 (src/edge/spawn-guard.js)
92
+ fileBytes[shim] = enc.encode(withSpawnGuard(linux.utc ? withUtcClock(text) : text, spawnMark))
93
+ args = ['--require', shim, ...args]
94
+ }
95
+ pkg = await core.createPackage({ modules: { node: edge }, commands: { node: { module: 'node' } }, files: fileBytes })
96
+ const b = core.sandbox()
97
+ b.package(pkg)
98
+ b.env('HOME', '/root')
99
+ for (const [k, v] of Object.entries(env || {})) b.env(k, v)
100
+ b.network('disabled')
101
+ for (const [path, id, ro] of mounts) b.mountHost(path, id, ro)
102
+ sb = await b.start()
103
+ await fwd.reset()
104
+ const cmd = sb.commandPackage(pkg)
105
+ cmd.args(args)
106
+ if (cwd) cmd.currentDir(cwd)
107
+ // the runtime wants a number of ms and has a limit of its own by default (10 minutes); a node server or a long job runs as long as it does in the
108
+ // guest, so the run's limit is the largest 32-bit value (24 days) unless the page asks for one. A dead frame is the page's ping watch's to find.
109
+ cmd.timeoutMs(timeoutMs || 2 ** 31 - 1)
110
+ // stdio as pipes (the SDK's live modes), not a terminal: node reports isTTY false and npm draws no spinner
111
+ cmd.stdinMode(stdin)
112
+ cmd.stdoutMode('pipe')
113
+ cmd.stderrMode('pipe')
114
+ const pr = await cmd.spawn()
115
+ return {
116
+ pr,
117
+ readStdout: n => pr.readStdout(n),
118
+ readStderr: n => pr.readStderr(n),
119
+ writeStdin: bytes => pr.writeStdin(bytes),
120
+ closeStdin: () => pr.closeStdin(),
121
+ }
122
+ }
123
+
124
+ export async function signal(proc, n) {
125
+ if (n === 9) return proc.pr.kill()
126
+ return proc.pr.terminate(2000)
127
+ }
128
+
129
+ export async function exit(proc) {
130
+ const w = await proc.pr.wait()
131
+ return { exitCode: w.exitCode, reason: w.reason }
132
+ }
133
+
134
+ export async function teardown() {
135
+ try {
136
+ await sb?.close()
137
+ } finally {
138
+ await wasmer?.close()
139
+ }
140
+ }
141
+
142
+ /** Ends every Worker this adapter made that is still alive (worker.js calls it on every way a run ends, before it says done). */
143
+ export function release() {
144
+ return workers.release()
145
+ }
146
+
147
+ export const liveWorkers = () => workers.size()
148
+
149
+ export async function stats() {
150
+ return { service: fwd ? await fwd.stats() : null, frameRtt: fwd ? fwd.rttSummary() : null }
151
+ }
@@ -0,0 +1,80 @@
1
+ // X5 part B (switch edge=1): in the frame, the part that carries one SDK file request to the channel service and
2
+ // writes the reply into the blocked caller's buffer.
3
+ //
4
+ // An SDK Worker that needs a file call posts {type: 'wasmer-filesystem-rpc', mount, method, args, response}
5
+ // (response: a SharedArrayBuffer it then waits on). The embedder takes the request, asks the service over a
6
+ // MessagePort (src/edge/service-port.js) and calls `respond(request, reply)`, which writes the reply and wakes the
7
+ // caller. One Forwarder per port. `sent` times (round trip as the frame sees it) go in a histogram per method.
8
+
9
+ import { Hist } from '../hist.js'
10
+
11
+ const epochMs = () => performance.timeOrigin + performance.now()
12
+
13
+ export class Forwarder {
14
+ /**
15
+ * @param {MessagePort} port to the channel service
16
+ * @param {(request: object, reply: object) => void} respond the SDK's respondToHostFileSystem
17
+ */
18
+ constructor(port, respond) {
19
+ this.port = port
20
+ this.respond = respond
21
+ this.pending = new Map() // id -> {request, t0, method}
22
+ this.next = 1
23
+ this.rtt = {} // method -> Hist (post to reply, as seen here)
24
+ this.stat = new Map() // id -> resolve (stats requests)
25
+ port.onmessage = ({ data: m }) => this.#reply(m)
26
+ }
27
+
28
+ /** The SDK's request m, sent to the service. */
29
+ send(m) {
30
+ const id = this.next++
31
+ const t0 = performance.now()
32
+ this.pending.set(id, { request: m, t0, method: m.method })
33
+ this.port.postMessage({ id, mount: m.mount, method: m.method, args: m.args, t0: performance.timeOrigin + t0 })
34
+ }
35
+
36
+ #reply(m) {
37
+ if (m.stats !== undefined || m.reset || m.plan) {
38
+ const r = this.stat.get(m.id)
39
+ this.stat.delete(m.id)
40
+ if (r) r(m)
41
+ return
42
+ }
43
+ const p = this.pending.get(m.id)
44
+ if (!p) return
45
+ this.pending.delete(m.id)
46
+ ;(this.rtt[p.method] ||= new Hist()).add((performance.now() - p.t0) * 1000)
47
+ this.respond(p.request, m.res)
48
+ }
49
+
50
+ /** The service's counters (its crossings, waits and work), once. */
51
+ stats() {
52
+ return new Promise(res => {
53
+ const id = this.next++
54
+ this.stat.set(id, m => res(m.stats))
55
+ this.port.postMessage({ id, op: 'stats' })
56
+ })
57
+ }
58
+
59
+ /** What the service knows before node starts: the directories it could not list (see EdgeFsRoute.oversizeDirs). */
60
+ plan() {
61
+ return new Promise(res => {
62
+ const id = this.next++
63
+ this.stat.set(id, m => res(m.plan))
64
+ this.port.postMessage({ id, op: 'plan' })
65
+ })
66
+ }
67
+
68
+ reset() {
69
+ return new Promise(res => {
70
+ const id = this.next++
71
+ this.stat.set(id, () => res())
72
+ this.port.postMessage({ id, op: 'reset' })
73
+ this.rtt = {}
74
+ })
75
+ }
76
+
77
+ rttSummary() {
78
+ return Object.fromEntries(Object.entries(this.rtt).map(([k, h]) => [k, h.summary()]))
79
+ }
80
+ }
@@ -0,0 +1,50 @@
1
+ // X5 part B (switch edge=1): loaded first in every Wasmer SDK Worker (the frame's server puts an import of
2
+ // this file in front of the SDK's browser-worker.js; the SDK's own files are not changed on disk).
3
+ //
4
+ // wmd's edgejs.wasm imports one N-API function the published SDK does not provide,
5
+ // `unofficial_napi_to_detail_string`. This fills any import of an Edge.js module that nothing provides with a
6
+ // function that returns napi_generic_failure (9), so the module links. Nothing else is wrapped.
7
+ const stubbed = new Map()
8
+
9
+ function isEdge(imports) {
10
+ return imports && typeof imports === 'object' && ('napi' in imports || 'napi_extension_wasmer_v0' in imports)
11
+ }
12
+
13
+ function prepare(module, imports) {
14
+ if (!isEdge(imports)) return imports
15
+ const out = {}
16
+ for (const ns of Object.keys(imports)) out[ns] = { ...imports[ns] }
17
+ for (const d of WebAssembly.Module.imports(module)) {
18
+ if (d.kind !== 'function') continue
19
+ const ns = out[d.module] || (out[d.module] = {})
20
+ if (!(d.name in ns)) {
21
+ stubbed.set(d.name, 0)
22
+ ns[d.name] = () => {
23
+ stubbed.set(d.name, stubbed.get(d.name) + 1)
24
+ return 9
25
+ }
26
+ }
27
+ }
28
+ return out
29
+ }
30
+
31
+ const RealInstance = WebAssembly.Instance
32
+ WebAssembly.Instance = function (module, imports) {
33
+ return new RealInstance(module, prepare(module, imports))
34
+ }
35
+ WebAssembly.Instance.prototype = RealInstance.prototype
36
+
37
+ const realInstantiate = WebAssembly.instantiate
38
+ WebAssembly.instantiate = function (source, imports) {
39
+ if (source instanceof WebAssembly.Module) return realInstantiate.call(this, source, prepare(source, imports))
40
+ return realInstantiate.call(this, source, imports)
41
+ }
42
+
43
+ // linux.cjs (wmd's preloaded shim, edge/src/linux.cjs) asks the host for what a file protocol with no mode, owner or link
44
+ // count cannot give: `__wmdCtl(pid, json)` returns the JSON reply, as wmd-edge's host function does on the desktop.
45
+ // Here it is one call on the SDK's own synchronous bridge: method `ctl`, mount 0, answered by src/edge/ctl.js in the machine's
46
+ // channel service. linux.cjs takes the function off the global when it loads (and falls back to a control file if
47
+ // there is none, which nothing here serves), so it must exist before the program starts.
48
+ if (typeof globalThis.__wmdCtl === 'undefined') {
49
+ globalThis.__wmdCtl = (pid, json) => globalThis.__wasmerHostFileSystem(0, 'ctl', [json])
50
+ }
@@ -0,0 +1,17 @@
1
+ // X5 part B (switch edge=1): the frame's relay Worker. The SDK's scheduler Worker makes file calls of its own
2
+ // (at sandbox start) and blocks on them, so it cannot also receive the reply from the channel service. Its
3
+ // requests come here; this Worker has a MessagePort of its own to the service, asks it and writes the reply into
4
+ // the scheduler's buffer.
5
+ import { respondToHostFileSystem } from '/sdk/dist/host-filesystem.js'
6
+ import { Forwarder } from './forward.js'
7
+
8
+ let fwd = null
9
+ onmessage = ({ data }) => {
10
+ if (data.port) {
11
+ fwd = new Forwarder(data.port, respondToHostFileSystem)
12
+ postMessage({ ready: true })
13
+ return
14
+ }
15
+ if (data.op === 'rtt') return postMessage({ rtt: fwd.rttSummary() })
16
+ fwd.send(data)
17
+ }