@waffle-os/runtime 0.0.145 → 0.0.146

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 (133) hide show
  1. package/README.md +32 -0
  2. package/browser/command-input.ts +86 -0
  3. package/browser/command-owner.ts +5 -0
  4. package/browser/display/guest.ts +2 -18
  5. package/browser/display/surface-info.ts +19 -0
  6. package/browser/operations/cells.ts +90 -0
  7. package/browser/operations/guest.ts +94 -0
  8. package/browser/operations/owner.ts +201 -0
  9. package/browser/operations/protocol.ts +16 -0
  10. package/browser/operations/types.ts +41 -0
  11. package/browser/operations/writer.ts +106 -0
  12. package/browser/preview1-worker.ts +8 -1
  13. package/browser/process-broker.ts +372 -22
  14. package/browser/process-start.ts +5 -2
  15. package/browser/run-command.ts +388 -0
  16. package/browser/shared-fs.ts +20 -3
  17. package/browser/worker-memory.ts +6 -0
  18. package/browser/worker.ts +121 -27
  19. package/dist/browser/command-input.js +82 -0
  20. package/dist/browser/command-owner.js +2 -0
  21. package/dist/browser/display/guest.js +2 -18
  22. package/dist/browser/display/surface-info.js +18 -0
  23. package/dist/browser/operations/cells.js +80 -0
  24. package/dist/browser/operations/guest.js +67 -0
  25. package/dist/browser/operations/owner.js +175 -0
  26. package/dist/browser/operations/protocol.js +0 -0
  27. package/dist/browser/operations/types.js +0 -0
  28. package/dist/browser/operations/writer.js +98 -0
  29. package/dist/browser/preview1-worker.js +4 -0
  30. package/dist/browser/process-broker.js +317 -18
  31. package/dist/browser/process-start.js +3 -0
  32. package/dist/browser/run-command.js +377 -0
  33. package/dist/browser/shared-fs.js +8 -3
  34. package/dist/browser/worker-memory.js +10 -1
  35. package/dist/browser/worker.js +83 -28
  36. package/dist/fs/client.js +81 -18
  37. package/dist/fs/resolve-observation.js +11 -0
  38. package/dist/fs/service.js +51 -4
  39. package/dist/proc/command-transfer.js +72 -0
  40. package/dist/proc/directory.js +9 -1
  41. package/dist/proc/intrinsics/host.js +4 -1
  42. package/dist/proc/intrinsics.js +1 -0
  43. package/dist/proc/pipes.js +37 -4
  44. package/dist/proc/registry.js +25 -14
  45. package/dist/proc/start-command.js +101 -0
  46. package/dist/proc/supervisor.js +34 -10
  47. package/dist/proc/worker-broker.js +86 -31
  48. package/dist/proc/worker-client.js +67 -31
  49. package/dist/programs/collection.js +2 -0
  50. package/dist/runtime.js +14 -1
  51. package/dist/tooling/program/program-transformer.json +1 -1
  52. package/fs/client.ts +113 -17
  53. package/fs/resolve-observation.ts +25 -0
  54. package/fs/service.ts +63 -4
  55. package/index.ts +5 -0
  56. package/package.json +9 -1
  57. package/proc/command-transfer.ts +96 -0
  58. package/proc/directory.ts +10 -1
  59. package/proc/intrinsics/host.ts +5 -1
  60. package/proc/intrinsics.ts +1 -0
  61. package/proc/pipes.ts +39 -6
  62. package/proc/registry.ts +52 -17
  63. package/proc/start-command.ts +157 -0
  64. package/proc/supervisor.ts +34 -9
  65. package/proc/worker-broker.ts +100 -38
  66. package/proc/worker-client.ts +84 -31
  67. package/programs/collection.ts +4 -0
  68. package/runtime.ts +44 -3
  69. package/scripts/test-browser.ts +49 -29
  70. package/tests/browser-controls-discovery.test.ts +2 -10
  71. package/tests/browser-matrix.test.ts +105 -59
  72. package/tests/browser-navigation.test.ts +1 -1
  73. package/tests/browser-runner-lifecycle.ts +23 -13
  74. package/tests/command-input.test.ts +40 -0
  75. package/tests/command-scope.test.ts +422 -0
  76. package/tests/filesystem-client-intrinsics.test.ts +2 -0
  77. package/tests/filesystem-refcount.test.ts +2 -0
  78. package/tests/filesystem-resolve-observation.test.ts +185 -0
  79. package/tests/fixtures/command-bounded-admission.ts +31 -0
  80. package/tests/fixtures/command-disposal.ts +47 -0
  81. package/tests/fixtures/command-guests.ts +123 -0
  82. package/tests/fixtures/operation-fs-worker.ts +114 -0
  83. package/tests/fixtures/operation-observer-worker.ts +41 -0
  84. package/tests/fixtures/operation-page.ts +522 -0
  85. package/tests/fixtures/process-start-worker.ts +32 -0
  86. package/tests/link-browser-runner.ts +95 -22
  87. package/tests/node-exports.test.ts +29 -0
  88. package/tests/operation-diagnostics-browser.ts +192 -0
  89. package/tests/operation-diagnostics.test.ts +291 -0
  90. package/tests/page-runner/browser-controls-process-fixture.ts +24 -0
  91. package/tests/page-runner/browser-controls-runner.test.ts +20 -0
  92. package/tests/page-runner/browser-controls-runner.ts +1 -0
  93. package/tests/page-runner/browser-controls-suite.ts +20 -3
  94. package/tests/page-runner/control-run.ts +9 -1
  95. package/tests/page-runner/driver.ts +2 -0
  96. package/tests/page-runner/playwright-driver.ts +1 -1
  97. package/tests/page-runner/suite-host.ts +26 -1
  98. package/tests/page-runner/suite-startup.test.ts +39 -0
  99. package/tests/page-runner/threads-runtime-browser.test.ts +4 -6
  100. package/tests/page-runner/threads-runtime-suite.test.ts +14 -5
  101. package/tests/page-runner/worker-capability-controls.ts +174 -15
  102. package/tests/pipe-reader-reuse-races.test.ts +44 -0
  103. package/tests/process-start-browser-runner.ts +12 -4
  104. package/tests/process-start-browser.ts +66 -5
  105. package/tests/program-build-tools.test.ts +1 -1
  106. package/tests/runtime-facade.test.ts +5 -0
  107. package/tests/start-command.test.ts +109 -0
  108. package/tests/threads-guest-fixture.ts +1 -1
  109. package/tests/threads-guest-module.ts +6 -3
  110. package/tests/threads-guest.test.ts +25 -0
  111. package/tests/threads-runtime-browser-runner.ts +36 -13
  112. package/tests/threads-runtime-browser.ts +231 -92
  113. package/tests/threads-runtime-cases.ts +18 -1
  114. package/tests/threads-runtime-cleanup.ts +5 -1
  115. package/tests/threads-runtime-fd-browser.ts +247 -0
  116. package/tests/threads-runtime-fd-control.ts +3 -385
  117. package/tests/threads-runtime-fd-descriptors.test.ts +15 -13
  118. package/tests/threads-runtime-fd-module.ts +13 -2
  119. package/tests/threads-runtime-fd-service.ts +23 -2
  120. package/tests/threads-runtime-growth-worker.ts +61 -0
  121. package/tests/threads-runtime-host.ts +17 -4
  122. package/tests/threads-runtime-modules.ts +23 -5
  123. package/tests/threads-runtime-regression-controls.ts +386 -0
  124. package/tests/threads-runtime-regression-modules.ts +242 -0
  125. package/tests/threads-runtime-service-barrier.ts +8 -1
  126. package/tests/webkit-diagnostics.ts +125 -0
  127. package/tests/webkit-error-output.test.ts +118 -0
  128. package/tests/worker-memory-bootstrap.test.ts +19 -1
  129. package/tests/worker-memory-broker.test.ts +16 -8
  130. package/tooling/ci-paths.test.ts +329 -61
  131. package/tooling/private-authority.ts +14 -0
  132. package/tooling/program/program-transformer.json +1 -1
  133. package/tooling/tarball-smoke.ts +3 -1
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # @waffle-os/runtime
2
+
3
+ A WebAssembly runtime that lets programs share one filesystem, process tree, pipes, and loopback network in a browser tab.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @waffle-os/runtime
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ Register the filesystem worker (`fs-worker.ts`):
14
+
15
+ ```ts
16
+ import "@waffle-os/runtime/browser/fs-worker";
17
+ ```
18
+
19
+ Create one runtime per cross-origin isolated page (`app.ts`):
20
+
21
+ ```ts
22
+ import { createRuntime } from "@waffle-os/runtime";
23
+
24
+ const runtime = createRuntime({ filesystem: { workerURL: "/fs-worker.js", mode: "memory" } });
25
+ await runtime.filesystem.writeFile("/hello.txt", "hello from Waffle");
26
+ console.log(new TextDecoder().decode(await runtime.filesystem.readFile("/hello.txt")));
27
+ await runtime.dispose();
28
+ ```
29
+
30
+ ## Links
31
+
32
+ [Getting started](https://github.com/ShaulLavo/waffle/blob/main/docs/getting-started.md) · [Docs](https://github.com/ShaulLavo/waffle/blob/main/docs/README.md) · [Landing site](https://waffle.shaulavo.dev/)
@@ -0,0 +1,86 @@
1
+ import { PipeErrno, type PipeEndpoint } from "../proc/pipes.js";
2
+ import { ProcessError } from "../proc/types.js";
3
+
4
+ const BATCH = 32;
5
+
6
+ export class CommandInput {
7
+ private reader?: ReadableStreamDefaultReader<Uint8Array>;
8
+ private closed = false;
9
+ private readonly joined: Promise<void>;
10
+
11
+ constructor(
12
+ private readonly writer: PipeEndpoint,
13
+ source: Uint8Array | ReadableStream<Uint8Array>,
14
+ fail: (error: unknown) => void,
15
+ ) {
16
+ if (source instanceof ReadableStream) this.reader = source.getReader();
17
+ this.joined = Promise.all([
18
+ this.pump(source)
19
+ .catch((error) => {
20
+ if (!this.closed) fail(error);
21
+ })
22
+ .finally(() => this.close(false)),
23
+ writer.waitReaderHangup().then(() => this.close()),
24
+ ]).then(() => {});
25
+ void this.joined.catch(fail);
26
+ }
27
+
28
+ stop(): Promise<void> {
29
+ this.close();
30
+ return this.joined;
31
+ }
32
+
33
+ private close(cancel = true): void {
34
+ if (this.closed) return;
35
+ this.closed = true;
36
+ const reader = this.reader;
37
+ this.reader = undefined;
38
+ this.writer.close();
39
+ if (!reader) return;
40
+ const stream = this.stream;
41
+ reader.releaseLock();
42
+ if (cancel && stream) void stream.cancel().catch(() => {});
43
+ }
44
+
45
+ private stream?: ReadableStream<Uint8Array>;
46
+
47
+ private async pump(source: Uint8Array | ReadableStream<Uint8Array>): Promise<void> {
48
+ if (source instanceof Uint8Array) {
49
+ await this.write(source);
50
+ return;
51
+ }
52
+ this.stream = source;
53
+ let chunks = 0;
54
+ while (this.reader && !this.closed) {
55
+ const next = await this.reader.read();
56
+ if (this.closed || next.done) return;
57
+ if (!(next.value instanceof Uint8Array))
58
+ throw new TypeError("Command stdin requires byte chunks");
59
+ await this.write(next.value);
60
+ if (++chunks % BATCH === 0) await yieldTask();
61
+ }
62
+ }
63
+
64
+ private async write(bytes: Uint8Array): Promise<void> {
65
+ let offset = 0,
66
+ writes = 0;
67
+ while (!this.closed && offset < bytes.length) {
68
+ const accepted = this.writer.tryWrite([bytes.subarray(offset)]);
69
+ if (accepted === -PipeErrno.PIPE) {
70
+ this.close();
71
+ return;
72
+ }
73
+ if (accepted === -PipeErrno.AGAIN) {
74
+ await this.writer.waitWritable();
75
+ continue;
76
+ }
77
+ if (accepted <= 0) throw new ProcessError(-accepted, "Command stdin write failed");
78
+ offset += accepted;
79
+ if (++writes % BATCH === 0) await yieldTask();
80
+ }
81
+ }
82
+ }
83
+
84
+ function yieldTask(): Promise<void> {
85
+ return new Promise((resolve) => setTimeout(resolve, 0));
86
+ }
@@ -0,0 +1,5 @@
1
+ import type { BrowserProcessBroker } from "./process-broker.js";
2
+ import type { ProcessService, Runtime } from "../runtime.js";
3
+
4
+ export const commandOwners = new WeakMap<ProcessService, BrowserProcessBroker>();
5
+ export const commandDisposals = new WeakMap<Runtime, AbortController>();
@@ -1,4 +1,5 @@
1
1
  import type { GraphicsConnection } from "./protocol.js";
2
+ import { readSurfaceInfo } from "./surface-info.js";
2
3
  import {
3
4
  atomicsLoad,
4
5
  DataViewConstructor,
@@ -59,7 +60,7 @@ export function createDisplayImports(
59
60
  const output = guestOutput(memory, ptr, 16);
60
61
  for (let index = 0; index < surfaces.length; index++) {
61
62
  if (surfaces[index]!.id !== id) continue;
62
- return readInfo(new Int32ArrayConstructor(surfaces[index]!.info), output);
63
+ return readSurfaceInfo(new Int32ArrayConstructor(surfaces[index]!.info), output);
63
64
  }
64
65
  return -8;
65
66
  } catch {
@@ -68,20 +69,3 @@ export function createDisplayImports(
68
69
  },
69
70
  };
70
71
  }
71
- function readInfo(info: Int32Array, output: DataView): number {
72
- for (let attempt = 0; attempt < 16; attempt++) {
73
- const version = atomicsLoad(info, 0);
74
- if (version & 1) continue;
75
- const width = atomicsLoad(info, 1),
76
- height = atomicsLoad(info, 2);
77
- const scale = atomicsLoad(info, 3),
78
- flags = atomicsLoad(info, 4);
79
- if (version !== atomicsLoad(info, 0)) continue;
80
- dataViewSetUint32(output, 0, width, true);
81
- dataViewSetUint32(output, 4, height, true);
82
- dataViewSetUint32(output, 8, scale, true);
83
- dataViewSetUint32(output, 12, flags, true);
84
- return 0;
85
- }
86
- return -6;
87
- }
@@ -0,0 +1,19 @@
1
+ import { atomicsLoad, dataViewSetUint32 } from "../../proc/intrinsics.js";
2
+
3
+ export function readSurfaceInfo(info: Int32Array, output: DataView): number {
4
+ for (let attempt = 0; attempt < 16; attempt++) {
5
+ const version = atomicsLoad(info, 0);
6
+ if (version & 1) continue;
7
+ const width = atomicsLoad(info, 1),
8
+ height = atomicsLoad(info, 2);
9
+ const scale = atomicsLoad(info, 3),
10
+ flags = atomicsLoad(info, 4);
11
+ if (version !== atomicsLoad(info, 0)) continue;
12
+ dataViewSetUint32(output, 0, width, true);
13
+ dataViewSetUint32(output, 4, height, true);
14
+ dataViewSetUint32(output, 8, scale, true);
15
+ dataViewSetUint32(output, 12, flags, true);
16
+ return 0;
17
+ }
18
+ return -6;
19
+ }
@@ -0,0 +1,90 @@
1
+ import {
2
+ atomicsCompareExchange,
3
+ atomicsLoad,
4
+ BigInt64ArrayConstructor,
5
+ } from "../../proc/intrinsics/core.js";
6
+ import { BigIntConstructor } from "../../proc/intrinsics/host.js";
7
+ import type { GuestOperationBinding, OperationBinding } from "./protocol.js";
8
+
9
+ export const OPERATION_SLOTS = 16;
10
+ const ROW_WORDS = 20;
11
+ export const OPERATION_BYTES = OPERATION_SLOTS * ROW_WORDS * 8;
12
+ export const MAX_VALUE = 0xffffffff;
13
+ const MASK = 0xffffffffn;
14
+
15
+ export const PIPE_OFFSET = 0;
16
+ export const RESOLVE_OFFSET = 9;
17
+ export const ACKNOWLEDGED = 18;
18
+ export const Field = {
19
+ sequence: 0,
20
+ active: 1,
21
+ started: 2,
22
+ result: 3,
23
+ duration: 4,
24
+ completed: 5,
25
+ cancelled: 6,
26
+ failed: 7,
27
+ timed: 8,
28
+ } as const;
29
+
30
+ export const Result = {
31
+ completed: 1,
32
+ signalPending: 2,
33
+ processStop: 3,
34
+ filesystemCancelled: 4,
35
+ pollError: 5,
36
+ resolveError: 6,
37
+ transportError: 7,
38
+ submissionError: 8,
39
+ } as const;
40
+ export type ResultName = keyof typeof Result;
41
+ export type ResultCode = (typeof Result)[ResultName];
42
+
43
+ const perfNow = performance.now.bind(performance);
44
+ const timeOrigin = performance.timeOrigin;
45
+ const trunc = Math.trunc;
46
+ const min = Math.min;
47
+ const max = Math.max;
48
+ export function operationClock(): number {
49
+ return timeOrigin + perfNow();
50
+ }
51
+ export function elapsedFrom(origin: number, now = operationClock()): number {
52
+ return min(MAX_VALUE, max(0, trunc(now - origin)));
53
+ }
54
+
55
+ export class OperationCells {
56
+ readonly #words: BigInt64Array;
57
+ readonly #tag: bigint;
58
+ constructor(binding: OperationBinding | GuestOperationBinding) {
59
+ this.#words = new BigInt64ArrayConstructor(
60
+ binding.buffer,
61
+ binding.slot * ROW_WORDS * 8,
62
+ ROW_WORDS,
63
+ );
64
+ this.#tag = BigIntConstructor(binding.captureId);
65
+ }
66
+ read(index: number): number | undefined {
67
+ const cell = atomicsLoad(this.#words, index);
68
+ if (((cell >> 32n) & MASK) === this.#tag) return NumberConstructor(cell & MASK);
69
+ }
70
+ write(index: number, value: number): boolean {
71
+ const previous = atomicsLoad(this.#words, index);
72
+ if (((previous >> 32n) & MASK) !== this.#tag) return false;
73
+ const next = (this.#tag << 32n) | BigIntConstructor(value);
74
+ return atomicsCompareExchange(this.#words, index, previous, next) === previous;
75
+ }
76
+ /** Only the page changes a slot's tag. Each old producer can win at most one in-flight CAS. */
77
+ assign(): void {
78
+ const next = this.#tag << 32n;
79
+ for (let index = 0; index < ROW_WORDS; index++) {
80
+ let previous = atomicsLoad(this.#words, index);
81
+ for (;;) {
82
+ const actual = atomicsCompareExchange(this.#words, index, previous, next);
83
+ if (actual === previous) break;
84
+ previous = actual;
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ const NumberConstructor = Number;
@@ -0,0 +1,94 @@
1
+ import { RIGHT_FD_READ, RIGHT_POLL_FD_READWRITE } from "../../core/rights.js";
2
+ import type { DescriptorTable } from "../../core/descriptors.js";
3
+ import { PipeEndpoint } from "../../proc/pipes.js";
4
+ import { controlWait } from "../../proc/control.js";
5
+ import { assertTerminalWaitAllowed } from "../../proc/terminal-turn.js";
6
+ import {
7
+ DataViewConstructor,
8
+ dataViewGetUint32,
9
+ isInstance,
10
+ wasmMemoryBuffer,
11
+ } from "../../proc/intrinsics.js";
12
+ import type { OperationWriter } from "./writer.js";
13
+
14
+ export { createOperationWriters } from "./writer.js";
15
+
16
+ type Poll = (...args: number[]) => number;
17
+ const PIPE_READ_RIGHTS = RIGHT_FD_READ | RIGHT_POLL_FD_READWRITE;
18
+
19
+ function qualifyingPipe(
20
+ memory: WebAssembly.Memory | undefined,
21
+ descriptors: DescriptorTable,
22
+ ptr: number,
23
+ ): boolean {
24
+ if (!memory) return false;
25
+ try {
26
+ const subscription = new DataViewConstructor(wasmMemoryBuffer(memory), ptr >>> 0, 16);
27
+ if (dataViewGetUint32(subscription, 0, true) !== 0) return false;
28
+ const descriptor = descriptors.get(dataViewGetUint32(subscription, 4, true));
29
+ return (
30
+ !!descriptor &&
31
+ (descriptor.rightsBase & PIPE_READ_RIGHTS) === PIPE_READ_RIGHTS &&
32
+ isInstance(descriptor.resource, PipeEndpoint) &&
33
+ descriptor.resource.mode === "read"
34
+ );
35
+ } catch {
36
+ // The actual import owns validation and its error result.
37
+ return false;
38
+ }
39
+ }
40
+
41
+ export function observePipePoll(options: {
42
+ readonly writer: OperationWriter;
43
+ readonly entered: () => boolean;
44
+ readonly memory: () => WebAssembly.Memory | undefined;
45
+ readonly descriptors: DescriptorTable;
46
+ readonly checkActive: () => void;
47
+ readonly stopped: (error: unknown) => boolean;
48
+ }) {
49
+ const { writer, entered, memory, descriptors, checkActive, stopped } = options;
50
+ let qualified = false;
51
+ let guardStopped = false;
52
+ function guard(): void {
53
+ try {
54
+ checkActive();
55
+ } catch (error) {
56
+ guardStopped = stopped(error);
57
+ throw error;
58
+ }
59
+ }
60
+ function pollObserved(
61
+ poll: Poll,
62
+ ptr: number,
63
+ count: number,
64
+ timeout: number,
65
+ out: number,
66
+ ): number {
67
+ if (count !== 1 || timeout !== -1 || !entered() || !qualifyingPipe(memory(), descriptors, ptr))
68
+ return poll(ptr, count, timeout, out);
69
+ qualified = true;
70
+ guardStopped = false;
71
+ try {
72
+ const result = poll(ptr, count, timeout, out);
73
+ writer.settle(result === 1 ? "completed" : result === 0 ? "signalPending" : "pollError");
74
+ return result;
75
+ } catch (error) {
76
+ writer.settle(guardStopped ? "processStop" : "pollError");
77
+ throw error;
78
+ } finally {
79
+ qualified = false;
80
+ }
81
+ }
82
+ return {
83
+ wait(ms: number, word: Int32Array, expected: number): void {
84
+ guard();
85
+ assertTerminalWaitAllowed();
86
+ if (qualified) writer.begin(1);
87
+ controlWait(word, 0, expected, ms);
88
+ guard();
89
+ },
90
+ wrap(poll: Poll): Poll {
91
+ return (ptr, count, timeout, out) => pollObserved(poll, ptr!, count!, timeout!, out!);
92
+ },
93
+ };
94
+ }
@@ -0,0 +1,201 @@
1
+ import {
2
+ ACKNOWLEDGED,
3
+ elapsedFrom,
4
+ Field,
5
+ MAX_VALUE,
6
+ OPERATION_BYTES,
7
+ OPERATION_SLOTS,
8
+ OperationCells,
9
+ operationClock,
10
+ PIPE_OFFSET,
11
+ RESOLVE_OFFSET,
12
+ Result,
13
+ } from "./cells.js";
14
+ import type { GuestOperationBinding } from "./protocol.js";
15
+ import type {
16
+ OperationDiagnostics,
17
+ OperationImage,
18
+ OperationPhase,
19
+ OperationResult,
20
+ OperationSummary,
21
+ } from "./types.js";
22
+
23
+ type Image = Pick<OperationImage, "pid" | "generation" | "captureId">;
24
+ interface Capture {
25
+ readonly image: Image;
26
+ readonly cells: OperationCells;
27
+ readonly origin: number;
28
+ pipeReadWait?: OperationSummary;
29
+ fsResolve?: OperationSummary;
30
+ }
31
+
32
+ function result(code: number): OperationResult | undefined {
33
+ switch (code) {
34
+ case Result.completed:
35
+ return { phase: "completed" };
36
+ case Result.signalPending:
37
+ return { phase: "cancelled", reason: "signal-pending" };
38
+ case Result.processStop:
39
+ return { phase: "cancelled", reason: "process-stop" };
40
+ case Result.filesystemCancelled:
41
+ return { phase: "cancelled", reason: "filesystem-cancelled" };
42
+ case Result.pollError:
43
+ return { phase: "failed", reason: "poll-error" };
44
+ case Result.resolveError:
45
+ return { phase: "failed", reason: "resolve-error" };
46
+ case Result.transportError:
47
+ return { phase: "failed", reason: "transport-error" };
48
+ case Result.submissionError:
49
+ return { phase: "failed", reason: "submission-error" };
50
+ }
51
+ }
52
+
53
+ function readSummary(capture: Capture, offset: number, now: number): OperationSummary | undefined {
54
+ const { cells, origin } = capture;
55
+ for (let attempt = 0; attempt < 2; attempt++) {
56
+ const first = cells.read(offset + Field.sequence);
57
+ if (first === undefined || first % 2 !== 0) continue;
58
+ const active = cells.read(offset + Field.active);
59
+ const started = cells.read(offset + Field.started);
60
+ const code = cells.read(offset + Field.result);
61
+ const duration = cells.read(offset + Field.duration);
62
+ const timed = cells.read(offset + Field.timed);
63
+ const completed = cells.read(offset + Field.completed);
64
+ const cancelled = cells.read(offset + Field.cancelled);
65
+ const failed = cells.read(offset + Field.failed);
66
+ const accepted = offset === RESOLVE_OFFSET && cells.read(ACKNOWLEDGED) === active;
67
+ if (cells.read(offset + Field.sequence) !== first) continue;
68
+ if (
69
+ active === undefined ||
70
+ started === undefined ||
71
+ code === undefined ||
72
+ duration === undefined ||
73
+ completed === undefined ||
74
+ cancelled === undefined ||
75
+ failed === undefined
76
+ )
77
+ continue;
78
+ const phase: OperationPhase =
79
+ offset === PIPE_OFFSET ? "waiting" : accepted ? "accepted" : "submitted";
80
+ const latest = result(code);
81
+ return {
82
+ ...(active
83
+ ? {
84
+ active: {
85
+ phase,
86
+ elapsedMs: started === MAX_VALUE ? null : elapsedFrom(origin + started, now),
87
+ },
88
+ }
89
+ : {}),
90
+ ...(latest ? { latest: { ...latest, elapsedMs: timed ? duration : null } } : {}),
91
+ completed,
92
+ cancelled,
93
+ failed,
94
+ };
95
+ }
96
+ }
97
+
98
+ function retire(summary: OperationSummary | undefined): OperationSummary | undefined {
99
+ if (!summary?.active) return summary;
100
+ const { active, ...confirmed } = summary;
101
+ return {
102
+ ...confirmed,
103
+ retirement: { phase: "retired-unconfirmed", elapsedMs: active.elapsedMs },
104
+ };
105
+ }
106
+
107
+ function copy(summary: OperationSummary | undefined): OperationSummary | undefined {
108
+ if (!summary) return;
109
+ return {
110
+ completed: summary.completed,
111
+ cancelled: summary.cancelled,
112
+ failed: summary.failed,
113
+ ...(summary.active ? { active: { ...summary.active } } : {}),
114
+ ...(summary.latest ? { latest: { ...summary.latest } } : {}),
115
+ ...(summary.retirement ? { retirement: { ...summary.retirement } } : {}),
116
+ };
117
+ }
118
+
119
+ export class OperationOwner {
120
+ private buffer?: SharedArrayBuffer;
121
+ private unavailable = false;
122
+ private readonly slots = Array.from<Capture | undefined>({ length: OPERATION_SLOTS });
123
+ private readonly history: OperationImage[] = [];
124
+ private nextHistory = 0;
125
+ private captureId = 0;
126
+ private skippedImages = 0;
127
+ constructor(
128
+ private readonly allocate: (length: number) => SharedArrayBuffer,
129
+ private readonly owned: (image: Image) => boolean,
130
+ ) {}
131
+
132
+ enroll(pid: number, generation: number): GuestOperationBinding | undefined {
133
+ if (this.unavailable || this.captureId === MAX_VALUE) return;
134
+ if (!this.buffer) {
135
+ try {
136
+ this.buffer = this.allocate(OPERATION_BYTES);
137
+ } catch {
138
+ this.unavailable = true;
139
+ return;
140
+ }
141
+ }
142
+ this.reconcile();
143
+ const slot = this.slots.indexOf(undefined);
144
+ if (slot < 0) {
145
+ this.skippedImages = Math.min(MAX_VALUE, this.skippedImages + 1);
146
+ return;
147
+ }
148
+ const captureId = ++this.captureId;
149
+ const origin = operationClock();
150
+ const binding = { buffer: this.buffer, slot, captureId, origin };
151
+ const cells = new OperationCells(binding);
152
+ cells.assign();
153
+ this.slots[slot] = { image: { pid, generation, captureId }, cells, origin };
154
+ return binding;
155
+ }
156
+
157
+ snapshot(): OperationDiagnostics {
158
+ if (this.unavailable) return { status: "unavailable" };
159
+ if (!this.buffer) return { status: "empty" };
160
+ const owned = this.reconcile();
161
+ const history = this.history
162
+ .slice(this.nextHistory)
163
+ .concat(this.history.slice(0, this.nextHistory));
164
+ const departed = history.map(({ pipeReadWait, fsResolve, ...image }) => ({
165
+ ...image,
166
+ pipeReadWait: copy(pipeReadWait),
167
+ fsResolve: copy(fsResolve),
168
+ }));
169
+ return { status: "recording", owned, departed, skippedImages: this.skippedImages };
170
+ }
171
+
172
+ private reconcile(): OperationImage[] {
173
+ const now = operationClock();
174
+ const rows: OperationImage[] = [];
175
+ for (let slot = 0; slot < OPERATION_SLOTS; slot++) {
176
+ const capture = this.slots[slot];
177
+ if (!capture) continue;
178
+ const pipeReadWait = readSummary(capture, PIPE_OFFSET, now);
179
+ const fsResolve = readSummary(capture, RESOLVE_OFFSET, now);
180
+ if (pipeReadWait) capture.pipeReadWait = pipeReadWait;
181
+ if (fsResolve) capture.fsResolve = fsResolve;
182
+ if (!this.owned(capture.image)) {
183
+ this.archive(slot, capture);
184
+ continue;
185
+ }
186
+ rows.push({ ...capture.image, pipeReadWait: copy(pipeReadWait), fsResolve: copy(fsResolve) });
187
+ }
188
+ return rows;
189
+ }
190
+
191
+ private archive(slot: number, capture: Capture): void {
192
+ new OperationCells({ buffer: this.buffer!, slot, captureId: 0 }).assign();
193
+ this.slots[slot] = undefined;
194
+ this.history[this.nextHistory] = {
195
+ ...capture.image,
196
+ pipeReadWait: retire(capture.pipeReadWait),
197
+ fsResolve: retire(capture.fsResolve),
198
+ };
199
+ this.nextHistory = (this.nextHistory + 1) % OPERATION_SLOTS;
200
+ }
201
+ }
@@ -0,0 +1,16 @@
1
+ import type { RuntimeWorkerRequest } from "../worker.js";
2
+
3
+ export interface OperationBinding {
4
+ readonly buffer: SharedArrayBuffer;
5
+ readonly slot: number;
6
+ readonly captureId: number;
7
+ }
8
+
9
+ export interface GuestOperationBinding extends OperationBinding {
10
+ readonly origin: number;
11
+ }
12
+
13
+ export type ObservedPreview1Bootstrap = [
14
+ request: RuntimeWorkerRequest,
15
+ operations: GuestOperationBinding,
16
+ ];
@@ -0,0 +1,41 @@
1
+ export type OperationPhase = "waiting" | "submitted" | "accepted";
2
+ export type OperationResult =
3
+ | { readonly phase: "completed" }
4
+ | {
5
+ readonly phase: "cancelled";
6
+ readonly reason: "signal-pending" | "process-stop" | "filesystem-cancelled";
7
+ }
8
+ | {
9
+ readonly phase: "failed";
10
+ readonly reason: "poll-error" | "resolve-error" | "transport-error" | "submission-error";
11
+ };
12
+
13
+ export interface OperationSummary {
14
+ readonly active?: { readonly phase: OperationPhase; readonly elapsedMs: number | null };
15
+ readonly latest?: OperationResult & { readonly elapsedMs: number | null };
16
+ readonly retirement?: {
17
+ readonly phase: "retired-unconfirmed";
18
+ readonly elapsedMs: number | null;
19
+ };
20
+ readonly completed: number;
21
+ readonly cancelled: number;
22
+ readonly failed: number;
23
+ }
24
+
25
+ export interface OperationImage {
26
+ readonly pid: number;
27
+ readonly generation: number;
28
+ readonly captureId: number;
29
+ /** Omitted when the guest is updating this operation's cells. */
30
+ readonly pipeReadWait?: OperationSummary;
31
+ readonly fsResolve?: OperationSummary;
32
+ }
33
+
34
+ export type OperationDiagnostics =
35
+ | { readonly status: "disabled" | "empty" | "unavailable" }
36
+ | {
37
+ readonly status: "recording";
38
+ readonly owned: readonly OperationImage[];
39
+ readonly departed: readonly OperationImage[];
40
+ readonly skippedImages: number;
41
+ };