@waffle-os/runtime 0.0.155 → 0.0.157

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 (77) hide show
  1. package/browser/filesystem-backend.ts +11 -1
  2. package/browser/preview-protocol.ts +2 -0
  3. package/browser/preview.ts +128 -18
  4. package/browser/runtime-terminals.ts +65 -24
  5. package/browser/shared-fs.ts +141 -14
  6. package/browser/worker.ts +73 -6
  7. package/core/descriptors.ts +19 -2
  8. package/core/devices.ts +237 -2
  9. package/core/fd-reopen.ts +105 -20
  10. package/core/filesystem.ts +79 -0
  11. package/core/index.ts +4 -0
  12. package/core/open-file.ts +212 -18
  13. package/core/wasi.ts +449 -47
  14. package/dist/browser/filesystem-backend.js +4 -2
  15. package/dist/browser/preview.js +120 -17
  16. package/dist/browser/runtime-terminals.js +53 -10
  17. package/dist/browser/shared-fs.js +124 -11
  18. package/dist/browser/worker.js +59 -6
  19. package/dist/core/descriptors.js +9 -1
  20. package/dist/core/devices.js +211 -1
  21. package/dist/core/fd-reopen.js +79 -18
  22. package/dist/core/filesystem.js +14 -0
  23. package/dist/core/open-file.js +166 -13
  24. package/dist/core/wasi.js +402 -29
  25. package/dist/fs/backend.js +51 -3
  26. package/dist/fs/client.js +204 -7
  27. package/dist/fs/cold-read-cache.js +23 -0
  28. package/dist/fs/index.js +21 -1
  29. package/dist/fs/indexeddb.js +30 -2
  30. package/dist/fs/locks.js +1112 -0
  31. package/dist/fs/memory.js +126 -2
  32. package/dist/fs/multitab-backend.js +317 -196
  33. package/dist/fs/multitab-protocol.js +2 -0
  34. package/dist/fs/persistent.js +32 -7
  35. package/dist/fs/protocol.js +9 -3
  36. package/dist/fs/service.js +387 -22
  37. package/dist/fs/shared.js +54 -1
  38. package/dist/fs/storage-geometry.js +2 -0
  39. package/dist/interrupt/rewriter-internal.js +4 -1
  40. package/dist/proc/abi.js +80 -6
  41. package/dist/proc/errors.js +1 -0
  42. package/dist/proc/filesystem-codec.js +40 -9
  43. package/dist/proc/index.js +10 -1
  44. package/dist/proc/pty.js +193 -0
  45. package/dist/proc/worker-client.js +11 -2
  46. package/dist/proc/worker-pipes.js +51 -0
  47. package/dist/runtime.js +11 -2
  48. package/dist/search/engine.js +53 -0
  49. package/dist/tooling/program/program-transformer.json +1 -1
  50. package/fs/backend.ts +54 -2
  51. package/fs/client.ts +230 -6
  52. package/fs/cold-read-cache.ts +38 -0
  53. package/fs/index.ts +22 -1
  54. package/fs/indexeddb.ts +36 -2
  55. package/fs/locks.ts +1406 -0
  56. package/fs/memory.ts +132 -1
  57. package/fs/multitab-backend.ts +563 -304
  58. package/fs/multitab-protocol.ts +2 -0
  59. package/fs/persistent.ts +46 -4
  60. package/fs/protocol.ts +17 -5
  61. package/fs/service.ts +469 -23
  62. package/fs/shared.ts +60 -2
  63. package/fs/storage-geometry.ts +3 -0
  64. package/index.ts +2 -0
  65. package/interrupt/rewriter-internal.ts +4 -1
  66. package/package.json +2 -2
  67. package/proc/abi.ts +79 -6
  68. package/proc/errors.ts +1 -0
  69. package/proc/filesystem-codec.ts +39 -9
  70. package/proc/index.ts +11 -0
  71. package/proc/pty.ts +227 -0
  72. package/proc/worker-client.ts +28 -6
  73. package/proc/worker-pipes.ts +57 -0
  74. package/runtime.ts +12 -2
  75. package/search/engine.ts +49 -0
  76. package/testing/indexeddb-storage-browser.ts +173 -2
  77. package/tooling/program/program-transformer.json +1 -1
@@ -18,6 +18,7 @@ export interface FilesystemBackendOptions {
18
18
  readonly implementation?: "indexeddb" | "opfs-memory" | "memory";
19
19
  readonly startupRoot?: MemoryBudget;
20
20
  readonly connect?: MemoryBackendSharedRoot;
21
+ readonly machineId?: string;
21
22
  }
