@threadedstack/wmd-web 0.1.38 → 0.1.39
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 +4 -2
- package/RELEASE.json +26 -17
- 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 +93 -11
- 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 +164 -0
- package/src/gowasm/twin-fetch.js +27 -0
- package/src/host/chan-service.js +25 -1
- 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/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/host/ctl.js
CHANGED
|
@@ -765,6 +765,35 @@ function defaultMounts() {
|
|
|
765
765
|
]
|
|
766
766
|
}
|
|
767
767
|
|
|
768
|
+
/**
|
|
769
|
+
* X6: the mounts that put the guest's edge stub over each tool of `tools` ({name, path}): the stub folder (once: with the page switch edge=1 and the twin together X5's
|
|
770
|
+
* mounts already have it), the real binary bound into it, and the stub over the tool's own path. Returns a new list; a mount that is already there (the same
|
|
771
|
+
* destination and source) is not added again, so adding twice changes nothing. They go after the bundle's /etc files, where containerBundle puts them, and
|
|
772
|
+
* before the caller's volumes. The twin's setup in bootWmd (src/gowasm/boot-setup.js) calls this with the spec read from the 9P service's files.
|
|
773
|
+
*/
|
|
774
|
+
export function addEdgeToolMounts(mounts, tools) {
|
|
775
|
+
const out = [...mounts]
|
|
776
|
+
let at = out.length
|
|
777
|
+
for (let i = out.length - 1; i >= 0; i--) {
|
|
778
|
+
if (typeof out[i].source === 'string' && out[i].source.startsWith(`${GUEST_9P_MOUNT}/bundle/etc/`)) {
|
|
779
|
+
at = i + 1
|
|
780
|
+
break
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const add = []
|
|
784
|
+
const has = m => out.some(x => x.destination === m.destination && x.source === m.source) || add.some(x => x.destination === m.destination && x.source === m.source)
|
|
785
|
+
const put = m => {
|
|
786
|
+
if (!has(m)) add.push(m)
|
|
787
|
+
}
|
|
788
|
+
if (!out.some(m => m.destination === EDGE_CONTAINER_DIR)) put({ destination: EDGE_CONTAINER_DIR, type: 'bind', source: EDGE_GUEST_DIR, options: ['rbind', 'rw'] })
|
|
789
|
+
for (const t of tools) {
|
|
790
|
+
put({ destination: `${EDGE_CONTAINER_DIR}/${t.name}`, type: 'bind', source: `${GUEST_9P_MOUNT}/rootfs${t.path}`, options: ['bind', 'ro'] })
|
|
791
|
+
put({ destination: t.path, type: 'bind', source: EDGE_STUB, options: ['bind', 'ro'] })
|
|
792
|
+
}
|
|
793
|
+
out.splice(at, 0, ...add)
|
|
794
|
+
return out
|
|
795
|
+
}
|
|
796
|
+
|
|
768
797
|
/**
|
|
769
798
|
* The 9P tree's files for a container (paths relative to the share root, beside the
|
|
770
799
|
* rootfs/ the packs give): bundle/config/config.json, bundle/config/imageconfig.json,
|
|
@@ -838,14 +867,7 @@ export function containerBundle(o) {
|
|
|
838
867
|
for (const name of ETC_FILES) {
|
|
839
868
|
spec.mounts.push({ destination: `/etc/${name}`, type: 'bind', source: `${GUEST_9P_MOUNT}/bundle/etc/${name}`, options: ['rbind', 'rprivate', 'rw'] })
|
|
840
869
|
}
|
|
841
|
-
if (o.edge?.tools?.length)
|
|
842
|
-
// the stub folder once: with edge=1 and gowasm=1 together X5's mounts above already have it
|
|
843
|
-
if (!spec.mounts.some(m => m.destination === EDGE_CONTAINER_DIR)) spec.mounts.push({ destination: EDGE_CONTAINER_DIR, type: 'bind', source: EDGE_GUEST_DIR, options: ['rbind', 'rw'] })
|
|
844
|
-
for (const t of o.edge.tools) {
|
|
845
|
-
spec.mounts.push({ destination: `${EDGE_CONTAINER_DIR}/${t.name}`, type: 'bind', source: `${GUEST_9P_MOUNT}/rootfs${t.path}`, options: ['bind', 'ro'] })
|
|
846
|
-
spec.mounts.push({ destination: t.path, type: 'bind', source: EDGE_STUB, options: ['bind', 'ro'] })
|
|
847
|
-
}
|
|
848
|
-
}
|
|
870
|
+
if (o.edge?.tools?.length) spec.mounts = addEdgeToolMounts(spec.mounts, o.edge.tools)
|
|
849
871
|
const files = {}
|
|
850
872
|
;(o.mounts || []).forEach((m, i) => {
|
|
851
873
|
const share = `vol${i}`
|
package/src/host/edge-go.js
CHANGED
|
@@ -277,7 +277,7 @@ export function mountPoints(list) {
|
|
|
277
277
|
* early, run, and then sent to the guest by a late fallback frame without writing its outputs. Needs a stub that says late_fallback.
|
|
278
278
|
*/
|
|
279
279
|
export class GoEdge {
|
|
280
|
-
constructor({ fs, root = 'rootfs', tools, post, restart = null, stop = null, onRecord = null, onEvent = null, now = () => performance.now(), maxReruns = 2, maxInputBytes = 256 << 20, earlyReply = false, lateFallbackAt = 0, mounts = null, beatLimitMs = BEAT_LIMIT_MS, readyLimitMs = READY_LIMIT_MS, runLimitMs = RUN_LIMIT_MS }) {
|
|
280
|
+
constructor({ fs, root = 'rootfs', tools, post, restart = null, stop = null, onRecord = null, onEvent = null, now = () => performance.now(), maxReruns = 2, maxInputBytes = 256 << 20, earlyReply = false, lateFallbackAt = 0, mounts = null, beatLimitMs = BEAT_LIMIT_MS, readyLimitMs = READY_LIMIT_MS, runLimitMs = RUN_LIMIT_MS, off = '' }) {
|
|
281
281
|
this.mounts = mounts ? mountPoints(mounts.filter(m => m)) : null
|
|
282
282
|
this.earlyReply = earlyReply
|
|
283
283
|
this.lateFallbackAt = lateFallbackAt
|
|
@@ -297,6 +297,13 @@ export class GoEdge {
|
|
|
297
297
|
this.ruleWhy = {} // rule -> the reason text of the first time
|
|
298
298
|
this.offWhy = null // fix 11 (F-N): the reason it is off, once it is
|
|
299
299
|
this.off = false // turned off for the machine (FAIL_LIMIT failures in a row, or a module that is not the one tools.json names)
|
|
300
|
+
// X6 default part 6: off from the start. A machine restored from a checkpoint taken with the twin, in a boot that has the twin off: the stub mounts are in the
|
|
301
|
+
// guest's memory, no twin Worker exists, and the stub is answered by the very guard a twin that went off during the machine's life meets (#serve: the compile
|
|
302
|
+
// goes back to the guest as a fallback). The page said why once when it chose, so no event is raised here.
|
|
303
|
+
if (off) {
|
|
304
|
+
this.off = true
|
|
305
|
+
this.offWhy = String(off)
|
|
306
|
+
}
|
|
300
307
|
this.lastBeat = 0
|
|
301
308
|
this.watch = null // the timer of the watchdog, there while a run is out or the Worker has not said ready
|
|
302
309
|
this.readyBy = now() + readyLimitMs // the Worker must say ready by then
|
|
@@ -305,11 +312,13 @@ export class GoEdge {
|
|
|
305
312
|
this.maxReruns = maxReruns
|
|
306
313
|
this.maxInputBytes = maxInputBytes
|
|
307
314
|
this.known = new Map() // tool path -> {key, res}
|
|
315
|
+
this.loadingFor = new Map() // X6 default part 5: module key (the run's `module`, '' for the first) -> the Worker's sha256, while that module is still loading
|
|
316
|
+
this.loadInfo = null // the last {t:'loaded'} the Worker sent (bytes, fetchMs, compileMs)
|
|
308
317
|
this.sent = new Map() // path -> key: what the twin holds (its cache, as it last said)
|
|
309
318
|
this.queue = []
|
|
310
319
|
this.busy = null
|
|
311
320
|
this.ready = false
|
|
312
|
-
this.dead =
|
|
321
|
+
this.dead = !!off
|
|
313
322
|
this.open = new Set() // jobs whose stub is waiting for an answer (a checkpoint must not be taken meanwhile)
|
|
314
323
|
this.jobs = new Set() // jobs whose stub has said hello and whose stream is not closed yet
|
|
315
324
|
this.live = new Set() // the guest init's streams for stubs that are connected (from the request line until the stub is gone)
|
|
@@ -629,10 +638,59 @@ export class GoEdge {
|
|
|
629
638
|
}
|
|
630
639
|
}
|
|
631
640
|
if (!dropped) return { kept, dropped }
|
|
641
|
+
this.#cut(spec, file, drop, dropReal, kept)
|
|
642
|
+
return { kept, dropped }
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** Takes the stub mounts of the paths in `drop` (and the real binaries' mounts in `dropReal`) out of the spec and writes it back. */
|
|
646
|
+
#cut(spec, file, drop, dropReal, kept) {
|
|
632
647
|
spec.mounts = spec.mounts.filter(m => !drop.has(m.destination) && !dropReal.some(d => d.dest === m.destination && typeof m.source === 'string' && m.source.endsWith(d.src)))
|
|
633
648
|
// the stub folder goes with the last thing in it. Another stub may live there: with the page switch edge=1 (X5) the image's node does
|
|
634
649
|
if (!kept && !spec.mounts.some(m => typeof m.destination === 'string' && m.destination.startsWith(`${EDGE_DIR}/`))) spec.mounts = spec.mounts.filter(m => m.destination !== EDGE_DIR)
|
|
635
650
|
this.fs.writeFile(file, JSON.stringify(spec, null, 2) + '\n')
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* X6 default part 3: the second half of the image deciding. pruneBundle takes out the stubs of tools the image does not have; this takes out
|
|
656
|
+
* those of tools it has that are no tool the twin stands for (a Go release the pins do not name, an architecture they do not carry): such a
|
|
657
|
+
* compile would be handed to the page and given back to the guest at every run, so the guest is left to run it alone from the start, and
|
|
658
|
+
* ONE calm event (rule `unpinned`) says why. The file is hashed here, once, instead of at the first compile (the answer is kept, #recognize
|
|
659
|
+
* reads the same cache). A file that cannot be read or hashed keeps its mounts: only a hash that is no known tool drops them. Awaited by
|
|
660
|
+
* the channel service before the guest reads the spec.
|
|
661
|
+
*/
|
|
662
|
+
async pruneUnpinned() {
|
|
663
|
+
const file = 'bundle/config/config.json'
|
|
664
|
+
let spec
|
|
665
|
+
try {
|
|
666
|
+
spec = JSON.parse(new TextDecoder().decode(this.fs.readFile(file)))
|
|
667
|
+
} catch {
|
|
668
|
+
return { kept: 0, dropped: 0 }
|
|
669
|
+
}
|
|
670
|
+
if (!spec || !Array.isArray(spec.mounts)) return { kept: 0, dropped: 0 }
|
|
671
|
+
let kept = 0
|
|
672
|
+
let dropped = 0
|
|
673
|
+
const drop = new Set()
|
|
674
|
+
const dropReal = []
|
|
675
|
+
const seen = new Set()
|
|
676
|
+
let why = ''
|
|
677
|
+
for (const t of Object.values(this.tools)) {
|
|
678
|
+
if (!t || typeof t.path !== 'string' || !spec.mounts.some(m => m.destination === t.path) || seen.has(t.path)) continue
|
|
679
|
+
seen.add(t.path)
|
|
680
|
+
let res = null
|
|
681
|
+
try {
|
|
682
|
+
res = await this.#recognize(t.path)
|
|
683
|
+
} catch {}
|
|
684
|
+
if (res && res.unpinned) {
|
|
685
|
+
dropped++
|
|
686
|
+
drop.add(t.path)
|
|
687
|
+
dropReal.push({ dest: `${EDGE_DIR}/${t.name}`, src: `rootfs${t.path}` })
|
|
688
|
+
why = why || res.fallback
|
|
689
|
+
} else kept++
|
|
690
|
+
}
|
|
691
|
+
if (!dropped) return { kept, dropped }
|
|
692
|
+
this.#cut(spec, file, drop, dropReal, kept)
|
|
693
|
+
this.#note('unpinned', why)
|
|
636
694
|
return { kept, dropped }
|
|
637
695
|
}
|
|
638
696
|
|
|
@@ -654,7 +712,7 @@ export class GoEdge {
|
|
|
654
712
|
// a copy: the bytes may sit in shared memory, which digest refuses
|
|
655
713
|
const sha = hex(await crypto.subtle.digest('SHA-256', this.fs.read(r.node, 0, a.size).slice()))
|
|
656
714
|
const t = this.tools[sha]
|
|
657
|
-
const res = t ? { ok: true, name: t.name, sha256: sha, arch: toolArch(t), module: t.wasmSha256 } : { fallback: `${path}: sha256 ${sha.slice(0, 12)} is not a tool the twin stands for
|
|
715
|
+
const res = t ? { ok: true, name: t.name, sha256: sha, arch: toolArch(t), module: t.wasmSha256 } : { fallback: `${path}: sha256 ${sha.slice(0, 12)} is not a tool the twin stands for`, unpinned: true }
|
|
658
716
|
this.known.set(path, { key, res })
|
|
659
717
|
return res
|
|
660
718
|
}
|
|
@@ -854,7 +912,11 @@ export class GoEdge {
|
|
|
854
912
|
async #serveChecked(job, h, parsed, rec, ctx) {
|
|
855
913
|
const tool = await this.#recognize(h.argv[0])
|
|
856
914
|
if (job.done) return
|
|
857
|
-
if (!tool.ok)
|
|
915
|
+
if (!tool.ok) {
|
|
916
|
+
// X6 part 3: a compile the pins do not know (a Go release with no pin): the image is fine, the twin simply has no module for it. One calm event, once
|
|
917
|
+
if (tool.unpinned) this.#note('unpinned', tool.fallback)
|
|
918
|
+
return this.#toGuest(job, tool.fallback)
|
|
919
|
+
}
|
|
858
920
|
rec.tool = tool.name
|
|
859
921
|
|
|
860
922
|
const cwd = h.cwd || '/'
|
|
@@ -916,8 +978,11 @@ export class GoEdge {
|
|
|
916
978
|
}
|
|
917
979
|
let reruns = 0
|
|
918
980
|
for (;;) {
|
|
981
|
+
// X6 default part 5: the module is still loading (the Worker said so): nothing is posted, the guest compiles
|
|
982
|
+
if (this.loadingFor.has(tool.module ?? '')) return this.#toGuest(job, 'the twin is still loading', { reruns })
|
|
919
983
|
const r = await this.#toTwin(job, { argv: h.argv, env, cwd, want, rec, ctx, module: tool.module })
|
|
920
984
|
if (job.done || job.cancelled) return
|
|
985
|
+
if (r.loading) return this.#toGuest(job, 'the twin is still loading', { reruns })
|
|
921
986
|
if (r.infra) return this.#toGuest(job, r.infra, { reruns })
|
|
922
987
|
// a file the compile looked for and the container has: send it and run again (a fresh instance)
|
|
923
988
|
const asked = []
|
|
@@ -1052,6 +1117,14 @@ export class GoEdge {
|
|
|
1052
1117
|
this.dead = false
|
|
1053
1118
|
this.readyInfo = m
|
|
1054
1119
|
this.#pump()
|
|
1120
|
+
} else if (m.t === 'loading') {
|
|
1121
|
+
// X6 default part 5: the Worker is downloading the module: that is life for a run that waits for it
|
|
1122
|
+
if (this.busy) this.lastBeat = this.now()
|
|
1123
|
+
this.loadBytes = m.bytes
|
|
1124
|
+
} else if (m.t === 'loaded') {
|
|
1125
|
+
for (const [k, v] of [...this.loadingFor]) if (v === m.sha) this.loadingFor.delete(k)
|
|
1126
|
+
this.loadInfo = { sha: m.sha, wasmBytes: m.wasmBytes, fetchMs: m.fetchMs, compileMs: m.compileMs }
|
|
1127
|
+
this.onEvent?.({ t: 'gowasm-loaded', sha: String(m.sha).slice(0, 12), wasmBytes: m.wasmBytes, fetchMs: Math.round(m.fetchMs || 0), compileMs: Math.round(m.compileMs || 0) }) // calm: the numbers of the load
|
|
1055
1128
|
} else if (m.t === 'beat') {
|
|
1056
1129
|
const q = this.busy
|
|
1057
1130
|
if (!q || q.id !== m.id) return // a beat of a run that was cancelled
|
|
@@ -1074,6 +1147,20 @@ export class GoEdge {
|
|
|
1074
1147
|
this.sent.clear()
|
|
1075
1148
|
for (const [p, k] of m.held) this.sent.set(p, k)
|
|
1076
1149
|
}
|
|
1150
|
+
if (m.loading) {
|
|
1151
|
+
// X6 default part 5: the module is still loading. Not a failure (nothing is counted, nothing restarts): this compile and every one queued behind it
|
|
1152
|
+
// for the same module go to the guest, and so does every later one until the Worker says `loaded`
|
|
1153
|
+
const k = q.module ?? ''
|
|
1154
|
+
this.loadingFor.set(k, m.module)
|
|
1155
|
+
q.resolve({ loading: true })
|
|
1156
|
+
for (const w of this.queue.filter(x => (x.module ?? '') === k)) {
|
|
1157
|
+
this.queue.splice(this.queue.indexOf(w), 1)
|
|
1158
|
+
w.job.queued = false
|
|
1159
|
+
w.resolve({ loading: true })
|
|
1160
|
+
}
|
|
1161
|
+
this.#pump()
|
|
1162
|
+
return
|
|
1163
|
+
}
|
|
1077
1164
|
if (!m.infra) this.failures = 0 // a compile the twin ran to its end: the failures before it no longer count
|
|
1078
1165
|
q.resolve(m.infra ? { infra: m.infra } : m)
|
|
1079
1166
|
this.#pump()
|
|
@@ -1098,6 +1185,7 @@ export class GoEdge {
|
|
|
1098
1185
|
this.ready = false
|
|
1099
1186
|
this.dead = true
|
|
1100
1187
|
this.sent.clear()
|
|
1188
|
+
this.loadingFor.clear() // the Worker is replaced: its download goes with it
|
|
1101
1189
|
const q = this.busy
|
|
1102
1190
|
this.busy = null
|
|
1103
1191
|
if (q) {
|
|
@@ -1118,6 +1206,7 @@ export class GoEdge {
|
|
|
1118
1206
|
#turnOff(why) {
|
|
1119
1207
|
if (this.off) return
|
|
1120
1208
|
this.off = true
|
|
1209
|
+
this.loadingFor.clear()
|
|
1121
1210
|
this.offWhy = why // fix 11 (F-N): the counters say why, not only the event
|
|
1122
1211
|
this.ready = false
|
|
1123
1212
|
this.dead = true
|
|
@@ -1143,6 +1232,7 @@ export class GoEdge {
|
|
|
1143
1232
|
this.dead = false
|
|
1144
1233
|
this.ready = false
|
|
1145
1234
|
this.sent.clear()
|
|
1235
|
+
this.loadingFor.clear()
|
|
1146
1236
|
this.readyBy = this.now() + this.readyLimitMs
|
|
1147
1237
|
this.#arm()
|
|
1148
1238
|
}
|
package/src/host/gowasm-guard.js
CHANGED
|
@@ -90,7 +90,7 @@ export function normalizeTable(t) {
|
|
|
90
90
|
for (const [k, x] of entries) {
|
|
91
91
|
const url = x.wasmUrl ?? t.wasmUrl
|
|
92
92
|
const sha256 = (x.wasmSha256 ?? t.wasmSha256).toLowerCase()
|
|
93
|
-
if (!modules.has(sha256)) modules.set(sha256, { url, sha256 })
|
|
93
|
+
if (!modules.has(sha256)) modules.set(sha256, { url, sha256, ...(Number.isInteger(x.wasmSize) && x.wasmSize > 0 ? { size: x.wasmSize } : {}), ...(typeof x.wasmPath === 'string' && x.wasmPath ? { path: x.wasmPath } : {}), ...(x.wasmPkg && typeof x.wasmPkg === 'object' ? { pkg: x.wasmPkg } : {}) })
|
|
94
94
|
tools[k.toLowerCase()] = { ...x, wasmUrl: url, wasmSha256: sha256 }
|
|
95
95
|
}
|
|
96
96
|
return { legacy: false, modules: [...modules.values()], preload: modules.size === 1 ? [...modules.keys()] : [], tools }
|
|
@@ -160,3 +160,13 @@ export function makeBeat({ post, id, intervalMs = 200, now = () => performance.n
|
|
|
160
160
|
stats: () => ({ beats, calls, maxCallGapMs }),
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* X6 default part 5: the longest a compile waits for the twin's module to be loaded (ms). Past it the compile goes to the guest (a calm answer, not a failure) and
|
|
166
|
+
* the download goes on in the background. 10 s, from counted runs on a fast local link (docs/research/browser-speed-2026-11/x6/default1/part5/part5.md): the
|
|
167
|
+
* 41.1 MB module took 93 to 396 ms to fetch and 19 to 232 ms to compile in the three browsers, so 10 s is more than 15 times the slowest of those and also
|
|
168
|
+
* covers a link of about 4.1 MB/s (33 Mbit/s); a slower link costs a build this wait ONCE (every other compile queued behind it is answered at once, later ones go
|
|
169
|
+
* to the guest without being posted), against a guest-alone build of 245 to 560 s in the same runs, so at most about 4 %. It stays far below the heartbeat
|
|
170
|
+
* limit (the Worker beats while it waits).
|
|
171
|
+
*/
|
|
172
|
+
export const TWIN_WAIT_MS = 10_000
|
|
@@ -17,12 +17,19 @@
|
|
|
17
17
|
// Paths are the container's absolute paths; in the in-memory file system they have no leading slash (the one
|
|
18
18
|
// preopen is "/"). The inputs are kept between runs (the same archives are read by many compiles), at most cacheBytes.
|
|
19
19
|
import { MemFs, runWasi } from '../registry/wasi-mem.js'
|
|
20
|
-
import { makeBeat, verifyModule } from './gowasm-guard.js'
|
|
20
|
+
import { TWIN_WAIT_MS, makeBeat, verifyModule } from './gowasm-guard.js'
|
|
21
|
+
import { fetchPinned } from './pinned-fetch.js'
|
|
22
|
+
import { cspWatch } from './csp-reason.js'
|
|
21
23
|
|
|
22
24
|
const modules = new Map() // sha256 (lower case) -> {url, module?: WebAssembly.Module, bad?: string}
|
|
25
|
+
let globalSources = null // the ordered sources the page gave (pinned-fetch.js); none: each module's own url
|
|
23
26
|
let firstModule = null // the sha256 of the module a run that names none uses
|
|
24
27
|
let cacheCap = 192 << 20
|
|
25
28
|
let beatMs = 200
|
|
29
|
+
let waitMs = TWIN_WAIT_MS // the longest a run waits for a module that is not loaded (X6 default part 5); past it the run is answered `loading`
|
|
30
|
+
let fetchKnobs = {} // stallMs, sourceMs (timeoutMs), loadMs (allMs): tests only
|
|
31
|
+
let diedSaid = false
|
|
32
|
+
const csp = cspWatch(self) // X6 fix 10: a source the page's policy blocked says so in its reason
|
|
26
33
|
let port = null
|
|
27
34
|
const cache = new Map() // abs path -> {key, bytes, used}
|
|
28
35
|
let clock = 0
|
|
@@ -61,55 +68,102 @@ const cacheBytes = () => {
|
|
|
61
68
|
return n
|
|
62
69
|
}
|
|
63
70
|
|
|
71
|
+
/** A module url as the Worker's own place sees it (a table may give one relative to the page); one that cannot be made absolute goes on as it is and is refused. */
|
|
72
|
+
const absoluteUrl = u => {
|
|
73
|
+
try {
|
|
74
|
+
return new URL(u, self.location?.href).href
|
|
75
|
+
} catch {
|
|
76
|
+
return String(u)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
64
80
|
/**
|
|
65
|
-
* The module with this sha256, fetched, hashed against that sha256 and compiled
|
|
66
|
-
*
|
|
81
|
+
* The module with this sha256, fetched, hashed against that sha256 and compiled: ONCE per module per Worker (X6 default part 5: the promise is kept, so a run that
|
|
82
|
+
* gave up waiting, or a second run, starts no second download). Resolves {module, wasmBytes, fetchMs, compileMs} or {error, fatal}: fatal is a module that is not
|
|
83
|
+
* the one the table names or that no source could give (the twin is off for the machine), else it could not be compiled. When the load ends the Worker says so
|
|
84
|
+
* to the page: {t:'loaded'}, or {t:'died', fatal:true} (once, with the reason of each source).
|
|
67
85
|
*/
|
|
68
|
-
|
|
86
|
+
function loadModule(sha) {
|
|
69
87
|
const e = modules.get(sha)
|
|
70
|
-
if (!e) return { error: `the table names no module ${String(sha).slice(0, 12)}...` }
|
|
71
|
-
if (e.module) return { module: e.module }
|
|
72
|
-
if (e.bad) return { error: e.bad, fatal: e.fatal }
|
|
88
|
+
if (!e) return Promise.resolve({ error: `the table names no module ${String(sha).slice(0, 12)}...` })
|
|
89
|
+
if (e.module) return Promise.resolve({ module: e.module })
|
|
90
|
+
if (e.bad) return Promise.resolve({ error: e.bad, fatal: e.fatal })
|
|
91
|
+
if (!e.loadP) {
|
|
92
|
+
e.loadP = doLoad(sha, e).then(l => {
|
|
93
|
+
if (l.error) {
|
|
94
|
+
if (l.fatal && !diedSaid) {
|
|
95
|
+
diedSaid = true
|
|
96
|
+
port.postMessage({ t: 'died', why: l.error, fatal: true })
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
port.postMessage({ t: 'loaded', sha, wasmBytes: l.wasmBytes, fetchMs: l.fetchMs, compileMs: l.compileMs })
|
|
100
|
+
}
|
|
101
|
+
return l
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
return e.loadP
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function doLoad(sha, e) {
|
|
73
108
|
const t0 = performance.now()
|
|
74
109
|
try {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
110
|
+
// X6 default part 3, item 2: the bytes come from an ordered list of sources that are not trusted (src/host/pinned-fetch.js): a tarball of the npm registry,
|
|
111
|
+
// a file under a base, or the table's own url; the first that gives the pinned sha256 and size wins, and a good one is kept in Cache Storage
|
|
112
|
+
const sources = e.sources || globalSources || [{ kind: 'url', url: absoluteUrl(e.url) }]
|
|
113
|
+
const path = e.path || String(e.url || 'twin.wasm').split('/').pop() || 'twin.wasm'
|
|
114
|
+
let last = -1e9
|
|
115
|
+
const onProgress = bytes => {
|
|
116
|
+
const t = performance.now()
|
|
117
|
+
if (t - last < 250) return
|
|
118
|
+
last = t
|
|
119
|
+
port?.postMessage({ t: 'loading', sha, bytes })
|
|
120
|
+
}
|
|
121
|
+
const got = await fetchPinned({ files: [{ path, sha256: sha, size: e.size }], pkg: e.pkg ?? null, sources, schemes: ['https:', 'http:', 'data:', 'blob:'], onProgress, explain: (u, err) => csp.explain(u, err), ...(fetchKnobs.stallMs ? { stallMs: fetchKnobs.stallMs } : {}), ...(fetchKnobs.sourceMs ? { timeoutMs: fetchKnobs.sourceMs } : {}), ...(fetchKnobs.loadMs ? { allMs: fetchKnobs.loadMs } : {}) })
|
|
122
|
+
if (got.error) {
|
|
123
|
+
// every source failed (or the cache and the sources together): the twin is off for the machine, with the reason of each source in one text
|
|
124
|
+
e.bad = `the twin module could not be had: ${got.error}`
|
|
83
125
|
e.fatal = true
|
|
84
126
|
return { error: e.bad, fatal: true }
|
|
85
127
|
}
|
|
128
|
+
const bytes = got.files[path]
|
|
129
|
+
const t1 = performance.now()
|
|
86
130
|
e.module = await WebAssembly.compile(bytes)
|
|
87
131
|
return { module: e.module, wasmBytes: bytes.byteLength, fetchMs: t1 - t0, compileMs: performance.now() - t1 }
|
|
88
132
|
} catch (err) {
|
|
133
|
+
// the bytes passed the hash check, so a compile that throws (an engine out of memory, a module this engine cannot take) will throw again: the twin is off for
|
|
134
|
+
// the machine, once, with the real reason (a page that was told `loading` must not wait for ever), and nothing is downloaded a second time
|
|
89
135
|
e.bad = `the twin did not load: ${(err && err.message) || err}`
|
|
90
|
-
|
|
136
|
+
e.fatal = true
|
|
137
|
+
return { error: e.bad, fatal: true }
|
|
91
138
|
}
|
|
92
139
|
}
|
|
93
140
|
|
|
94
|
-
/**
|
|
141
|
+
/**
|
|
142
|
+
* A run whose module is not loaded starts the load (once), beating while it waits for it, at most waitMs: past that it is answered `loading` (not a failure: the
|
|
143
|
+
* guest compiles it) and the load goes on. Then compileOnce.
|
|
144
|
+
*/
|
|
95
145
|
async function runMessage(m) {
|
|
96
146
|
if (m.t !== 'run') return compileOnce(m, null)
|
|
97
147
|
const sha = (m.module ?? firstModule)?.toLowerCase()
|
|
98
148
|
const e = modules.get(sha)
|
|
99
149
|
if (!e) return { t: 'done', id: m.id, infra: `the table names no module ${String(sha).slice(0, 12)}...`, held: heldList() }
|
|
100
|
-
let timer = null
|
|
101
|
-
if (!e.module && !e.bad) timer = setInterval(() => port.postMessage({ t: 'beat', id: m.id }), beatMs)
|
|
102
150
|
let l
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
151
|
+
if (e.module || e.bad) l = await loadModule(sha)
|
|
152
|
+
else {
|
|
153
|
+
const timer = setInterval(() => port.postMessage({ t: 'beat', id: m.id }), beatMs)
|
|
154
|
+
let wait = null
|
|
155
|
+
try {
|
|
156
|
+
const gate = new Promise(r => (wait = setTimeout(() => r(null), waitMs)))
|
|
157
|
+
l = await Promise.race([loadModule(sha), gate])
|
|
158
|
+
} finally {
|
|
159
|
+
clearInterval(timer)
|
|
160
|
+
clearTimeout(wait)
|
|
161
|
+
}
|
|
162
|
+
if (l === null) return { t: 'done', id: m.id, loading: true, module: sha, held: heldList() }
|
|
107
163
|
}
|
|
108
164
|
if (l.error) {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
return null
|
|
112
|
-
}
|
|
165
|
+
// a module no source could give: loadModule said so to the page once ({t:'died', fatal}); this run has no answer to give
|
|
166
|
+
if (l.fatal) return null
|
|
113
167
|
return { t: 'done', id: m.id, infra: l.error, held: heldList() }
|
|
114
168
|
}
|
|
115
169
|
return compileOnce(m, l.module)
|
|
@@ -152,22 +206,22 @@ function compileOnce(m, module) {
|
|
|
152
206
|
}
|
|
153
207
|
|
|
154
208
|
self.onmessage = async ({ data: m }) => {
|
|
209
|
+
if (m.t === 'csp') return csp.add(m.violation) // the page's document saw the violation (a browser that does not fire it in the Worker)
|
|
155
210
|
if (m.t !== 'init') return
|
|
156
211
|
port = m.port
|
|
157
212
|
cacheCap = m.cacheBytes ?? cacheCap
|
|
158
213
|
beatMs = m.beatMs ?? beatMs
|
|
214
|
+
waitMs = m.waitMs ?? waitMs
|
|
215
|
+
fetchKnobs = { stallMs: m.stallMs, sourceMs: m.sourceMs, loadMs: m.loadMs }
|
|
216
|
+
globalSources = Array.isArray(m.sources) && m.sources.length ? m.sources : null
|
|
159
217
|
try {
|
|
160
218
|
// one module (the table's own wasmUrl and wasmSha256, which may be missing: the verifier then refuses) or a list of them
|
|
161
219
|
const list = m.modules || [{ url: m.wasmUrl, sha256: m.wasmSha256 }]
|
|
162
|
-
for (const x of list) modules.set(typeof x.sha256 === 'string' ? x.sha256.toLowerCase() : `none:${modules.size}`, { url: x.url })
|
|
220
|
+
for (const x of list) modules.set(typeof x.sha256 === 'string' ? x.sha256.toLowerCase() : `none:${modules.size}`, { url: x.url, size: x.size, path: x.path, pkg: x.pkg })
|
|
163
221
|
firstModule = [...modules.keys()][0]
|
|
222
|
+
// X6 default part 5: a preloaded module starts loading now and the Worker says ready at once: the network never holds `ready` (a compile that comes before the
|
|
223
|
+
// module is there waits for it at most waitMs, then goes to the guest)
|
|
164
224
|
const pre = m.modules ? m.preload || [] : [firstModule]
|
|
165
|
-
let first = null
|
|
166
|
-
for (const sha of pre) {
|
|
167
|
-
const l = await loadModule(String(sha).toLowerCase())
|
|
168
|
-
if (l.error) return port.postMessage({ t: 'died', why: l.error, fatal: l.fatal })
|
|
169
|
-
first ??= l
|
|
170
|
-
}
|
|
171
225
|
// a table keyed by a sha256 that is no digest at all (the one-module shape with no wasmSha256) is refused by the verifier above
|
|
172
226
|
port.onmessage = async e => {
|
|
173
227
|
let r
|
|
@@ -178,7 +232,8 @@ self.onmessage = async ({ data: m }) => {
|
|
|
178
232
|
}
|
|
179
233
|
if (r) port.postMessage(r, (r.outs || []).map(o => o.bytes.buffer))
|
|
180
234
|
}
|
|
181
|
-
port.postMessage({ t: 'ready', wasmBytes:
|
|
235
|
+
port.postMessage({ t: 'ready', wasmBytes: 0, fetchMs: 0, compileMs: 0, loaded: 0, loading: pre.length })
|
|
236
|
+
for (const sha of pre) void loadModule(String(sha).toLowerCase())
|
|
182
237
|
} catch (err) {
|
|
183
238
|
port.postMessage({ t: 'died', why: `the twin did not load: ${(err && err.message) || err}` })
|
|
184
239
|
}
|