@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/dist/runtime.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { commandDisposals, commandOwners } from "./browser/command-owner.js";
1
2
  import { installSharedControlAllocator } from "./memory/control.js";
2
3
  import { defaultSharedMemoryPlatform, validateDeclaration } from "./memory/platform.js";
3
4
  import {
@@ -193,6 +194,7 @@ function sourceTime() {
193
194
  }
194
195
  }
195
196
  export function createRuntime(options = {}) {
197
+ const observeOperations = options.observeOperations === true;
196
198
  if (owners[ownerKey] !== undefined)
197
199
  throw new Error("A live page runtime already owns this page");
198
200
  const token = {};
@@ -396,6 +398,12 @@ export function createRuntime(options = {}) {
396
398
  get disposed() {
397
399
  return disposed;
398
400
  },
401
+ operationDiagnostics() {
402
+ assertLive();
403
+ if (!observeOperations)
404
+ return { status: "disabled" };
405
+ return host?.operationDiagnostics() ?? { status: "empty" };
406
+ },
399
407
  registerAdapter(name, launch) {
400
408
  return registerAdapter(name, "guest", launch);
401
409
  },
@@ -553,7 +561,7 @@ export function createRuntime(options = {}) {
553
561
  reservations,
554
562
  hostIdentity,
555
563
  filesystem: {
556
- connect: (identity, headroom) => filesystem.connect(identity, headroom),
564
+ connect: (identity, headroom, operations) => operations ? filesystem.connectObserved(identity, headroom, operations) : filesystem.connect(identity, headroom),
557
565
  revoke: (identity) => filesystem.revoke(identity),
558
566
  reap: (identity) => filesystem.reap(identity),
559
567
  quiesce: (identity) => filesystem.quiesce(identity),
@@ -563,6 +571,7 @@ export function createRuntime(options = {}) {
563
571
  registry: activeRegistry,
564
572
  table,
565
573
  onProcessAdmission: options.onProcessAdmission,
574
+ observeOperations,
566
575
  memoryGroups: options.memoryGroups,
567
576
  launchCommand: (context, capabilities) => ownLaunch(async () => {
568
577
  const { runCommand } = await import("./proc/command-runner.js");
@@ -577,6 +586,8 @@ export function createRuntime(options = {}) {
577
586
  }
578
587
  };
579
588
  const created = await (options.processHost ? options.processHost(hostOptions) : import("./browser/process-broker.js").then(({ BrowserProcessBroker }) => new BrowserProcessBroker(hostOptions)));
589
+ if (observeOperations)
590
+ await created.prepareOperationDiagnostics();
580
591
  host = created;
581
592
  return created;
582
593
  });
@@ -596,6 +607,7 @@ export function createRuntime(options = {}) {
596
607
  return borrowed;
597
608
  };
598
609
  service = borrow(owner, processCapabilities, assertLive, new Map([["ready", ready]]));
610
+ commandOwners.set(service, owner);
599
611
  return service;
600
612
  });
601
613
  return activation;
@@ -686,6 +698,7 @@ export function createRuntime(options = {}) {
686
698
  });
687
699
  token.disposal = disposal;
688
700
  suspend(failures);
701
+ commandDisposals.get(runtime)?.abort();
689
702
  if (pendingStartup) {
690
703
  try {
691
704
  filesystem.revoke(filesystem.client.connection);
@@ -1 +1 @@
1
- {"commit":"4d79516d35d2b72d099b0800a3b2b8e18d712ddb","buildToolsSha256":"ff483dc57811fa0752d84f76fcbea3e384c3a4cd2a63c6fcd9849fe51df0c9a2","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
1
+ {"commit":"3230c056cde1ff65b3392c39ba04ba8515fa7a10","buildToolsSha256":"ff483dc57811fa0752d84f76fcbea3e384c3a4cd2a63c6fcd9849fe51df0c9a2","optimizerSourceSha256":"34c4a040f3cf639f039823880822c6541c384c9b4eaa116d27dda8d9cb5c9f9e"}
package/fs/client.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import { allocateSharedControl } from "../memory/control.js";
2
+ import type { OperationWriter } from "../browser/operations/writer.js";
3
+ import { isInstance } from "../proc/intrinsics/core.js";
2
4
  import type { WalkPlan, WalkCursor, WalkPage, WalkPageOptions } from "./walk.js";
3
5
  import { FilesystemWatch, type WatchOptions } from "./watch.js";
4
6
  import { checkDirectoryPage } from "./directory-pages.js";
5
7
  import { DirtyCapacityError } from "./dirty-admission.js";
6
8
  import { ResidentAttachment, stopWorkspaceBridge } from "./publication-attachment.js";
7
9
  import { localPublication } from "./publication-internal.js";
10
+ import { takeResolveObservation, type ResolveObservation } from "./resolve-observation.js";
8
11
  import {
9
12
  FilesystemRequestAllocator,
10
13
  FilesystemTransportError,
@@ -170,7 +173,17 @@ function transferList(payload: ArrayBuffer): Transferable[] {
170
173
  return { __proto__: null, [symbolIterator]: () => iterator } as unknown as Transferable[];
171
174
  }
172
175
 
176
+ type WaitCancellation = { error?: FilesystemError };
177
+ let waitForObservedResolve: (
178
+ completion: FilesystemCompletion,
179
+ cancellation: WaitCancellation,
180
+ ) => ResolvedPath | number;
181
+
173
182
  export class FilesystemCompletion {
183
+ static {
184
+ waitForObservedResolve = (completion, cancellation) => completion.#wait(cancellation);
185
+ }
186
+
174
187
  readonly cells: Int32Array;
175
188
  private changed: (() => void)[] = [];
176
189
  private cancellations = new SetConstructor<() => void>();
@@ -241,15 +254,18 @@ export class FilesystemCompletion {
241
254
  this.consumed = true;
242
255
  this.release();
243
256
  }
244
- private check(): void {
257
+ private check(cancellation?: WaitCancellation): void {
245
258
  const failure = this.client.transportError();
246
259
  if (failure) throw failure;
247
260
  if (
248
261
  isRevoked(this.client.connection) ||
249
262
  requestCancelled(this.buffer) ||
250
263
  this.cells[0] === State.Cancelled
251
- )
252
- throw new FilesystemError(11);
264
+ ) {
265
+ const error = new FilesystemError(11);
266
+ if (cancellation) cancellation.error = error;
267
+ throw error;
268
+ }
253
269
  if (this.cells[0] === State.Failed) throw new FilesystemError(this.cells[3]!);
254
270
  }
255
271
  private decode(bytes: Uint8Array): unknown {
@@ -261,26 +277,42 @@ export class FilesystemCompletion {
261
277
  return new Uint8ArrayConstructor(typedArraySubarray(requestBytes(this.buffer), 0, available));
262
278
  }
263
279
  wait(): any {
280
+ return this.#wait();
281
+ }
282
+ #wait(cancellation?: WaitCancellation): any {
264
283
  const signal = new Int32ArrayConstructor(this.client.connection.signal);
265
284
  while (!this.ready) {
266
285
  const observed = atomicsLoad(signal, 0);
267
- this.check();
286
+ this.check(cancellation);
268
287
  if (!this.ready) atomicsWait(signal, 0, observed);
269
288
  }
270
- this.check();
289
+ this.check(cancellation);
271
290
  if (this.consumed) return this.decoded;
272
291
  const size = this.cells[2]!;
273
292
  let bytes = this.inlineBytes();
274
293
  if (this.cells[0] === State.Overflow) {
275
294
  bytes = new Uint8ArrayConstructor(size);
276
- for (let at = 0; at < size; at += PAGE)
277
- bytes.set(this.client.call("take", [this.id, at, PAGE]), at);
295
+ for (let at = 0; at < size; at += PAGE) {
296
+ const args = [this.id, at, PAGE];
297
+ const part = cancellation
298
+ ? this.#takeObserved(args, cancellation)
299
+ : this.client.call("take", args);
300
+ bytes.set(part, at);
301
+ }
278
302
  }
279
- this.check();
303
+ this.check(cancellation);
280
304
  this.decoded = this.decode(bytes);
281
305
  this.consumed = true;
282
306
  return this.decoded;
283
307
  }
308
+ #takeObserved(args: number[], cancellation: WaitCancellation): Uint8Array {
309
+ const part = this.client.submit("take", args);
310
+ try {
311
+ return part.#wait(cancellation);
312
+ } finally {
313
+ part.release();
314
+ }
315
+ }
284
316
  async value(): Promise<any> {
285
317
  if (!this.ready)
286
318
  await new Promise<void>((resolve) => {
@@ -391,6 +423,33 @@ export interface FilesystemClientOptions {
391
423
  /** Trusted host capability; never included in a serialized connection or supplied to a guest. */
392
424
  readonly connect?: (identity: FilesystemIdentity) => FilesystemConnection;
393
425
  }
426
+
427
+ function observeResolveWait(
428
+ completion: FilesystemCompletion,
429
+ writer: OperationWriter,
430
+ ): ResolvedPath | number {
431
+ const cancellation: WaitCancellation = {};
432
+ writer.begin(completion.id);
433
+ let value: ResolvedPath | number;
434
+ try {
435
+ value = waitForObservedResolve(completion, cancellation);
436
+ } catch (error) {
437
+ writer.settle(
438
+ isInstance(error, FilesystemTransportError)
439
+ ? "transportError"
440
+ : cancellation.error && error === cancellation.error
441
+ ? "filesystemCancelled"
442
+ : "resolveError",
443
+ );
444
+ throw error;
445
+ }
446
+ writer.settle(
447
+ value && typeof value === "object" && typeof value.parent === "number"
448
+ ? "completed"
449
+ : "resolveError",
450
+ );
451
+ return value;
452
+ }
394
453
  function retiredLocalRelease(connection: FilesystemConnection, error: unknown): boolean {
395
454
  if (!(error instanceof FilesystemTransportError) || error.reason !== "stale") return false;
396
455
  if (atomicsLoad(new Int32ArrayConstructor(connection.revocations[0]!), 0) !== 2) return false;
@@ -446,10 +505,15 @@ export class FilesystemClient implements FileSystem {
446
505
  private watchingRevocation = false;
447
506
  private resident: ResidentAttachment | undefined;
448
507
  private workspaceStop: Promise<void> | undefined;
508
+ readonly #resolveCold: (key: string, args: unknown[]) => ResolvedPath | number;
449
509
  constructor(
450
510
  readonly connection: FilesystemConnection,
451
511
  private readonly options: FilesystemClientOptions = {},
452
512
  ) {
513
+ const observation = takeResolveObservation(connection);
514
+ this.#resolveCold = observation
515
+ ? (key, args) => this.#resolveObserved(key, args, observation)
516
+ : this.#resolveUnobserved;
453
517
  this.requests = new FilesystemRequestAllocator(connection.requests);
454
518
  this.capabilities = new Int32ArrayConstructor(connection.capabilities, 0, CAPABILITY_LENGTH);
455
519
  this.epoch = new Int32ArrayConstructor(connection.epoch);
@@ -484,6 +548,28 @@ export class FilesystemClient implements FileSystem {
484
548
  };
485
549
  connection.port.start();
486
550
  }
551
+ #resolveObserved(
552
+ key: string,
553
+ args: unknown[],
554
+ { entered, writer }: ResolveObservation,
555
+ ): ResolvedPath | number {
556
+ if (!entered()) return this.#resolveUnobserved(key, args);
557
+ let completion: FilesystemCompletion;
558
+ try {
559
+ completion = this.submit("resolve", args);
560
+ } catch (error) {
561
+ writer.submissionFailed(
562
+ isInstance(error, FilesystemTransportError) ? "transportError" : "submissionError",
563
+ );
564
+ throw error;
565
+ }
566
+ try {
567
+ const resolved = observeResolveWait(completion, writer);
568
+ return this.#cacheResolved(key, completion.epoch, resolved);
569
+ } finally {
570
+ completion.release();
571
+ }
572
+ }
487
573
  transportError() {
488
574
  return requestTransportError(this.requests.memory);
489
575
  }
@@ -1585,19 +1671,29 @@ export class FilesystemClient implements FileSystem {
1585
1671
  const cached = this.paths.get(key);
1586
1672
  if (!this.resident && !this.shared.publication && !(epoch & 1) && cached?.epoch === epoch)
1587
1673
  return typeof cached.path === "number" ? cached.path : { ...cached.path };
1588
- const completion = this.submit("resolve", [directory, path, followFinal]);
1589
- try {
1590
- const resolved: ResolvedPath | number = completion.wait();
1591
- if (this.paths.size >= 256) this.paths.clear();
1592
- this.paths.set(key, { path: resolved, epoch: completion.epoch });
1593
- return typeof resolved === "number" ? resolved : { ...resolved };
1594
- } finally {
1595
- completion.release();
1596
- }
1674
+ return this.#resolveCold(key, [directory, path, followFinal]);
1597
1675
  } catch (error) {
1598
1676
  return errno(error);
1599
1677
  }
1600
1678
  }
1679
+ #resolveUnobserved(key: string, args: unknown[]): ResolvedPath | number {
1680
+ const completion = this.submit("resolve", args);
1681
+ try {
1682
+ const resolved: ResolvedPath | number = completion.wait();
1683
+ return this.#cacheResolved(key, completion.epoch, resolved);
1684
+ } finally {
1685
+ completion.release();
1686
+ }
1687
+ }
1688
+ #cacheResolved(
1689
+ key: string,
1690
+ epoch: number,
1691
+ resolved: ResolvedPath | number,
1692
+ ): ResolvedPath | number {
1693
+ if (this.paths.size >= 256) this.paths.clear();
1694
+ this.paths.set(key, { path: resolved, epoch });
1695
+ return typeof resolved === "number" ? resolved : { ...resolved };
1696
+ }
1601
1697
  stat(handle: FileHandle): FileStat {
1602
1698
  // Keep the capability's backend pin alive while reading its shared metadata slot.
1603
1699
  this.retain(handle);
@@ -0,0 +1,25 @@
1
+ import type { OperationWriter } from "../browser/operations/writer.js";
2
+ import { WeakMapConstructor, weakMapDelete, weakMapGet, weakMapSet } from "../proc/intrinsics.js";
3
+ import type { FilesystemConnection } from "./protocol.js";
4
+
5
+ export interface ResolveObservation {
6
+ readonly entered: () => boolean;
7
+ readonly writer: OperationWriter;
8
+ }
9
+
10
+ const observations = new WeakMapConstructor<FilesystemConnection, ResolveObservation>();
11
+
12
+ export function registerResolveObservation(
13
+ connection: FilesystemConnection,
14
+ observation: ResolveObservation,
15
+ ): void {
16
+ weakMapSet(observations, connection, observation);
17
+ }
18
+
19
+ export function takeResolveObservation(
20
+ connection: FilesystemConnection,
21
+ ): ResolveObservation | undefined {
22
+ const observation = weakMapGet(observations, connection);
23
+ if (observation) weakMapDelete(observations, connection);
24
+ return observation;
25
+ }
package/fs/service.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { WalkTable, type WalkTransaction } from "./walk.js";
2
+ import type { OperationBinding } from "../browser/operations/protocol.js";
2
3
  import {
3
4
  requestMemorySections,
4
5
  waitForRequestQuiescence,
@@ -87,6 +88,11 @@ const mutations = new Set([
87
88
  "remove",
88
89
  "move",
89
90
  ]);
91
+ let connectObserved: (
92
+ owner: FilesystemService,
93
+ connection: FilesystemConnection,
94
+ acceptResolve: (id: number) => void,
95
+ ) => void;
90
96
  type ResponsePayload =
91
97
  | { kind: "pending" }
92
98
  | { kind: "inline" }
@@ -180,6 +186,11 @@ interface PreparedRequest {
180
186
  }
181
187
  /** One serial owner of the tree. No request ever waits for a guest acknowledgment. */
182
188
  export class FilesystemService {
189
+ static {
190
+ connectObserved = (owner, connection, acceptResolve) =>
191
+ owner.#connect(connection, acceptResolve);
192
+ }
193
+
183
194
  private sessions = new Set<Session>();
184
195
  private requestBudget?: SharedArrayBuffer;
185
196
  private readBudget?: WorkspaceReadBudget;
@@ -231,6 +242,9 @@ export class FilesystemService {
231
242
  }
232
243
  }
233
244
  connect(connection: FilesystemConnection): void {
245
+ this.#connect(connection);
246
+ }
247
+ #connect(connection: FilesystemConnection, acceptResolve?: (id: number) => void): void {
234
248
  if (this.ownerStopping) {
235
249
  this.refuseConnection(connection);
236
250
  throw new FilesystemError(11);
@@ -308,17 +322,40 @@ export class FilesystemService {
308
322
  // The launch snapshot can be older than the tree. Every segment that exists now is offered
309
323
  // again, so an agent that reaches its event loop attaches what its snapshot lacked.
310
324
  this.announceSegments(this.backend.sharedSegments?.() ?? [], [session]);
311
- connection.port.onmessage = ({ data }: MessageEvent<RequestMessage>) => {
325
+ const receive = ({ data }: MessageEvent<RequestMessage>) => {
312
326
  try {
313
327
  this.receive(session, data);
314
328
  } catch {
315
329
  this.signalTransportFailure(session, "protocol");
316
330
  }
317
331
  };
332
+ connection.port.onmessage = acceptResolve
333
+ ? (event: MessageEvent<RequestMessage>) => {
334
+ receive(event);
335
+ this.observeAcceptedResolve(session, event.data, acceptResolve);
336
+ }
337
+ : receive;
318
338
  connection.port.onmessageerror = () => this.signalTransportFailure(session);
319
339
  connection.port.start();
320
340
  if (!session.closed) this.trackWork(session, this.watchTransport(session));
321
341
  }
342
+ private observeAcceptedResolve(
343
+ session: Session,
344
+ data: RequestMessage,
345
+ accept: (id: number) => void,
346
+ ): void {
347
+ try {
348
+ if (!("id" in data)) return;
349
+ if (requestTransportError(session.requests)) return;
350
+ const buffer = session.pending.get(data.id);
351
+ if (!buffer) return;
352
+ const bytes = requestInput(session, data.id, requestBytes(buffer));
353
+ const { inputLength } = requestLengths(buffer, bytes);
354
+ if (unpack(bytes.subarray(0, inputLength)).operation === "resolve") accept(data.id);
355
+ } catch {
356
+ // Receipt observation cannot fail the transport or affect the queued request.
357
+ }
358
+ }
322
359
  /** Offers segments by index. Delivery is never awaited or acknowledged: a blocked agent
323
360
  * cannot receive it, and reaches those pages through the owner until it can. */
324
361
  private announceSegments(
@@ -2070,6 +2107,23 @@ function diagnosticField(error: unknown, key: string): string | undefined {
2070
2107
  return;
2071
2108
  }
2072
2109
  }
2110
+
2111
+ async function prepareAcceptance(binding: OperationBinding) {
2112
+ try {
2113
+ const { captureAcceptance } = await import("../browser/operations/writer.js");
2114
+ return captureAcceptance(binding);
2115
+ } catch {
2116
+ return undefined;
2117
+ }
2118
+ }
2119
+
2120
+ function backendOptions(data: Record<string, unknown>): Record<string, unknown> {
2121
+ if (data.operations === undefined) return data;
2122
+ const options = { ...data };
2123
+ delete options.operations;
2124
+ return options;
2125
+ }
2126
+
2073
2127
  /** Installs the service in a browser/Bun worker without importing any app code. */
2074
2128
  export function installFilesystemWorker(
2075
2129
  scope: {
@@ -2121,13 +2175,13 @@ export function installFilesystemWorker(
2121
2175
  scope.postMessage({ type: "filesystem-startup", stage, timestamp });
2122
2176
  reportRuntimeStartup(onStartupStage, "filesystem-connected");
2123
2177
  }
2124
- return backendFactory(data, onStartupStage, startupAbort.signal, () => {
2178
+ return backendFactory(backendOptions(data), onStartupStage, startupAbort.signal, () => {
2125
2179
  if (!disposing) scope.postMessage({ type: "filesystem-state", status: "waiting" });
2126
2180
  });
2127
2181
  })
2128
2182
  .then((backend) => new FilesystemService(backend));
2129
2183
  void service
2130
- .then((owner) => {
2184
+ .then(async (owner) => {
2131
2185
  if (disposing) {
2132
2186
  data.connect?.port.close();
2133
2187
  return;
@@ -2135,7 +2189,12 @@ export function installFilesystemWorker(
2135
2189
  if (data.socketScope && data.connect && data.reply) {
2136
2190
  attachSocketScopeControl(owner, data);
2137
2191
  } else if (data.connect) {
2138
- owner.connect(data.connect);
2192
+ const acceptResolve = data.operations
2193
+ ? await prepareAcceptance(data.operations)
2194
+ : undefined;
2195
+ if (disposing) return data.connect.port.close();
2196
+ if (acceptResolve) connectObserved(owner, data.connect, acceptResolve);
2197
+ else owner.connect(data.connect);
2139
2198
  scope.postMessage({ type: "filesystem-state", status: "ready" });
2140
2199
  reportRuntimeStartup(onStartupStage, "filesystem-ready");
2141
2200
  onStartupStage = undefined;
package/index.ts CHANGED
@@ -38,6 +38,11 @@ export type {
38
38
  WorkerMemoryObservation,
39
39
  ProcessStartState,
40
40
  ProcessStartStep,
41
+ OperationDiagnostics,
42
+ OperationImage,
43
+ OperationPhase,
44
+ OperationResult,
45
+ OperationSummary,
41
46
  ProgramDefinition,
42
47
  ProgramLoadState,
43
48
  GuestLauncher,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waffle-os/runtime",
3
- "version": "0.0.145",
3
+ "version": "0.0.146",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ShaulLavo/waffle.git",
@@ -32,6 +32,7 @@
32
32
  "Cargo.lock",
33
33
  "rust-toolchain.toml",
34
34
  "network",
35
+ "README.md",
35
36
  "LICENSE",
36
37
  "LICENSES"
37
38
  ],
@@ -588,6 +589,13 @@
588
589
  "browser": "./programs/catalog.ts",
589
590
  "default": "./programs/catalog.ts"
590
591
  },
592
+ "./command": {
593
+ "types": "./proc/start-command.ts",
594
+ "node": "./dist/proc/start-command.js",
595
+ "bun": "./proc/start-command.ts",
596
+ "browser": "./proc/start-command.ts",
597
+ "default": "./proc/start-command.ts"
598
+ },
591
599
  "./proc/command": {
592
600
  "types": "./proc/command.ts",
593
601
  "node": "./dist/proc/command.js",
@@ -0,0 +1,96 @@
1
+ import {
2
+ BigInt64ArrayConstructor,
3
+ Int32ArrayConstructor,
4
+ Uint8ArrayConstructor,
5
+ atomicsCompareExchange,
6
+ atomicsLoad,
7
+ atomicsStore,
8
+ encodeUtf8Prefix,
9
+ decodeUtf8,
10
+ typedArraySet,
11
+ typedArrayLength,
12
+ } from "./intrinsics.js";
13
+ import { packedControl, TaggedCells } from "./control.js";
14
+ import {
15
+ directoryCapacity,
16
+ directoryProcessValidity,
17
+ wakeDirectory,
18
+ type DirectoryHandle,
19
+ } from "./directory.js";
20
+ import { describeStartError } from "./start-diagnostic.js";
21
+
22
+ const HEADER_BYTES = 24;
23
+ const DIAGNOSTIC_BYTES = 1024;
24
+ const EXEC_WORDS_OFFSET = HEADER_BYTES + DIAGNOSTIC_BYTES;
25
+
26
+ interface TransferSource extends DirectoryHandle {
27
+ readonly commandTransfer?: SharedArrayBuffer;
28
+ readonly generation: number;
29
+ }
30
+
31
+ export function commandTransferBytes(directory: SharedArrayBuffer): number {
32
+ return EXEC_WORDS_OFFSET + directoryCapacity(directory) * 8;
33
+ }
34
+
35
+ /** One incarnation-tagged handoff per process slot, allocated only for a command root. */
36
+ export function commandExecTransfer(source: TransferSource): TaggedCells | undefined {
37
+ const buffer = source.commandTransfer;
38
+ if (!buffer) return;
39
+ return new TaggedCells(
40
+ new BigInt64ArrayConstructor(buffer, EXEC_WORDS_OFFSET + source.slot * 8, 1),
41
+ source.pid,
42
+ directoryProcessValidity(source),
43
+ );
44
+ }
45
+
46
+ export function initializeCommandExec(source: TransferSource): void {
47
+ const handoff = commandExecTransfer(source);
48
+ if (handoff) atomicsStore(handoff.cells, 0, packedControl(source.pid, 0));
49
+ }
50
+
51
+ /** Publication stays inside the producer's filesystem fence, even if no message was sent. */
52
+ export function recordCommandTransferFailure(
53
+ source: TransferSource,
54
+ kind: "spawn" | "exec",
55
+ target: number,
56
+ error: unknown,
57
+ ): void {
58
+ const buffer = source.commandTransfer;
59
+ if (!buffer) return;
60
+ const words = new Int32ArrayConstructor(buffer, 0, HEADER_BYTES / 4);
61
+ if (atomicsCompareExchange(words, 0, 0, -1) !== 0) return;
62
+ atomicsStore(words, 1, source.pid);
63
+ atomicsStore(words, 2, source.generation);
64
+ atomicsStore(words, 3, target);
65
+ try {
66
+ const bytes = encodeUtf8Prefix(describeStartError(error), DIAGNOSTIC_BYTES);
67
+ typedArraySet(new Uint8ArrayConstructor(buffer, HEADER_BYTES), bytes);
68
+ atomicsStore(words, 4, typedArrayLength(bytes));
69
+ } finally {
70
+ atomicsStore(words, 0, kind === "spawn" ? 1 : 2);
71
+ wakeDirectory(source.directory);
72
+ }
73
+ }
74
+
75
+ export function commandTransferFailed(buffer: SharedArrayBuffer | undefined): boolean {
76
+ return buffer !== undefined && atomicsLoad(new Int32ArrayConstructor(buffer, 0, 1), 0) !== 0;
77
+ }
78
+
79
+ export function readCommandTransferFailure(buffer: SharedArrayBuffer) {
80
+ const words = new Int32ArrayConstructor(buffer, 0, HEADER_BYTES / 4);
81
+ const operation = atomicsLoad(words, 0);
82
+ if (operation <= 0) return;
83
+ const pid = atomicsLoad(words, 1);
84
+ const generation = atomicsLoad(words, 2);
85
+ const target = atomicsLoad(words, 3);
86
+ const length = atomicsLoad(words, 4);
87
+ const cause = decodeUtf8(new Uint8ArrayConstructor(buffer, HEADER_BYTES, length));
88
+ const kind = operation === 1 ? "spawn" : "exec";
89
+ const error = new Error(
90
+ kind === "spawn"
91
+ ? `Spawn transfer to process ${target} from process ${pid} image ${generation} could not be released`
92
+ : `Exec transfer for process ${pid} image ${target} could not be released`,
93
+ { cause: new Error(cause) },
94
+ );
95
+ return { kind, pid, generation, target, error };
96
+ }
package/proc/directory.ts CHANGED
@@ -81,6 +81,12 @@ export function directoryAdmissionVersion(directory: SharedArrayBuffer): bigint
81
81
  return version;
82
82
  }
83
83
 
84
+ /** The page scope can observe an idle stamp without treating an in-flight spawn as an error. */
85
+ export function idleDirectoryAdmission(directory: SharedArrayBuffer): bigint | undefined {
86
+ const version = atomicsLoad(new BigInt64ArrayConstructor(directory, 16, 1), 0);
87
+ if ((version & 0xffffffffn) === 0n) return version;
88
+ }
89
+
84
90
  /** Linearize the owner decision against every concurrent earlier spawn intent. No freeze. */
85
91
  export function commitDirectoryAdmission(directory: SharedArrayBuffer, version: bigint): void {
86
92
  const word = new BigInt64ArrayConstructor(directory, 16, 1);
@@ -92,7 +98,7 @@ export interface DirectoryHandle {
92
98
  readonly slot: number;
93
99
  readonly pid: number;
94
100
  }
95
- function directoryCapacity(directory: SharedArrayBuffer): number {
101
+ export function directoryCapacity(directory: SharedArrayBuffer): number {
96
102
  const capacity =
97
103
  (sharedArrayBufferByteLength(directory) - HEADER_BYTES) / ((PROCESS_WORDS + JOB_WORDS) * 8);
98
104
  if (!Number.isInteger(capacity) || capacity < 1) throw new TypeError("invalid process directory");
@@ -125,6 +131,9 @@ function validity(raw: BigInt64Array, id: number): CellValidity {
125
131
  id,
126
132
  };
127
133
  }
134
+ export function directoryProcessValidity(handle: DirectoryHandle): CellValidity {
135
+ return validity(row(handle.directory, handle.slot), handle.pid);
136
+ }
128
137
  function cells(raw: BigInt64Array, id: number, offset: number, count = 1): TaggedCells {
129
138
  return new TaggedCells(typedArraySubarray(raw, offset, offset + count), id);
130
139
  }
@@ -204,7 +204,8 @@ const setDeleteMethod = Set.prototype.delete,
204
204
  setForEachMethod = Set.prototype.forEach;
205
205
  const weakMapGetMethod = WeakMap.prototype.get,
206
206
  weakMapSetMethod = WeakMap.prototype.set,
207
- weakMapHasMethod = WeakMap.prototype.has;
207
+ weakMapHasMethod = WeakMap.prototype.has,
208
+ weakMapDeleteMethod = WeakMap.prototype.delete;
208
209
  export function weakMapGet<K extends object, V>(map: WeakMap<K, V>, key: K): V | undefined {
209
210
  return apply(weakMapGetMethod, map, [key]);
210
211
  }
@@ -214,6 +215,9 @@ export function weakMapSet<K extends object, V>(map: WeakMap<K, V>, key: K, valu
214
215
  export function weakMapHas<K extends object, V>(map: WeakMap<K, V>, key: K): boolean {
215
216
  return apply(weakMapHasMethod, map, [key]);
216
217
  }
218
+ export function weakMapDelete<K extends object, V>(map: WeakMap<K, V>, key: K): boolean {
219
+ return apply(weakMapDeleteMethod, map, [key]);
220
+ }
217
221
  export function setHas<T>(set: ReadonlySet<T>, value: T): boolean {
218
222
  return apply(setHasMethod, set, [value]);
219
223
  }
@@ -90,6 +90,7 @@ export {
90
90
  weakMapGet,
91
91
  weakMapSet,
92
92
  weakMapHas,
93
+ weakMapDelete,
93
94
  setHas,
94
95
  setAdd,
95
96
  setDelete,