@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
@@ -0,0 +1,35 @@
1
+ // Writes src/gowasm/pins-data.js from src/gowasm/pins.json (the one file scripts/gowasm/pins.mjs and the release workflow keep): the pins as a JS module,
2
+ // so that a bundler cannot separate the code from its pins and no request is made for them. `node src/gowasm/make-pins-module.mjs` regenerates it;
3
+ // `--check` exits 1 when the module is not what pins.json would give (a unit test, x6-boot.test.js, says the same). The PACKAGES part below the marker is
4
+ // kept as it is: it names, per Go release, the npm package that holds the twin and is filled in by hand when the package exists.
5
+ import { readFileSync, writeFileSync } from 'node:fs'
6
+
7
+ const here = new URL('.', import.meta.url)
8
+ const MARK = '// ---- the part below is written by hand (make-pins-module.mjs keeps it) ----'
9
+ const pins = JSON.parse(readFileSync(new URL('pins.json', here), 'utf8'))
10
+ const head = `// GENERATED from src/gowasm/pins.json by src/gowasm/make-pins-module.mjs: do not edit above the marker. A unit test (x6-boot.test.js) says the two are equal.
11
+ // The pins of the Go compiler's Wasm twin as a JS module: per Go release the twin's sha256 and size and, per architecture, the sha256 of the guest's own
12
+ // compile with its path in the image. No import: a bundler cannot separate this code from its pins.
13
+ export const PINS = ${JSON.stringify(pins, null, 2)}
14
+
15
+ `
16
+ let tail = `${MARK}
17
+ /**
18
+ * Per Go release (key: the release, like '1.25.14'): the npm package that holds the twin, as {name, version}. A release with no entry has no package: a
19
+ * source that needs one ({name} in its url) is skipped for it with a reason, and a plain base still works. The planned shape:
20
+ * name '@threadedstack/wmd-gowasm', version '<go release>-<revision>', the twin at 'compile-<go release>.wasm' inside it (PINS releases[...].twin.file).
21
+ */
22
+ export const PACKAGES = {}
23
+ `
24
+ let old = ''
25
+ try {
26
+ old = readFileSync(new URL('pins-data.js', here), 'utf8')
27
+ } catch {}
28
+ if (old.includes(MARK)) tail = old.slice(old.indexOf(MARK))
29
+ const out = head + tail
30
+ if (process.argv.includes('--check')) {
31
+ if (old !== out) {
32
+ console.error('pins-data.js is not what pins.json gives')
33
+ process.exit(1)
34
+ }
35
+ } else writeFileSync(new URL('pins-data.js', here), out)
@@ -0,0 +1,162 @@
1
+ // GENERATED from src/gowasm/pins.json by src/gowasm/make-pins-module.mjs: do not edit above the marker. A unit test (x6-boot.test.js) says the two are equal.
2
+ // The pins of the Go compiler's Wasm twin as a JS module: per Go release the twin's sha256 and size and, per architecture, the sha256 of the guest's own
3
+ // compile with its path in the image. No import: a bundler cannot separate this code from its pins.
4
+ export const PINS = {
5
+ "version": 1,
6
+ "release": {
7
+ "repo": "threadedstack/wmd-releases",
8
+ "tag": "gowasm-modules",
9
+ "baseUrl": "https://github.com/threadedstack/wmd-releases/releases/download/gowasm-modules",
10
+ "redirectHosts": [
11
+ "github.com",
12
+ "objects.githubusercontent.com",
13
+ "release-assets.githubusercontent.com"
14
+ ]
15
+ },
16
+ "releases": {
17
+ "1.25.14": {
18
+ "twin": {
19
+ "file": "compile-1.25.14.wasm",
20
+ "sha256": "b758cab40ddb2027f6579e5d15b444b06f75b0e748b9c17c85b15663d2c29d39",
21
+ "size": 41102658
22
+ },
23
+ "notices": {
24
+ "file": "compile-1.25.14.NOTICES.txt",
25
+ "sha256": "9d543a6292351d6172e18d67affeb2fe502111a3bfb560a009acf3e67b466189",
26
+ "size": 4925
27
+ },
28
+ "tools": {
29
+ "8e43c7337f0092969078696e9d291ffbe1646187510324359b29faf15d7a6700": {
30
+ "name": "compile",
31
+ "path": "/usr/local/go/pkg/tool/linux_arm64/compile",
32
+ "arch": "arm64",
33
+ "size": 20271801,
34
+ "goVersion": "1.25.14",
35
+ "check": {
36
+ "passed": true,
37
+ "script": "scripts/gowasm/check-twin.sh",
38
+ "compiles": 94,
39
+ "identical": 94,
40
+ "variant": [],
41
+ "referenceVsGuest": null
42
+ }
43
+ },
44
+ "7c4c460753bc9cff43a87858b9510fbc82daeeb05ddf8afd6c4518b6dc6d5497": {
45
+ "name": "compile",
46
+ "path": "/usr/local/go/pkg/tool/linux_amd64/compile",
47
+ "arch": "amd64",
48
+ "size": 21654239,
49
+ "goVersion": "1.25.14",
50
+ "check": {
51
+ "passed": true,
52
+ "script": "scripts/gowasm/check-twin.sh",
53
+ "compiles": 94,
54
+ "identical": 94,
55
+ "variant": [],
56
+ "referenceVsGuest": null
57
+ }
58
+ }
59
+ }
60
+ },
61
+ "1.26.11": {
62
+ "twin": {
63
+ "file": "compile-1.26.11.wasm",
64
+ "sha256": "50a941beef8a134a2d24091afb272c0d68efc600da68b79109fd6b32b5e8054e",
65
+ "size": 48090349
66
+ },
67
+ "notices": {
68
+ "file": "compile-1.26.11.NOTICES.txt",
69
+ "sha256": "bc1b393922fe1555772d5fe70f17ea96f2ccb7386544444696a0c1982b9ec80b",
70
+ "size": 4925
71
+ },
72
+ "tools": {
73
+ "fcd8ab38428db95acaa3e732570798c354ccbf8521394396acc29549c3e69d68": {
74
+ "name": "compile",
75
+ "path": "/usr/local/go/pkg/tool/linux_arm64/compile",
76
+ "arch": "arm64",
77
+ "size": 24254837,
78
+ "goVersion": "1.26.11",
79
+ "check": {
80
+ "passed": true,
81
+ "script": "scripts/gowasm/check-twin.sh",
82
+ "compiles": 96,
83
+ "identical": 96,
84
+ "variant": [],
85
+ "referenceVsGuest": null
86
+ }
87
+ },
88
+ "896a17923b901c9581505c08e8ed1c5a2a6b1b519beb457ceb106f1b59373329": {
89
+ "name": "compile",
90
+ "path": "/usr/local/go/pkg/tool/linux_amd64/compile",
91
+ "arch": "amd64",
92
+ "size": 25787792,
93
+ "goVersion": "1.26.11",
94
+ "check": {
95
+ "passed": true,
96
+ "script": "scripts/gowasm/check-twin.sh",
97
+ "compiles": 96,
98
+ "identical": 96,
99
+ "variant": [],
100
+ "referenceVsGuest": null
101
+ }
102
+ }
103
+ }
104
+ },
105
+ "1.27.4": {
106
+ "twin": {
107
+ "file": "compile-1.27.4.wasm",
108
+ "sha256": "4d623c4a04c2b4e115106f18c0ad0b8d0a4c797940d9edd94ec5a79e92b610ca",
109
+ "size": 52519098
110
+ },
111
+ "notices": {
112
+ "file": "compile-1.27.4.NOTICES.txt",
113
+ "sha256": "a02e47842837f5c99a0f07a6ca96e7dcaee4c67433a20a60b610d6da865bd600",
114
+ "size": 4919
115
+ },
116
+ "tools": {
117
+ "4070e0e743ba23672219a3687a1f9bfb489fa5c95bfb6584b4f33932339f92ef": {
118
+ "name": "compile",
119
+ "path": "/usr/local/go/pkg/tool/linux_arm64/compile",
120
+ "arch": "arm64",
121
+ "size": 26606430,
122
+ "goVersion": "1.27.4",
123
+ "check": {
124
+ "passed": true,
125
+ "script": "scripts/gowasm/check-twin.sh",
126
+ "compiles": 95,
127
+ "identical": 95,
128
+ "variant": [],
129
+ "referenceVsGuest": null
130
+ }
131
+ },
132
+ "40307e5f5c65a4b4220bbf35dbe014348780589ea2964003f0bf318fa14640e1": {
133
+ "name": "compile",
134
+ "path": "/usr/local/go/pkg/tool/linux_amd64/compile",
135
+ "arch": "amd64",
136
+ "size": 28272322,
137
+ "goVersion": "1.27.4",
138
+ "check": {
139
+ "passed": true,
140
+ "script": "scripts/gowasm/check-twin.sh",
141
+ "compiles": 95,
142
+ "identical": 95,
143
+ "variant": [],
144
+ "referenceVsGuest": null
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ // ---- the part below is written by hand (make-pins-module.mjs keeps it) ----
153
+ /**
154
+ * Per Go release (key: the release, like '1.25.14'): the npm package that holds the twin, as {name, version}. A release with no entry has no package: a
155
+ * source that needs one ({name} in its url) is skipped for it with a reason, and a plain base still works. The planned shape:
156
+ * name '@threadedstack/wmd-gowasm', version '<go release>-<revision>', the twin at 'compile-<go release>.wasm' inside it (PINS releases[...].twin.file).
157
+ */
158
+ export const PACKAGES = {
159
+ '1.25.14': { name: '@threadedstack/wmd-gowasm', version: '1.25.14-1' },
160
+ '1.26.11': { name: '@threadedstack/wmd-gowasm', version: '1.26.11-1' },
161
+ '1.27.4': { name: '@threadedstack/wmd-gowasm', version: '1.27.4-1' },
162
+ }
@@ -0,0 +1,167 @@
1
+ // X6 default part 2, item H, and part 3: the Go compiler's Wasm twin for a page that embeds the package. bootWmd does the whole setup alone
2
+ // (src/gowasm/boot-setup.js, twinForBoot, which uses planOf below); an embedder writes no twin line. This module is also the entry of the test page
3
+ // (page/ckpt.js, gowasmSetup) and holds what both share:
4
+ // planOf({ sources, pins, packages, limits }) the table made in memory from the pins (src/gowasm/pins-data.js, a JS module: no request) and the
5
+ // ordered sources (src/host/pinned-fetch.js: tgz of the npm registry, file under a base, url)
6
+ // tableFromPins(pins, packages, sources) the table
7
+ // GOWASM_SOURCES_DEFAULT ONE constant: the sources used when the embedder names none (the registry, jsDelivr, unpkg)
8
+ // The twin's module is fetched by the twin's Worker on first use from the first source that gives the pinned sha256, and kept in Cache Storage.
9
+ // `gowasmSetup({ table: '/own/tools.json' })` is the override that reads a table an app serves itself, with its own modules.
10
+ // The module imports the table's guard and the pins alone, none of the twin's machine code (edge-go.js, its error texts, yamux): the twin's code is
11
+ // loaded by the channel service's Worker, only for a machine that got a `gowasm` service field. It never throws into its caller.
12
+ import { loadToolsTable, normalizeTable, toolsTableProblem } from '../host/gowasm-guard.js'
13
+ import { PACKAGES, PINS } from './pins-data.js'
14
+
15
+ /**
16
+ * The sources the twin's modules are fetched from when the embedder names none: ONE constant, the ordered list, the npm registry first (CORS open, the
17
+ * official place), then two CDNs of the same package (jsDelivr refuses files over 50 MB, so it is a second place for the twin and not for X5's big files).
18
+ * An embedder that passes `gowasm: false` has the twin off. Only the pins (pins-data.js PACKAGES) say which package and version.
19
+ */
20
+ export const GOWASM_SOURCES_DEFAULT = [
21
+ { kind: 'tgz', url: 'https://registry.npmjs.org/{name}/-/{file}-{version}.tgz' },
22
+ { kind: 'file', base: 'https://cdn.jsdelivr.net/npm/{name}@{version}' },
23
+ { kind: 'file', base: 'https://unpkg.com/{name}@{version}' },
24
+ ]
25
+
26
+ /** Why a list of sources cannot be used, or null. A list is [{kind: 'tgz', url} | {kind: 'file', base} | {kind: 'url', url}]; https and http only. */
27
+ export function sourcesProblem(sources) {
28
+ if (!Array.isArray(sources) || !sources.length) return 'the list of sources is empty or is not a list'
29
+ for (const x of sources) {
30
+ const text = x && x.kind === 'file' ? x.base : x && (x.kind === 'tgz' || x.kind === 'url') ? x.url : undefined
31
+ if (typeof text !== 'string' || !text) return `a source is not {kind: 'tgz'|'url', url} or {kind: 'file', base}: ${JSON.stringify(x)?.slice(0, 80)}`
32
+ if (!/^https?:\/\//i.test(text)) return `a source is not an http(s) url: ${text.slice(0, 80)}`
33
+ }
34
+ return null
35
+ }
36
+
37
+ /**
38
+ * The table the page used to read from tools.json, made in memory from the pins: the guest compile's sha256 (the key) -> its name, path and architecture,
39
+ * and the twin of its release: its file name, sha256 and size (the size bounds the fetch) and, when `packages` names one for the release, the npm package
40
+ * that holds it ({name, version}). `sources` is the ordered list the Worker tries (src/host/pinned-fetch.js).
41
+ */
42
+ export function tableFromPins(pins, packages, sources) {
43
+ const tools = {}
44
+ for (const [ver, rel] of Object.entries(pins.releases)) {
45
+ const pkg = packages && packages[ver] ? { name: packages[ver].name, version: packages[ver].version } : undefined
46
+ for (const [sha, t] of Object.entries(rel.tools)) {
47
+ tools[sha] = { name: t.name, path: t.path, arch: t.arch, goVersion: t.goVersion, wasmUrl: rel.twin.file, wasmPath: rel.twin.file, wasmSha256: rel.twin.sha256, wasmSize: rel.twin.size, ...(pkg ? { wasmPkg: pkg } : {}) }
48
+ }
49
+ }
50
+ return { tools, sources }
51
+ }
52
+
53
+ /** The pins are the pins of the twin: releases, each with a twin file and its tools. */
54
+ const pinsProblem = p => {
55
+ const rels = p && typeof p === 'object' && p.releases && typeof p.releases === 'object' ? Object.values(p.releases) : []
56
+ if (!rels.length || !rels.every(x => x && x.twin && typeof x.twin.file === 'string' && /^[0-9a-f]{64}$/i.test(String(x.twin.sha256)) && x.tools && typeof x.tools === 'object')) return 'the pins have no releases of the twin'
57
+ return null
58
+ }
59
+
60
+ /**
61
+ * The plan from the pins and a list of sources, with no request: {table, edge, service(mounts)} or {why}.
62
+ * @param {{sources: object[], pins?: object, packages?: object, limits?: object}} o
63
+ */
64
+ export function planOf({ sources, pins = PINS, packages = PACKAGES, limits = {} }) {
65
+ const bad = sourcesProblem(sources)
66
+ if (bad) return { why: bad }
67
+ const pb = pinsProblem(pins)
68
+ if (pb) return { why: pb }
69
+ const table = tableFromPins(pins, packages, sources.map(x => ({ ...x })))
70
+ const tb = toolsTableProblem(table)
71
+ if (tb) return { why: `the table made from the pins ${tb}` }
72
+ return { table, edge: gowasmEdgeOf(table), service: mounts => gowasmServiceOf(table, limits, mounts) }
73
+ }
74
+
75
+ /** The time limit of the table's fetch when `limits.readyLimitMs` is not given: the machine's ready limit (READY_LIMIT_MS of src/host/edge-go.js, tested to be equal). */
76
+ export const TABLE_LIMIT_MS = 60_000
77
+
78
+ /** The limits an embedder may name (0 or absent: the twin's own default; the two flags off). */
79
+ export const GOWASM_LIMITS = { beatLimitMs: 0, readyLimitMs: 0, runLimitMs: 0, earlyReply: false, lateFallbackAt: 0 }
80
+
81
+ const defaultFetchJson = async (u, signal) => {
82
+ const r = await fetch(u, { cache: 'no-store', signal })
83
+ if (!r.ok) throw new Error(`GET ${u}: ${r.status}`)
84
+ return r.json()
85
+ }
86
+
87
+ /**
88
+ * The `gowasm` field of the 9P service (bootWmd channels.services[]): the table, the limits, and the destinations of every mount of the bundle.
89
+ * Each limit goes on under the name the GoEdge constructor takes (src/host/chan-service.js), 0 meaning its default.
90
+ */
91
+ export function gowasmServiceOf(table, limits, mounts) {
92
+ // one module for every tool (wasmUrl, wasmSha256 at the top) goes on as it always did; a module per tool goes on as a list of
93
+ // modules, the ones to load at start, and the tools with their own module (src/host/gowasm-guard.js normalizeTable)
94
+ const n = normalizeTable(table)
95
+ const l = { ...GOWASM_LIMITS, ...limits }
96
+ return {
97
+ ...(n.legacy ? { wasmUrl: table.wasmUrl, wasmSha256: table.wasmSha256 } : { modules: n.modules, preload: n.preload }),
98
+ beatLimitMs: Number(l.beatLimitMs) | 0,
99
+ readyLimitMs: Number(l.readyLimitMs) | 0,
100
+ runLimitMs: Number(l.runLimitMs) | 0,
101
+ tools: n.tools,
102
+ ...(table.sources ? { sources: table.sources } : {}),
103
+ cacheBytes: table.cacheBytes,
104
+ maxReruns: table.maxReruns,
105
+ earlyReply: l.earlyReply === true,
106
+ lateFallbackAt: Number(l.lateFallbackAt) | 0,
107
+ mounts,
108
+ }
109
+ }
110
+
111
+ /** The `edge` option of containerBundle: the stub stands in the container for each of the table's tools (one pair per place in the image). */
112
+ export const gowasmEdgeOf = table => {
113
+ const seen = new Set()
114
+ const tools = Object.values(table.tools).filter(t => {
115
+ const k = `${t.name} ${t.path}`
116
+ if (seen.has(k)) return false
117
+ seen.add(k)
118
+ return true
119
+ })
120
+ // sorted: the spec text (and so a checkpoint's boot key) follows the tools, not the order the pins list them in or which releases are pinned
121
+ tools.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
122
+ return { tools }
123
+ }
124
+
125
+ /**
126
+ * The entry of the test page (and of a caller that wants the plan itself).
127
+ * @param {object} o
128
+ * @param {string} [o.table] the url of a table (tools.json) the embedder serves itself, with the twin's modules: the override
129
+ * @param {object[]} [o.sources] the ordered sources (default GOWASM_SOURCES_DEFAULT); `base` is one file source
130
+ * @param {string} [o.base] one file source: <base>/<file>
131
+ * @param {boolean} [o.gowasm] false: off, asks for nothing
132
+ * @param {object} [o.limits] beatLimitMs, readyLimitMs (also the table's time limit, default 60000), runLimitMs, earlyReply, lateFallbackAt
133
+ * @param {function} [o.fetchJson] (url, signal) -> parsed JSON, for the table override only
134
+ * @param {function} [o.onEvent] ({t: 'gowasm-off', why, machine}) once, for a plan that is off for a reason the user should see
135
+ * @param {number} [o.machine] the machine's count, copied into the event
136
+ * @returns {Promise<{use: boolean, reason: string, edge: object|undefined, service: function|undefined, table: object|null}>}
137
+ */
138
+ export async function gowasmSetup(o = {}) {
139
+ const { table: url, base, sources: given, gowasm, limits = {}, fetchJson = defaultFetchJson, onEvent = () => {}, machine = 0, pins, packages } = o || {}
140
+ const off = (reason, say) => {
141
+ if (say) {
142
+ try {
143
+ onEvent({ t: 'gowasm-off', why: reason, machine })
144
+ } catch {
145
+ // a handler of the embedder must not decide the plan
146
+ }
147
+ }
148
+ return { use: false, reason, edge: undefined, service: undefined, table: null }
149
+ }
150
+ try {
151
+ if (gowasm === false) return off('the twin is switched off (gowasm: false)', false)
152
+ const sources = given ?? (base ? [{ kind: 'file', base }] : GOWASM_SOURCES_DEFAULT)
153
+ if (!url && !sources) return off('no table is stated: no table url and no sources were given, so none is asked for', true)
154
+ if (url) {
155
+ const r = await loadToolsTable({ fetchJson, url, limitMs: Number(limits.readyLimitMs) || TABLE_LIMIT_MS })
156
+ if (!r.table) return off(r.why, true)
157
+ const edge = gowasmEdgeOf(r.table)
158
+ gowasmServiceOf(r.table, limits, []) // a table that cannot be turned into a service field is found now, not at the boot
159
+ return { use: true, reason: '', edge, service: mounts => gowasmServiceOf(r.table, limits, mounts), table: r.table }
160
+ }
161
+ const plan = planOf({ sources, pins, packages, limits })
162
+ if (plan.why) return off(`the twin's setup is not usable: ${plan.why}`, true)
163
+ return { use: true, reason: '', edge: plan.edge, service: plan.service, table: plan.table }
164
+ } catch (e) {
165
+ return off(`the twin's setup failed: ${(e && e.message) || e}`, true)
166
+ }
167
+ }
@@ -0,0 +1,27 @@
1
+ // X6 default part 2, item H, now a thin user of src/host/pinned-fetch.js (part 3, item 2): one module at one url, the shape the first design had.
2
+ // fetchTwin never throws and never waits without a limit: {bytes, from: 'cache' | 'network'} or {error}. Kept for its tests and for a table that
3
+ // names a module by a url; the twin's Worker calls fetchPinned itself with the sources the pins give.
4
+ import { fetchPinned, MAX_PINNED_BYTES, PINNED_CACHE_NAME, PINNED_STALL_MS, PINNED_TOTAL_MS, pinnedCacheKey } from '../host/pinned-fetch.js'
5
+
6
+ export const TWIN_CACHE_NAME = PINNED_CACHE_NAME
7
+ /** The most a twin without a pinned size may be (the three pinned ones are about 41 to 53 MB). */
8
+ export const MAX_TWIN_BYTES = MAX_PINNED_BYTES
9
+ export const TWIN_TOTAL_MS = PINNED_TOTAL_MS
10
+ export const TWIN_STALL_MS = PINNED_STALL_MS
11
+ /** The Cache Storage key of a module: a url of the page's own origin that holds the sha256 (never fetched). */
12
+ export const twinCacheKey = pinnedCacheKey
13
+
14
+ /**
15
+ * @param {object} o
16
+ * @param {string} o.url the module's url (http or https; relative to the page is not accepted)
17
+ * @param {string} o.sha256 the pinned hash (64 hex digits)
18
+ * @param {number} [o.size] the pinned size in bytes
19
+ * @param {string[]} [o.schemes] the url schemes accepted (default https and http)
20
+ * @returns {Promise<{bytes: ArrayBuffer, from: string} | {error: string}>}
21
+ */
22
+ export async function fetchTwin(o) {
23
+ const { url, sha256, size, ...rest } = o || {}
24
+ const r = await fetchPinned({ ...rest, cacheKeyOf: rest.cacheKeyOf || twinCacheKey, files: [{ path: 'twin', sha256, size }], sources: [{ kind: 'url', url }] })
25
+ if (r.error) return { error: r.error }
26
+ return { bytes: r.files.twin, from: r.from.twin === 'cache' ? 'cache' : 'network' }
27
+ }
@@ -44,11 +44,15 @@
44
44
 
45
45
  import { H_DOORBELL, H_SVC, SVC_RUNNING, markServiceDead } from './chan.js'
46
46
  import { ChanHost } from './chan-services.js'
47
- import { EDGE_CONTAINER_DIR, EDGE_STUB } from './ctl.js'
48
47
  import { Pack, bytesSource } from '../fs/pack.js'
49
48
  import { Overlay } from '../fs/overlay.js'
50
49
  import { seedEntry } from '../fs/seed.js'
51
50
  import { exportUpper } from '../fs/upper-pack.js'
51
+ // The stub's two places, as in ctl.js (EDGE_CONTAINER_DIR, EDGE_STUB, which internal/engine/edge.go also names). Not imported: a Worker fetches each of
52
+ // its modules itself, and ctl.js (a large module the page has already) was one request more than a page without the twin made (X6 default part 2,
53
+ // item E; check 7's F4). web/test/unit/x6-def2.test.js says that these two are ctl.js's.
54
+ const EDGE_CONTAINER_DIR = '/dev/.wmd-edge'
55
+ const EDGE_STUB = '/sbin/wmd-edgestub'
52
56
  // X5 (edge=1 only): the edge modules are loaded by init() when the machine has `edge`, and by nothing else (check5 F8)
53
57
  let EdgePorts, EdgeService, EdgeHost, checkpointRefusal
54
58
 
@@ -153,10 +157,11 @@ self.onmessage = e => {
153
157
  case 'edge-fs': {
154
158
  // X5 (edge=1 only): node's file requests, answered between 9P requests
155
159
  if (!host) throw new Error('the channel service has not started')
156
- edge ||= new EdgePorts(host.fsFor(m.port9p), { mounts: m.mounts, root: m.root || '' })
160
+ edge ||= new EdgePorts(host.fsFor(m.port9p), { mounts: m.mounts, root: m.root || '', ringMax: m.ringMax })
161
+ if (m.ringMax > 0) edge.ringMax = Math.floor(m.ringMax) // every run says it: the routes it makes keep that many calls
157
162
  if (m.own) {
158
163
  // the own runtime's port (src/edge/own/): its file messages and its children (a raw stream to the stub of this run)
159
- for (const p of m.ports || []) edge.attachOwn(p, { run: m.run || 0, root: m.root || '', job: m.job || 0, openExec: id => edgeSvc.openExec(id), onTraffic: kick, kickAll: !!m.kickAll, onSignalTaken: (n, handled) => edgeSvc.post({ t: 'edge', ev: 'signal-taken', id: m.job || 0, n, handled }) })
164
+ for (const p of m.ports || []) edge.attachOwn(p, { run: m.run || 0, root: m.root || '', job: m.job || 0, openExec: id => edgeSvc.openExec(id), net: id => edgeSvc.netFor(id), onTraffic: kick, kickAll: !!m.kickAll, onSignalTaken: (n, handled) => edgeSvc.post({ t: 'edge', ev: 'signal-taken', id: m.job || 0, n, handled }) })
160
165
  } else {
161
166
  const route = edge.routeFor({ mounts: m.mounts, root: m.root || '' }) // this run's own table (see EdgePorts.routeFor)
162
167
  for (const p of m.ports || []) edge.attach(p, route, m.run || 0)
@@ -280,18 +285,26 @@ async function init(m) {
280
285
  const restore = {}
281
286
  for (const svc of m.services || []) if (svc.restore) restore[svc.port] = new Uint8Array(svc.restore)
282
287
  let edgeAccept = null
288
+ let edgeFlushedHook = null
283
289
  if (m.edge) {
284
290
  const [port, service, hosted] = await Promise.all([import('../edge/service-port.js'), import('../edge/service-host.js'), import('./edge-host.js')])
285
291
  ;({ EdgePorts } = port)
286
292
  ;({ EdgeService } = service)
287
293
  ;({ EdgeHost, checkpointRefusal } = hosted)
288
294
  // X5 (edge=1 only): streams the guest opens on the control session are node starts (src/host/edge-host.js)
289
- edgeSvc = new EdgeService({ fs: fs[m.edge.port9p], root: m.edge.root || '', rt: m.edge.rt || '', post: msg => self.postMessage(msg) })
295
+ edgeSvc = new EdgeService({ fs: fs[m.edge.port9p], root: m.edge.root || '', rt: m.edge.rt || '', post: msg => self.postMessage(msg), cleanOf: id => !!edge?.jobClean(id) })
290
296
  const eh = (edgeHost = new EdgeHost({ start: (h, ctx) => edgeSvc.start(h, ctx) }))
291
297
  edgeAccept = s => (eh.accept(s), kick())
298
+ edgeFlushedHook = t => eh.flushed(t)
292
299
  }
293
300
  // X6 (default off): the compiler hand-off, for the 9P service that has a gowasm table
294
301
  const goSvc = m.gowasmPort ? (m.services || []).find(s => s.gowasm && fs[s.port]) : null
302
+ // X6 part 3: a service that has a twin table and no twin Worker (the page could not start it): its stub mounts must not reach the guest
303
+ if (!m.gowasmPort) for (const s of m.services || []) if (s.gowasm && !s.gowasm.off && fs[s.port]) noTwin(fs[s.port], s.gowasm.tools, `no twin Worker: ${m.gowasmWhy || 'the page started none'}`)
304
+ // X6 default part 6: a machine restored from a checkpoint taken with the twin, in a boot that has the twin off (gowasm.off holds the reason, the page started no
305
+ // Worker): the stub mounts STAY (the guest's memory has them), a GoEdge is built that is off from the start, and it answers each stub with the fallback by the
306
+ // same guard (edge-go.js #serve) as a twin that went off during the machine's life. No prune, no port, nothing of the twin is fetched.
307
+ const offSvc = !m.gowasmPort ? (m.services || []).find(s => s.gowasm && s.gowasm.off && fs[s.port]) : null
295
308
  let goMod = null
296
309
  if (goSvc) {
297
310
  // X6 fix 4, item 6: loaded only for a machine with the switch on (a page without gowasm=1 asks for none of the twin's modules)
@@ -320,9 +333,23 @@ async function init(m) {
320
333
  mounts: goSvc.gowasm.mounts || null,
321
334
  })
322
335
  goEdge.pruneBundle() // an image with no Go compile: its stub mounts go out of the bundle before the guest starts the container
336
+ await goEdge.pruneUnpinned() // a Go release the pins do not name: its stubs go out too (the guest runs it alone), one calm event
323
337
  bindGoPort(m.gowasmPort)
324
338
  }
325
- host = new ChanHost(sab, { fs, consoleInputBytes: m.consoleInputBytes, yamuxPorts, netPost, restore, edge: goEdge, edgeAccept })
339
+ if (offSvc) {
340
+ twinOffWhy = offSvc.gowasm.off // the stats carry it as gowasmOff, as for noTwin
341
+ const loaded = await loadWithin(async () => await import('./edge-go.js'), offSvc.gowasm.readyLimitMs || IMPORT_LIMIT_MS, './edge-go.js')
342
+ if (loaded.mod) {
343
+ goEdge = new loaded.mod.GoEdge({ fs: fs[offSvc.port], root: offSvc.at || '', tools: offSvc.gowasm.tools, post: () => {}, onRecord: rec => self.postMessage({ t: 'gowasm', rec }), mounts: offSvc.gowasm.mounts || null, off: offSvc.gowasm.off })
344
+ // fix 10 (F1): the stub mounts of a tool the image does not hold go out of the spec before the guest reads it, as in the on branch: a cold machine of an image
345
+ // without Go (a base snapshot that was refused after its header) must not get a bind whose source is missing. A machine that really restored has the checkpoint's own tree
346
+ // (its spec was pruned the same way when it was taken), so this changes nothing there. pruneUnpinned (a hash of each tool) is not needed to start: a stub of an unpinned tool
347
+ // is answered with the fallback by the off GoEdge.
348
+ goEdge.pruneBundle()
349
+ }
350
+ // edge-go.js not loadable: no host for the stub, which then runs its own compile (the state of any restore without a twin before this part)
351
+ }
352
+ host = new ChanHost(sab, { fs, consoleInputBytes: m.consoleInputBytes, yamuxPorts, netPost, restore, edge: goEdge, edgeAccept, edgeFlushed: edgeFlushedHook })
326
353
  if (m.lockName && self.navigator?.locks?.request) {
327
354
  self.navigator.locks.request(m.lockName, () => {
328
355
  self.postMessage({ t: 'locked' })
@@ -399,7 +426,7 @@ function bindGoPort(p) {
399
426
 
400
427
  let twinOffWhy = null // fix 11 (F-N): why the twin's module did not load (noTwin), for the stats
401
428
  let lastStats = ''
402
- const withSpin = s => ({ ...s, spin: { ...spin, curUs: spinCur }, ...(twinOffWhy ? { gowasmOff: twinOffWhy } : {}), ...(edgeHost ? { edge: { ...edgeHost.stats, fallbackWhy: { ...edgeHost.stats.fallbackWhy }, look: { ...edgeSvc.stats }, route: edge ? (({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes }) => ({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes }))(edge.stats()) : null } } : {}) })
429
+ const withSpin = s => ({ ...s, spin: { ...spin, curUs: spinCur }, ...(twinOffWhy ? { gowasmOff: twinOffWhy } : {}), ...(edgeHost ? { edge: { ...edgeHost.stats, fallbackWhy: { ...edgeHost.stats.fallbackWhy }, look: { ...edgeSvc.stats }, route: edge ? (({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes, net, ownCalls }) => ({ runs, ports, released, handles, requests, bad, children, ring, wait, waitByMethod, serdes, net, ownCalls }))(edge.stats()) : null } } : {}) })
403
430
  let lastStatsAt = 0
404
431
  function maybePostStats() {
405
432
  const t = nowMs()
@@ -30,7 +30,7 @@
30
30
  import {
31
31
  CHAN_CONSOLE, CHAN_CONTROL, CHAN_NET, CHAN_P9, CONSOLE_IN_LIMIT, G2H, H2G, H_CIN_TAKEN, H_CLOSES, H_GONE, H_P9COUNT, KIND_NAMES, P9C_LOWER,
32
32
  P9C_NONE, P9C_UPPER, R_GONE, R_SHUT, RTT_BUCKETS, S_GEN, S_PORT, S_STATE, ST_CLOSING, ST_FREE, ST_OPEN, chanPorts, chanView, histSummary,
33
- p9cServed, ringAvail, ringKick, ringRead, ringSpace, ringWrite, rttBucket, stageNote,
33
+ p9cServed, ringAvail, ringBell, ringKick, ringRead, ringSpace, ringWrite, rttBucket, stageNote,
34
34
  } from './chan.js'
35
35
  import { NinePServer } from '../fs/9p/server.js'
36
36
  import { adoptServer, dumpService, loadService } from '../fs/svc-snapshot.js'
@@ -295,7 +295,7 @@ class ControlSession {
295
295
  ctl.epoch++
296
296
  this.epoch = ctl.epoch
297
297
  this.yamux = new YamuxClient({
298
- send: u8 => sess.out.push(u8),
298
+ send: u8 => (sess.out.push(u8), host.queuedOut()),
299
299
  keepAliveMs: host.ctlKeepAliveMs,
300
300
  onClose: why => host.ctlSessionDown(this, why),
301
301
  // streams the guest init opens ({"op":"edge"}): X6's compiler hand-off (default off) and X5's node host (edge=1 only)
@@ -417,7 +417,7 @@ export class ChanHost {
417
417
  * @param {number} [o.consoleInputBytes] console input (page -> guest) held at most (CONSOLE_IN_LIMIT)
418
418
  * @param {{accept: (s: object) => void, snapshot: () => object}} [o.edge] X6: takes the streams the guest opens on the control session (edge-go.js GoEdge)
419
419
  */
420
- constructor(sab, { fs = {}, onConsole, consoleInputBytes = CONSOLE_IN_LIMIT, yamuxPorts = [], ctlKeepAliveMs = 5000, netPost = null, restore = {}, edge = null, edgeAccept = null } = {}) {
420
+ constructor(sab, { fs = {}, onConsole, consoleInputBytes = CONSOLE_IN_LIMIT, yamuxPorts = [], ctlKeepAliveMs = 5000, netPost = null, restore = {}, edge = null, edgeAccept = null, edgeFlushed = null } = {}) {
421
421
  this.v = chanView(sab)
422
422
  this.edge = edge
423
423
  // P-B10: the network Worker (postMessage to it), and the net channel's session
@@ -431,6 +431,7 @@ export class ChanHost {
431
431
  this.restoredServers.set(Number(port), loadService(bytes, fs[port]))
432
432
  }
433
433
  this.yamuxPorts = new Set(yamuxPorts)
434
+ this.edgeFlushed = edgeFlushed // X25 gate 2e: called with the page's clock when a flush of the control session put bytes into the guest's ring (edge-host.js flushed)
434
435
  this.edgeAccept = edgeAccept // X5 (edge=1 only): called with each stream the guest opens on the control session; none: refused
435
436
  this.ctlKeepAliveMs = ctlKeepAliveMs
436
437
  // P-B11: the control session and the page's streams on it (k -> YamuxStream)
@@ -451,6 +452,17 @@ export class ChanHost {
451
452
  errors: [],
452
453
  }
453
454
  this.stopped = false
455
+ this.stepping = false // inside step(): what is queued for the guest is flushed by this step
456
+ }
457
+
458
+ /**
459
+ * Bytes were queued for the guest. Inside a step the step flushes them. Outside one (a promise job: the edge host's answer to a
460
+ * stub's hello after its owner decided, X5 B2.3) nothing would take them to the guest until the guest next rang the doorbell or the
461
+ * service's 500 ms wait ran out (chan-service.js loop()), and the guest waited idle for them: ring the doorbell, so the service's
462
+ * next step sends them.
463
+ */
464
+ queuedOut() {
465
+ if (!this.stepping) ringBell(this.v)
454
466
  }
455
467
 
456
468
  /** Queue an event for the page (chan-service.js posts ctlEvents after each step). */
@@ -677,6 +689,15 @@ export class ChanHost {
677
689
 
678
690
  /** One pass over every channel. Returns true if anything moved. */
679
691
  step() {
692
+ this.stepping = true
693
+ try {
694
+ return this.#step()
695
+ } finally {
696
+ this.stepping = false
697
+ }
698
+ }
699
+
700
+ #step() {
680
701
  const v = this.v
681
702
  const i32 = v.i32
682
703
  if (Atomics.load(i32, H_GONE)) {
@@ -736,13 +757,16 @@ export class ChanHost {
736
757
  sess.impl.tick?.()
737
758
  const before = sess.out.bytes
738
759
  let wrote = sess.out.flush(v, h)
760
+ if (wrote && sess.kind === CHAN_CONTROL) this.edgeFlushed?.()
739
761
  if (sess.kind === CHAN_CONSOLE && wrote) Atomics.add(v.i32, H_CIN_TAKEN, wrote) // console input taken by the ring
740
762
  if (!sess.broken && sess.impl.pending() && sess.out.bytes < OUT_LIMIT) {
741
763
  // requests held back while the replies were not read
742
764
  const n = sess.impl.pending()
743
765
  sess.impl.process(sess)
744
766
  if (sess.impl.pending() !== n) work = true
745
- wrote += sess.out.flush(v, h)
767
+ const w1 = sess.out.flush(v, h)
768
+ if (w1 && sess.kind === CHAN_CONTROL) this.edgeFlushed?.()
769
+ wrote += w1
746
770
  }
747
771
  if (wrote) {
748
772
  ks.bytesOut += wrote
@@ -764,6 +788,7 @@ export class ChanHost {
764
788
  work = true
765
789
  sess.impl.data(sess, this.inbuf.subarray(0, n))
766
790
  const w2 = sess.out.flush(v, h)
791
+ if (w2 && sess.kind === CHAN_CONTROL) this.edgeFlushed?.()
767
792
  if (sess.kind === CHAN_CONSOLE && w2) Atomics.add(v.i32, H_CIN_TAKEN, w2)
768
793
  ks.bytesOut += w2
769
794
  }