@mostra/runtime 0.6.0 → 0.6.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/runtime",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "The Mostra runtime: the supervisor that owns a home, its ledger, its child processes and the host protocol server (mostra-runtime host|daemon).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -34,38 +34,38 @@
34
34
  "provenance": true
35
35
  },
36
36
  "dependencies": {
37
- "@hono/node-server": "2.1.3",
37
+ "@hono/node-server": "2.1.5",
38
38
  "@mdx-js/mdx": "3.1.1",
39
- "@mostra/protocol": "0.6.0",
39
+ "@mostra/protocol": "0.6.2",
40
40
  "@tailwindcss/vite": "4.3.3",
41
- "@vitejs/plugin-react": "6.1.1",
41
+ "@vitejs/plugin-react": "6.1.2",
42
42
  "better-sqlite3": "13.0.3",
43
43
  "hono": "4.13.13",
44
- "ignore": "7.0.12",
45
- "oxc-parser": "0.152.0",
46
- "pnpm": "10.34.6",
44
+ "ignore": "7.0.13",
45
+ "oxc-parser": "0.155.0",
46
+ "pnpm": "10.34.7",
47
47
  "remark-frontmatter": "5.0.0",
48
48
  "remark-gfm": "4.0.1",
49
49
  "semver": "7.8.5",
50
50
  "tailwindcss": "4.3.3",
51
51
  "typescript": "7.0.2",
52
- "vite": "8.3.3",
52
+ "vite": "8.3.4",
53
53
  "yaml": "2.9.1",
54
- "zod": "4.6.6"
54
+ "zod": "4.6.7"
55
55
  },
56
56
  "devDependencies": {
57
- "@mostra/shell": "0.6.0",
57
+ "@mostra/shell": "0.6.2",
58
58
  "@mostra/tools": "0.0.0",
59
- "@mostra/verify": "0.6.0",
59
+ "@mostra/verify": "0.6.2",
60
60
  "@mostra/warm": "0.0.0",
61
- "@mostra/worker": "0.6.0",
61
+ "@mostra/worker": "0.6.2",
62
62
  "@types/better-sqlite3": "9.6.0",
63
- "@types/node": "24.19.1",
63
+ "@types/node": "24.19.2",
64
64
  "@types/semver": "7.8.0",
65
65
  "fast-check": "4.10.2",
66
- "playwright": "1.64.0",
67
- "tsdown": "0.23.0",
68
- "vitest": "5.0.3"
66
+ "playwright": "1.64.1",
67
+ "tsdown": "0.23.1",
68
+ "vitest": "5.0.5"
69
69
  },
70
70
  "keywords": [
71
71
  "mostra",
package/src/bin.ts CHANGED
@@ -103,7 +103,18 @@ function handleSignals(instance: Instance): void {
103
103
  process.on("exit", () => instance.processes.killAll());
104
104
  process.on("uncaughtException", (error) => {
105
105
  mirror(`${JSON.stringify({ level: "error", event: "uncaught", message: error.message })}\n`);
106
- void instance.stop("uncaught exception", EXIT.failure);
106
+ // The home's log keeps what failed and where, so a failure nobody watched stderr for still
107
+ // names its cause (#35: an instance that ended with only "uncaught exception" in its log).
108
+ void instance.stop(
109
+ "uncaught exception",
110
+ EXIT.failure,
111
+ createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", {
112
+ message: (error instanceof Error
113
+ ? (error.stack ?? `${error.name}: ${error.message}`)
114
+ : String(error)
115
+ ).slice(0, 8192),
116
+ }),
117
+ );
107
118
  setTimeout(() => process.exit(EXIT.failure), 15_000).unref();
108
119
  });
109
120
  }
package/src/dev/index.ts CHANGED
@@ -405,15 +405,34 @@ export function createDev(options: DevOptions): Dev {
405
405
  );
406
406
 
407
407
  // The session ends with its connection (D140 item 12), from the first moment: a connection