22
23
  export interface FilesystemBackendLifecycle {
23
24
  readonly retainOpeningDebt?: (debt: Promise<void>) => void;
@@ -37,7 +38,14 @@ export async function openFilesystemBackend(
37
38
  const { descriptor, whenBusy } = resolveVfs(options, options.implementation);
38
39
  requireVfsCapabilities(descriptor.implementation, whenBusy);
39
40
  if (descriptor.implementation === "memory")
40
- return new MemoryBackend(undefined, undefined, options.startupRoot, undefined, options.connect);
41
+ return new MemoryBackend(
42
+ undefined,
43
+ undefined,
44
+ options.startupRoot,
45
+ undefined,
46
+ options.connect,
47
+ options.machineId,
48
+ );
41
49
  if (whenBusy === "attach") {
42
50
  const { MultiTabBackend } = await import("../fs/multitab-backend.js");
43
51
  return MultiTabBackend.open({
@@ -45,6 +53,7 @@ export async function openFilesystemBackend(
45
53
  name: options.name ?? "waffle-workspace",
46
54
  startupRoot: options.startupRoot,
47
55
  sharedRoot: options.connect,
56
+ machineId: options.machineId,
48
57
  onStartupStage: lifecycle.onStartupStage,
49
58
  signal: lifecycle.signal,
50
59
  onWaiting: lifecycle.onWaiting,
@@ -71,6 +80,7 @@ export async function openFilesystemBackend(
71
80
  backend = await PersistentBackend.open(storage, {
72
81
  startupRoot: options.startupRoot,
73
82
  sharedRoot: options.connect,
83
+ machineId: options.machineId,
74
84
  });
75
85
  if (ownershipLost) {
76
86
  backend.dispose();
@@ -13,6 +13,8 @@ export type PreviewReply =
13
13
  | { type: "accepted" }
14
14
  | { type: "head"; status: number; statusText: string; headers: [string, string][] }
15
15
  | { type: "data"; chunk: Uint8Array }
16
+ | { type: "ping" }
17
+ | { type: "pong" }
16
18
  | { type: "end" }
17
19
  | { type: "error"; message: string };
18
20
 
@@ -22,7 +22,14 @@ export interface PreviewServer {
22
22
  connect(port: number, sink: ConnectionSink): PreviewConnection | null;
23
23
  }
24
24
 
25
- interface MountPreviewOptions {
25
+ interface SocketLivenessOptions {
26
+ /** Interval in ms between liveness pings on open socket tunnels (0 disables). Default 15000. */
27
+ readonly socketPingIntervalMs?: number;
28
+ /** Consecutive unanswered pings before closing a silent socket tunnel. Default 3. */
29
+ readonly socketMissedPings?: number;
30
+ }
31
+
32
+ interface MountPreviewOptions extends SocketLivenessOptions {
26
33
  baseURL: string;
27
34
  /** Consumer-owned mount directory, relative to baseURL (without a trailing slash). */
28
35
  prefix: string;
@@ -30,12 +37,16 @@ interface MountPreviewOptions {
30
37
 
31
38
  export type PreviewOptions =
32
39
  | MountPreviewOptions
33
- | { mode: "root"; originForPort(port: number): string };
40
+ | ({ mode: "root"; originForPort(port: number): string } & SocketLivenessOptions);
41
+
42
+ const DEFAULT_SOCKET_PING_MS = 15_000;
43
+ const DEFAULT_SOCKET_MISSED_PINGS = 3;
34
44
 
35
45
  /** Page-side request/socket routing. The consumer owns service-worker registration. */
36
46
  export class PreviewRouter {
37
47
  private servers = new Map<number, PreviewServer>();
38
48
  private hosts = new Map<number, PreviewHostRelay>();
49
+ private sockets = new Map<number, Set<() => void>>();
39
50
  private owner: string | undefined;
40
51
  constructor(private options: PreviewOptions) {}
41
52
 
@@ -85,6 +96,29 @@ export class PreviewRouter {
85
96
  return host;
86
97
  }
87
98
 
99
+ private closePortSockets(port: number): void {
100
+ const active = this.sockets.get(port);
101
+ if (!active) return;
102
+ this.sockets.delete(port);
103
+ for (const close of Array.from(active)) close();
104
+ }
105
+
106
+ /** Close every active host relay and open socket tunnel owned by this router. */
107
+ close(): void {
108
+ const errors: unknown[] = [];
109
+ for (const port of Array.from(this.sockets.keys())) this.closePortSockets(port);
110
+ for (const [port, host] of Array.from(this.hosts)) {
111
+ this.hosts.delete(port);
112
+ try {
113
+ host.close();
114
+ } catch (error) {
115
+ errors.push(error);
116
+ }
117
+ }
118
+ if (errors.length === 1) throw errors[0];
119
+ if (errors.length > 1) throw new AggregateError(errors, "PreviewRouter close failed");
120
+ }
121
+
88
122
  serves(port: number): boolean {
89
123
  return this.servers.has(port);
90
124
  }
@@ -92,6 +126,7 @@ export class PreviewRouter {
92
126
  if (this.servers.get(port) === server) return;
93
127
  const previous = this.hosts.get(port);
94
128
  this.hosts.delete(port);
129
+ this.closePortSockets(port);
95
130
  this.servers.set(port, server);
96
131
  previous?.close();
97
132
  }
@@ -100,6 +135,7 @@ export class PreviewRouter {
100
135
  this.servers.delete(port);
101
136
  const previous = this.hosts.get(port);
102
137
  this.hosts.delete(port);
138
+ this.closePortSockets(port);
103
139
  previous?.close();
104
140
  }
105
141
 
@@ -107,46 +143,120 @@ export class PreviewRouter {
107
143
  const pending: { message: PreviewReply; transfer: Transferable[] }[] = [];
108
144
  let ready = false;
109
145
  let finished = false;
146
+ let missedPings = 0;
110
147
  let connection: PreviewConnection | null = null;
148
+ let pingTimer: ReturnType<typeof setInterval> | undefined;
111
149
  const send = (message: PreviewReply, transfer: Transferable[] = []) => {
112
150
  if (finished) return;
113
151
  if (!ready) {
114
152
  pending.push({ message, transfer });
115
153
  return;
116
154
  }
117
- reply.postMessage(message, transfer);
155
+ try {
156
+ reply.postMessage(message, transfer);
157
+ } catch {
158
+ closeTunnel();
159
+ }
118
160
  };
119
- const finish = (message: PreviewReply) => {
120
- send(message);
161
+ const onPeerClose = () => closeTunnel();
162
+ let closing = false;
163
+ const closeTunnel = (finalMessage?: PreviewReply) => {
164
+ if (finished) return;
165
+ if (finalMessage) {
166
+ send(finalMessage);
167
+ finished = true;
168
+ }
169
+ if (closing) return;
170
+ closing = true;
171
+ if (pingTimer !== undefined) {
172
+ clearInterval(pingTimer);
173
+ pingTimer = undefined;
174
+ }
175
+ this.sockets.get(port)?.delete(closeTunnel);
176
+ reply.removeEventListener?.("close", onPeerClose);
177
+ reply.onmessage = null;
178
+ const activeConnection = connection;
179
+ connection = null;
180
+ try {
181
+ activeConnection?.close();
182
+ } catch {}
121
183
  finished = true;
122
184
  if (ready) reply.close();
123
185
  };
186
+ reply.addEventListener?.("close", onPeerClose);
124
187
  reply.onmessage = (event: MessageEvent<unknown>) => {
125
188
  const message = event.data;
126
- if (!message || typeof message !== "object" || !("type" in message) || !connection) return;
127
- if (message.type === "data" && "chunk" in message && message.chunk instanceof Uint8Array)
128
- connection.write(message.chunk);
189
+ if (!message || typeof message !== "object" || !("type" in message)) return;
190
+ missedPings = 0;
191
+ if (message.type === "ping") {
192
+ send({ type: "pong" });
193
+ return;
194
+ }
195
+ if (message.type === "pong") return;
129
196
  if (message.type === "end") {
130
- connection.close();
131
- reply.close();
197
+ closeTunnel();
198
+ return;
199
+ }
200
+ if (
201
+ message.type === "data" &&
202
+ "chunk" in message &&
203
+ message.chunk instanceof Uint8Array &&
204
+ connection
205
+ ) {
206
+ connection.write(message.chunk);
132
207
  }
133
208
  };
134
- connection =
209
+ const opened =
135
210
  this.servers.get(port)?.connect(port, {
136
211
  data: (chunk) => send({ type: "data", chunk }, [chunk.buffer]),
137
- end: () => finish({ type: "end" }),
138
- error: (message) => finish({ type: "error", message }),
212
+ end: () => closeTunnel({ type: "end" }),
213
+ error: (message) => closeTunnel({ type: "error", message }),
139
214
  }) ?? null;
140
- if (!connection) {
215
+ if (!opened) {
141
216
  ready = true;
142
- finish({ type: "error", message: "no server" });
217
+ closeTunnel({ type: "error", message: "no server" });
143
218
  return;
144
219
  }
220
+ if (finished) {
221
+ try {
222
+ opened.close();
223
+ } catch {}
224
+ } else {
225
+ connection = opened;
226
+ let portSockets = this.sockets.get(port);
227
+ if (!portSockets) {
228
+ portSockets = new Set();
229
+ this.sockets.set(port, portSockets);
230
+ }
231
+ portSockets.add(closeTunnel);
232
+ }
145
233
  ready = true;
146
- reply.postMessage({ type: "accepted" });
147
- for (const item of pending) reply.postMessage(item.message, item.transfer);
234
+ try {
235
+ reply.postMessage({ type: "accepted" });
236
+ for (const item of pending) reply.postMessage(item.message, item.transfer);
237
+ } catch {
238
+ pending.length = 0;
239
+ closeTunnel();
240
+ return;
241
+ }
148
242
  pending.length = 0;
149
- if (finished) reply.close();
243
+ if (finished) {
244
+ reply.close();
245
+ return;
246
+ }
247
+ const pingIntervalMs = this.options.socketPingIntervalMs ?? DEFAULT_SOCKET_PING_MS;
248
+ const maxMissedPings = this.options.socketMissedPings ?? DEFAULT_SOCKET_MISSED_PINGS;
249
+ if (pingIntervalMs > 0 && maxMissedPings > 0) {
250
+ pingTimer = setInterval(() => {
251
+ if (finished) return;
252
+ if (missedPings >= maxMissedPings) {
253
+ closeTunnel();
254
+ return;
255
+ }
256
+ missedPings++;
257
+ send({ type: "ping" });
258
+ }, pingIntervalMs);
259
+ }
150
260
  }
151
261
 
152
262
  onMessage(event: Pick<MessageEvent<PreviewMessage>, "data" | "ports">): void {
@@ -1,10 +1,24 @@
1
1
  // Original browser adapter: terminal destinations are host sinks, not shared pipe rings.
2
2
  import { OpenDescription, type DescriptorTable, type Stream } from "../core/descriptors.js";
3
- import { createNullDevice } from "../core/devices.js";
3
+ import {
4
+ createMachineIdFile,
5
+ createNullDevice,
6
+ isValidMachineId,
7
+ shareMachineIdOffset,
8
+ } from "../core/devices.js";
4
9
  import { guardedStream } from "./guarded-stream.js";
5
10
  import { ProcessError } from "../proc/types.js";
11
+ import { PtyEndpoint } from "../proc/pty.js";
6
12
  import type { WorkerDescriptorCodec } from "../proc/worker-client.js";
7
- import { WeakMapConstructor, weakMapGet, weakMapHas, weakMapSet } from "../proc/intrinsics.ts";
13
+ import {
14
+ isInstance,
15
+ isSharedArrayBuffer,
16
+ sharedArrayBufferByteLength,
17
+ WeakMapConstructor,
18
+ weakMapGet,
19
+ weakMapHas,
20
+ weakMapSet,
21
+ } from "../proc/intrinsics.ts";
8
22
  import { hostTerminalStream, type RuntimeTerminalOutput } from "./terminal-output.js";
9
23
 
10
24
  type TerminalTarget = 0 | 1 | 2;
@@ -18,6 +32,12 @@ interface NullDeviceToken {
18
32
  kind: "null-device";
19
33
  fdflags: number;
20
34
  }
35
+ interface MachineIdFileToken {
36
+ kind: "machine-id-file";
37
+ machineId: string;
38
+ offset: SharedArrayBuffer;
39
+ fdflags: number;
40
+ }
21
41
  // A remapped fd is not a new destination. Imported terminals retain their provenance across
22
42
  // codec instances and later generations; WeakMap entries disappear with their local streams.
23
43
  const targets = new WeakMapConstructor<Stream, TerminalTarget>();
@@ -45,32 +65,41 @@ export interface RuntimeTerminalCodecOptions {
45
65
  resolveTerminal?(target: TerminalTarget): Stream | undefined;
46
66
  checkActive?(): void;
47
67
  }
48
- function nullDeviceToken(value: unknown): NullDeviceToken | undefined {
49
- if (
50
- typeof value !== "object" ||
51
- value === null ||
52
- !("kind" in value) ||
53
- value.kind !== "null-device"
54
- )
55
- return;
56
- const fdflags = "fdflags" in value ? value.fdflags : undefined;
68
+ function hasTokenKind(value: unknown, kind: string): value is Record<string, unknown> {
69
+ return typeof value === "object" && value !== null && "kind" in value && value.kind === kind;
70
+ }
71
+
72
+ function validateFdflags(value: Record<string, unknown>, label: string): number {
73
+ const fdflags = value.fdflags;
57
74
  if (typeof fdflags !== "number" || !Number.isInteger(fdflags) || fdflags < 0 || fdflags > 31)
58
- throw new TypeError("invalid null device flags");
59
- return value as NullDeviceToken;
75
+ throw new TypeError(`invalid ${label} flags`);
76
+ return fdflags;
77
+ }
78
+
79
+ function nullDeviceToken(value: unknown): NullDeviceToken | undefined {
80
+ if (!hasTokenKind(value, "null-device")) return;
81
+ validateFdflags(value, "null device");
82
+ return value as unknown as NullDeviceToken;
83
+ }
84
+
85
+ function machineIdFileToken(value: unknown): MachineIdFileToken | undefined {
86
+ if (!hasTokenKind(value, "machine-id-file")) return;
87
+ const machineId = value.machineId;
88
+ if (typeof machineId !== "string" || !isValidMachineId(machineId))
89
+ throw new TypeError("invalid machine-id file token");
90
+ const offset = value.offset;
91
+ if (!isSharedArrayBuffer(offset) || sharedArrayBufferByteLength(offset) !== 8)
92
+ throw new TypeError("invalid machine-id file offset");
93
+ validateFdflags(value, "machine-id file");
94
+ return value as unknown as MachineIdFileToken;
60
95
  }
61
96
 
62
97
  function terminalToken(value: unknown): TerminalToken | undefined {
63
- if (
64
- typeof value !== "object" ||
65
- value === null ||
66
- !("kind" in value) ||
67
- value.kind !== "web-terminal"
68
- )
69
- return;
70
- if (!("target" in value) || (value.target !== 0 && value.target !== 1 && value.target !== 2))
98
+ if (!hasTokenKind(value, "web-terminal")) return;
99
+ if (value.target !== 0 && value.target !== 1 && value.target !== 2)
71
100
  throw new TypeError("invalid browser terminal target");
72
101
  if ("pipe" in value && value.pipe !== true) throw new TypeError("invalid browser terminal kind");
73
- return value as TerminalToken;
102
+ return value as unknown as TerminalToken;
74
103
  }
75
104
  function resolveTerminal(
76
105
  options: RuntimeTerminalCodecOptions,
@@ -100,10 +129,17 @@ export function createRuntimeTerminalCodec(
100
129
  const resource = descriptor.resource;
101
130
  if (resource.kind === "device" && resource.device === "null")
102
131
  return { kind: "null-device", fdflags: resource.fdflags ?? 0 } satisfies NullDeviceToken;
132
+ if (resource.kind === "device" && resource.device === "machine-id" && resource.virtualFile)
133
+ return {
134
+ kind: "machine-id-file",
135
+ machineId: resource.virtualFile.machineId,
136
+ offset: shareMachineIdOffset(resource.virtualFile),
137
+ fdflags: resource.fdflags ?? 0,
138
+ } satisfies MachineIdFileToken;
103
139
  if (resource.kind !== "terminal" && resource.kind !== "pipe")
104
140
  return options.fallback.export(descriptor, pid);
105
141
  const target = weakMapGet(targets, resource);
106
- if (target === undefined && resource.kind === "pipe")
142
+ if (target === undefined && (resource.kind === "pipe" || isInstance(resource, PtyEndpoint)))
107
143
  return options.fallback.export(descriptor, pid);
108
144
  // Arbitrary callback terminals cannot be cloned: only known destination provenance
109
145
  // transfers. A receiving executor may resolve that destination to an interactive stream.
@@ -116,6 +152,11 @@ export function createRuntimeTerminalCodec(
116
152
  import(value, pid) {
117
153
  const nullDevice = nullDeviceToken(value);
118
154
  if (nullDevice) return new OpenDescription(createNullDevice(nullDevice.fdflags));
155
+ const machineIdFile = machineIdFileToken(value);
156
+ if (machineIdFile)
157
+ return new OpenDescription(
158
+ createMachineIdFile(machineIdFile.machineId, machineIdFile.fdflags, machineIdFile.offset),
159
+ );
119
160
  const token = terminalToken(value);
120
161
  if (!token) return options.fallback.import(value, pid);
121
162
  // A pipe destination is never an interactive terminal, so it never resolves to one.
@@ -144,7 +185,7 @@ export function createRuntimeTerminalCodec(
144
185
  return new OpenDescription(stream);
145
186
  },
146
187
  discard(value) {
147
- if (nullDeviceToken(value) || terminalToken(value)) return;
188
+ if (nullDeviceToken(value) || machineIdFileToken(value) || terminalToken(value)) return;
148
189
  options.fallback.discard(value);
149
190
  },
150
191
  };