408
- // that closes while packages resolve or the dev server starts leaves nothing running.
409
- connection.signal.addEventListener("abort", () => void stop(), { once: true });
408
+ // that closes while packages resolve or the dev server starts leaves nothing running. While
409
+ // the session starts, its start owns the cleanup: a close marks it, and the start stops what
410
+ // it started at its next step, then removes the session's directory. A close that removed
411
+ // the directory at once did so under a dev server still writing into it (its staging files,
412
+ // its `node_modules` link, Vite's cache), the removal failed on the files it wrote, and the
413
+ // failure took the whole instance down (#35). Once started, a close stops the session, and
414
+ // a stop that fails is logged: it never ends the instance.
415
+ let starting = true;
416
+ connection.signal.addEventListener(
417
+ "abort",
418
+ () => {
419
+ if (starting) closed = true;
420
+ else stop().catch((error: unknown) => log.warn("dev.stop_failed", { sessionId, error }));
421
+ },
422
+ { once: true },
423
+ );
410
424
  try {
411
425
  if (connection.signal.aborted) throw abandoned();
426
+ // A close stops the start at its next step, before resolving packages least of all, which
427
+ // may install under the shared gate (the Opus review of MT-02).
412
428
  await sync();
429
+ if (closed) throw abandoned();
413
430
  const described = await describe();
431
+ if (closed) throw abandoned();
414
432
  manifestKey = JSON.stringify(described.manifest);
415
433
  nodeModules = await resolve(described.manifest.id);
416
434
  artifactId = described.artifactId;
435
+ if (closed) throw abandoned();
417
436
  child = await startChild(described);
418
437
  if (closed) throw abandoned();
419
438
  const upstream = (): { port: number; secret: string } | undefined =>
@@ -438,13 +457,16 @@ export function createDev(options: DevOptions): Dev {
438
457
  ...(params.port !== undefined ? { shellPort: params.port } : {}),
439
458
  });
440
459
  if (closed) throw abandoned();
460
+ // Nothing below awaits, so no close can fall between this and the session's registration.
461
+ starting = false;
441
462
  sandbox.onSubmission((results) => notify("submission", { results }));
442
463
  } catch (error) {
443
464
  closed = true;
444
465
  sessions.delete(sessionId);
445
- // Again, after whatever a stop that ran meanwhile couldn't see yet (a child or sandbox
446
- // that finished starting after it).
466
+ // Every step that started something has returned, so nothing writes into the session's
467
+ // directory once its dev server and sandbox stopped.
447
468
  await release();
469
+ if (connection.signal.aborted) log.info("dev.stopped", { sessionId });
448
470
  throw error;
449
471
  }
450
472
 
@@ -125,6 +125,11 @@ export interface GatewayOptions {
125
125
  readonly via: IdentityVia;
126
126
  readonly headers: Headers;
127
127
  }) => Promise<IdentityOutcome>;
128
+ /**
129
+ * Logs every connection and request of every listener (`MOSTRA_TEST_REQUEST_LOG`, #66): tests
130
+ * only, so a request a browser saw go unanswered shows whether it reached the gateway.
131
+ */
132
+ readonly traceRequests?: boolean;
128
133
  /** The browser-protocol revisions served; `BROWSER_PROTOCOL_REVISIONS` unless a test adds one. */
129
134
  readonly revisions?: readonly string[];
130
135
  /**
@@ -1042,6 +1047,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1042
1047
  artifactRoutes(artifactId, () => port),
1043
1048
  ),
1044
1049
  ...(options.dev ? { upgrade: devSocket(artifactId, () => port) } : {}),
1050
+ ...(options.traceRequests ? { traceRequests: true } : {}),
1045
1051
  });
1046
1052
  port = await addressing.listen(listener.server, { purpose: "artifact", owner: artifactId });
1047
1053
  artifactListeners.set(artifactId, { listener, port });
@@ -1102,6 +1108,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1102
1108
  log,
1103
1109
  frameAncestors: () => "'none'",
1104
1110
  configure: (app) => mount(app, shellChecks, shellRoutes),
1111
+ ...(options.traceRequests ? { traceRequests: true } : {}),
1105
1112
  });
1106
1113
  shellPort = await addressing.listen(shellListener.server, {
1107
1114
  purpose: "shell",
@@ -6,6 +6,7 @@
6
6
  * theirs, WP-22), and every response leaves with the base headers.
7
7
  */
8
8
  import { createServer, type IncomingMessage, type Server } from "node:http";
9
+ import type { Socket } from "node:net";
9
10
  import type { Duplex } from "node:stream";
10
11
  import { getRequestListener } from "@hono/node-server";
11
12
  import {
@@ -29,6 +30,15 @@ import { refuse } from "./routes.ts";
29
30
  */
30
31
  export const MAX_HEADER_SIZE: number = 1024 * 1024;
31
32
 
33
+ /**
34
+ * How long a listener keeps an idle connection open: longer than browsers keep theirs (Chromium
35
+ * 300 s, Firefox 115 s), so the browser reuses its connections and closes them itself (D157 item
36
+ * 2). Node's default, 5 s, made the gateway close first, and each connection it closed stayed in
37
+ * TIME_WAIT on its side, where Chromium's random local ports on Windows collided with it and
38
+ * failed the connect at once with `ERR_NO_BUFFER_SPACE` (#66).
39
+ */
40
+ export const KEEP_ALIVE_MS: number = 305_000;
41
+
32
42
  /** A listener: its server and its Hono app. */
33
43
  export interface Listener {
34
44
  readonly server: Server;
@@ -114,6 +124,53 @@ function headersTooLarge(socket: Duplex): void {
114
124
  });
115
125
  }
116
126
 
127
+ /**
128
+ * Records every connection and request of a listener in the supervisor's log: its arrival and its
129
+ * end, whether it was answered, with the time between them and the client's port, so a request a
130
+ * browser saw go unanswered shows whether it ever reached the gateway (#66). Only a request's
131
+ * method and path are kept, never its query (a frame ticket travels there) or its headers; a test
132
+ * switch (`MOSTRA_TEST_REQUEST_LOG`), since a long-lived daemon would log every asset it serves.
133
+ */
134
+ function traceRequests(server: Server, log: Log, origin: () => string): void {
135
+ server.on("connection", (socket: Socket) => {
136
+ const opened = Date.now();
137
+ const client = socket.remotePort;
138
+ log.info("gateway.connection", { origin: origin(), client });
139
+ socket.once("close", (hadError: boolean) =>
140
+ log.info("gateway.connection_closed", {
141
+ origin: origin(),
142
+ client,
143
+ ms: Date.now() - opened,
144
+ read: socket.bytesRead,
145
+ written: socket.bytesWritten,
146
+ ...(hadError ? { hadError } : {}),
147
+ }),
148
+ );
149
+ });
150
+ server.prependListener("request", (incoming: IncomingMessage, outgoing) => {
151
+ const started = Date.now();
152
+ const fields = {
153
+ origin: origin(),
154
+ client: incoming.socket.remotePort,
155
+ method: incoming.method,
156
+ path: (incoming.url ?? "").replace(/[?#].*$/s, ""),
157
+ };
158
+ log.info("gateway.request", fields);
159
+ // `finished`: the whole answer was handed to the connection. A stream (events, a long poll)
160
+ // the browser leaves ends unfinished with its headers sent; a request that got nothing ends
161
+ // with neither.
162
+ outgoing.once("close", () =>
163
+ log.info("gateway.request_closed", {
164
+ ...fields,
165
+ status: outgoing.statusCode,
166
+ headersSent: outgoing.headersSent,
167
+ finished: outgoing.writableFinished,
168
+ ms: Date.now() - started,
169
+ }),
170
+ );
171
+ });
172
+ }
173
+
117
174
  /** Creates a listener whose routes `configure` mounts; the server isn't bound yet. */
118
175
  export function createListener(options: {
119
176
  readonly policy: () => RequestPolicy;
@@ -129,6 +186,8 @@ export function createListener(options: {
129
186
  socket: Duplex,
130
187
  head: Buffer,
131
188
  ) => Refusal | undefined;
189
+ /** Logs every connection and request ({@link traceRequests}): tests only. */
190
+ readonly traceRequests?: boolean;
132
191
  }): Listener {
133
192
  const app = new Hono<HttpEnv>();
134
193
  options.configure(app);
@@ -194,6 +253,7 @@ export function createListener(options: {
194
253
  }
195
254
  void listener(incoming, outgoing);
196
255
  });
256
+ if (options.traceRequests) traceRequests(server, options.log, () => options.policy().origin);
197
257
  // A client that sends something Node can't parse gets a 400 and its connection closed.
198
258
  server.on("clientError", (error: NodeJS.ErrnoException, socket) => {
199
259
  if (refusedSockets.has(socket)) return;
@@ -239,6 +299,9 @@ export function createListener(options: {
239
299
  });
240
300
  server.headersTimeout = 30_000;
241
301
  server.requestTimeout = 120_000;
302
+ // An idle connection waits for its next request without these two limits, which count from a
303
+ // request's first byte.
304
+ server.keepAliveTimeout = KEEP_ALIVE_MS;
242
305
 
243
306
  return {
244
307
  server,
@@ -611,9 +611,12 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
611
611
  const shellDir = locateShell(environment);
612
612
  if (shellDir === undefined)
613
613
  log.warn("gateway.shell_missing", { code: "MOSTRA_ENV_SHELL_MISSING" });
614
+ const traceRequests = Boolean(environment["MOSTRA_TEST_REQUEST_LOG"]);
615
+ if (traceRequests) log.warn("instance.test_request_log", {});
614
616
  const gateway: Gateway = createGateway({
615
617
  ledger: home.ledger,
616
618
  log,
619
+ ...(traceRequests ? { traceRequests } : {}),
617
620
  addressing,
618
621
  capabilities,
619
622
  artifacts: {
@@ -844,7 +847,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
844
847
  stopped,
845
848
  stop(reason, exitCode = 0, diagnostic) {
846
849
  stopping ??= (async () => {
847
- log.info("instance.stopping", { reason, exitCode });
850
+ log.info("instance.stopping", { reason, exitCode, ...(diagnostic ? { diagnostic } : {}) });
848
851
  idle?.stop();
849
852
  stopWatchingPublishes();
850
853
  live.stop();