Open History to see the last commit
1import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, describe, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8import * as HttpClient from "effect/unstable/http/HttpClient";
9import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
10
11import * as DesktopConfig from "./DesktopConfig.ts";
12import * as DesktopEnvironment from "./DesktopEnvironment.ts";
13import * as DesktopObservability from "./DesktopObservability.ts";
14
15const DesktopBackendChildLogRecord = Schema.Struct({
16 message: Schema.String,
17 level: Schema.Literals(["INFO", "ERROR"]),
18 timestamp: Schema.String,
19 annotations: Schema.Record(Schema.String, Schema.Unknown),
20 spans: Schema.Record(Schema.String, Schema.Unknown),
21 fiberId: Schema.String,
22});
23
24const decodeDesktopBackendChildLogRecord = Schema.decodeEffect(
25 Schema.fromJsonString(DesktopBackendChildLogRecord),
26);
27
28const TraceRecordLine = Schema.Struct({
29 name: Schema.String,
30 attributes: Schema.Record(Schema.String, Schema.Unknown),
31 events: Schema.Array(
32 Schema.Struct({
33 name: Schema.String,
34 attributes: Schema.Record(Schema.String, Schema.Unknown),
35 }),
36 ),
37});
38
39const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
40
41const environmentInput = (baseDir: string) =>
42 ({
43 dirname: "/repo/apps/desktop/dist-electron",
44 homeDirectory: baseDir,
45 platform: "darwin",
46 processArch: "arm64",
47 appVersion: "1.2.3",
48 appPath: "/repo",
49 isPackaged: false,
50 resourcesPath: "/repo/resources",
51 runningUnderArm64Translation: false,
52 }) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
53
54const makeEnvironmentLayer = (
55 baseDir: string,
56 isDevelopment = true,
57 env: Readonly<Record<string, string | undefined>> = {},
58) =>
59 DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
60 Layer.provide(
61 Layer.mergeAll(
62 NodeServices.layer,
63 DesktopConfig.layerTest({
64 T3CODE_HOME: baseDir,
65 VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
66 ...env,
67 }),
68 ),
69 ),
70 );
71
72interface ExportedRequest {
73 readonly url: string;
74 readonly headers: Readonly<Record<string, string>>;
75 readonly body: string;
76}
77
78/** Answers every export with a 200 and keeps what was posted for assertions. */
79const collectorLayer = (requests: Array<ExportedRequest>) =>
80 Layer.succeed(
81 HttpClient.HttpClient,
82 HttpClient.make((request) =>
83 Effect.sync(() => {
84 requests.push({
85 url: request.url,
86 headers: request.headers,
87 body:
88 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
89 });
90 return HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }));
91 }),
92 ),
93 );
94
95const encodeObservabilitySettingsFile = Schema.encodeSync(
96 Schema.fromJsonString(
97 Schema.Struct({ observability: Schema.Record(Schema.String, Schema.String) }),
98 ),
99);
100
101const writeObservabilitySettings = Effect.fn(function* (
102 environmentLayer: ReturnType<typeof makeEnvironmentLayer>,
103 observability: Readonly<Record<string, string>>,
104) {
105 const fileSystem = yield* FileSystem.FileSystem;
106 const { path, serverSettingsPath } = yield* Effect.gen(function* () {
107 const environment = yield* DesktopEnvironment.DesktopEnvironment;
108 return environment;
109 }).pipe(Effect.provide(environmentLayer));
110 yield* fileSystem.makeDirectory(path.dirname(serverSettingsPath), { recursive: true });
111 yield* fileSystem.writeFileString(
112 serverSettingsPath,
113 encodeObservabilitySettingsFile({ observability }),
114 );
115});
116
117describe("DesktopObservability", () => {
118 it("advances a retained output offset instead of repeatedly copying a full head chunk", () => {
119 const maxBufferedBytes = 1024 * 1024;
120 const initial = DesktopObservability.appendBoundedOutputChunk(
121 {
122 runId: "test-run",
123 startDetails: "pid=123",
124 chunks: [],
125 byteLength: 0,
126 },
127 "stderr",
128 new Uint8Array(maxBufferedBytes),
129 );
130 const initialBackingBuffer = initial.chunks[0]?.chunk.buffer;
131
132 const next = DesktopObservability.appendBoundedOutputChunk(initial, "stderr", Uint8Array.of(1));
133
134 assert.equal(next.chunks[0]?.chunk.buffer, initialBackingBuffer);
135 assert.equal(next.chunks[0]?.offset, 1);
136 assert.equal(next.byteLength, maxBufferedBytes);
137 });
138
139 it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () =>
140 Effect.gen(function* () {
141 const fileSystem = yield* FileSystem.FileSystem;
142 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
143 prefix: "t3-desktop-observability-test-",
144 });
145 const environmentLayer = makeEnvironmentLayer(baseDir);
146 const tracePath = yield* Effect.gen(function* () {
147 const environment = yield* DesktopEnvironment.DesktopEnvironment;
148 return environment.path.join(environment.logDir, "desktop.trace.ndjson");
149 }).pipe(Effect.provide(environmentLayer));
150 const logPath = yield* Effect.gen(function* () {
151 const environment = yield* DesktopEnvironment.DesktopEnvironment;
152 return environment.path.join(environment.logDir, "desktop-main.log");
153 }).pipe(Effect.provide(environmentLayer));
154
155 yield* Effect.scoped(
156 Effect.gen(function* () {
157 yield* Effect.annotateCurrentSpan({ "desktop.test": true });
158 yield* Effect.logInfo("desktop trace event");
159 }).pipe(
160 Effect.withSpan("desktop-observability-test"),
161 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
162 ),
163 );
164
165 const records = (yield* fileSystem.readFileString(tracePath))
166 .trim()
167 .split("\n")
168 .filter((line) => line.length > 0)
169 .map((line) => decodeTraceRecordLine(line));
170 const record = records.find((entry) => entry.name === "desktop-observability-test");
171
172 assert.notEqual(record, undefined);
173 if (!record) {
174 return;
175 }
176 assert.equal(record.attributes["desktop.test"], true);
177 assert.equal(
178 record.events.some((event) => event.name === "desktop trace event"),
179 true,
180 );
181 assert.isFalse(yield* fileSystem.exists(logPath));
182 }).pipe(
183 Effect.scoped,
184 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
185 ),
186 );
187
188 it.effect("buffers backend child output and persists it only when a failure is reported", () =>
189 Effect.gen(function* () {
190 const fileSystem = yield* FileSystem.FileSystem;
191 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
192 prefix: "t3-desktop-backend-output-log-test-",
193 });
194 const environmentLayer = makeEnvironmentLayer(baseDir, false);
195 const logPath = yield* Effect.gen(function* () {
196 const environment = yield* DesktopEnvironment.DesktopEnvironment;
197 return environment.path.join(environment.logDir, "server-child.log");
198 }).pipe(Effect.provide(environmentLayer));
199 const tracePath = yield* Effect.gen(function* () {
200 const environment = yield* DesktopEnvironment.DesktopEnvironment;
201 return environment.path.join(environment.logDir, "desktop.trace.ndjson");
202 }).pipe(Effect.provide(environmentLayer));
203
204 yield* Effect.gen(function* () {
205 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
206 const outputLog = yield* factory.forInstance("primary");
207 yield* outputLog.beginSession({
208 details: "pid=123 port=3773 cwd=/repo",
209 });
210 yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
211 assert.isFalse(yield* fileSystem.exists(logPath));
212 yield* outputLog.persistFailure({ details: "code=1" });
213 yield* outputLog.beginSession({ details: "pid=456" });
214 yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n"));
215 yield* outputLog.discardSession;
216 }).pipe(
217 Effect.annotateLogs({ runId: "test-run" }),
218 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
219 );
220
221 const log = yield* fileSystem.readFileString(logPath);
222 const lines = log.trimEnd().split("\n");
223 const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
224 const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
225 const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
226
227 assert.equal(lines.length, 3);
228 assert.equal(start.message, "backend child process failure output start");
229 assert.equal(start.level, "ERROR");
230 assert.equal(start.annotations.component, "desktop-backend-child");
231 assert.equal(start.annotations.runId, "test-run");
232 assert.equal(start.annotations.instanceId, "primary");
233 assert.equal(start.annotations.phase, "START");
234 assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
235
236 assert.equal(output.message, "backend child process output");
237 assert.equal(output.level, "INFO");
238 assert.equal(output.annotations.component, "desktop-backend-child");
239 assert.equal(output.annotations.runId, "test-run");
240 assert.equal(output.annotations.instanceId, "primary");
241 assert.equal(output.annotations.stream, "stdout");
242 assert.equal(output.annotations.text, "hello server\n");
243
244 assert.equal(end.message, "backend child process failure output end");
245 assert.equal(end.level, "ERROR");
246 assert.equal(end.annotations.instanceId, "primary");
247 assert.equal(end.annotations.phase, "END");
248 assert.equal(end.annotations.details, "code=1");
249
250 const traceRecords = (yield* fileSystem.readFileString(tracePath))
251 .trim()
252 .split("\n")
253 .filter((line) => line.length > 0)
254 .map((line) => decodeTraceRecordLine(line));
255 assert.isFalse(
256 traceRecords.some(
257 (record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
258 ),
259 );
260 }).pipe(
261 Effect.scoped,
262 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
263 ),
264 );
265
266 it.effect("keeps buffering output after a non-terminal failure snapshot", () =>
267 Effect.gen(function* () {
268 const fileSystem = yield* FileSystem.FileSystem;
269 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
270 prefix: "t3-desktop-backend-output-snapshot-test-",
271 });
272 const environmentLayer = makeEnvironmentLayer(baseDir, false);
273 const logPath = yield* Effect.gen(function* () {
274 const environment = yield* DesktopEnvironment.DesktopEnvironment;
275 return environment.path.join(environment.logDir, "server-child.log");
276 }).pipe(Effect.provide(environmentLayer));
277
278 yield* Effect.gen(function* () {
279 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
280 const outputLog = yield* factory.forInstance("primary");
281 yield* outputLog.beginSession({ details: "pid=123" });
282 yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
283 yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
284 yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
285 yield* outputLog.persistFailure({ details: "code=1" });
286 }).pipe(
287 Effect.annotateLogs({ runId: "test-run" }),
288 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
289 );
290
291 const records = yield* Effect.forEach(
292 (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
293 (line) => decodeDesktopBackendChildLogRecord(line),
294 );
295 assert.equal(
296 records.some((record) => record.annotations.text === "after timeout\n"),
297 true,
298 );
299 assert.equal(records.at(-1)?.annotations.details, "code=1");
300 }).pipe(
301 Effect.scoped,
302 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
303 ),
304 );
305
306 it.effect("retains only the last mebibyte of backend child output", () =>
307 Effect.gen(function* () {
308 const fileSystem = yield* FileSystem.FileSystem;
309 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
310 prefix: "t3-desktop-backend-output-bound-test-",
311 });
312 const environmentLayer = makeEnvironmentLayer(baseDir, false);
313 const logPath = yield* Effect.gen(function* () {
314 const environment = yield* DesktopEnvironment.DesktopEnvironment;
315 return environment.path.join(environment.logDir, "server-child.log");
316 }).pipe(Effect.provide(environmentLayer));
317 const maxBufferedBytes = 1024 * 1024;
318 const discardedPrefixBytes = 128;
319 const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
320 output.fill("x".charCodeAt(0));
321 output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
322
323 yield* Effect.scoped(
324 Effect.gen(function* () {
325 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
326 const outputLog = yield* factory.forInstance("primary");
327 yield* outputLog.beginSession({ details: "pid=123" });
328 yield* outputLog.writeOutputChunk("stderr", output);
329 yield* outputLog.persistFailure({ details: "code=1" });
330 }).pipe(
331 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
332 ),
333 );
334
335 const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
336 const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
337 const text = record.annotations.text;
338 assert.equal(typeof text, "string");
339 if (typeof text !== "string") {
340 return;
341 }
342 assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
343 assert.isFalse(text.includes("y"));
344 }).pipe(
345 Effect.scoped,
346 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
347 ),
348 );
349
350 it.effect("bounds the number of retained backend child output chunks", () =>
351 Effect.gen(function* () {
352 const fileSystem = yield* FileSystem.FileSystem;
353 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
354 prefix: "t3-desktop-backend-output-chunks-test-",
355 });
356 const environmentLayer = makeEnvironmentLayer(baseDir, false);
357 const logPath = yield* Effect.gen(function* () {
358 const environment = yield* DesktopEnvironment.DesktopEnvironment;
359 return environment.path.join(environment.logDir, "server-child.log");
360 }).pipe(Effect.provide(environmentLayer));
361
362 yield* Effect.scoped(
363 Effect.gen(function* () {
364 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
365 const outputLog = yield* factory.forInstance("primary");
366 yield* outputLog.beginSession({ details: "pid=123" });
367 for (let index = 0; index < 300; index += 1) {
368 yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
369 }
370 yield* outputLog.persistFailure({ details: "code=1" });
371 }).pipe(
372 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
373 ),
374 );
375
376 const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
377 assert.equal(lines.length, 258);
378 }).pipe(
379 Effect.scoped,
380 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
381 ),
382 );
383
384 it.effect("exports main process log records to the configured logs endpoint", () => {
385 const requests: Array<ExportedRequest> = [];
386 return Effect.gen(function* () {
387 const fileSystem = yield* FileSystem.FileSystem;
388 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
389 prefix: "t3-desktop-observability-test-",
390 });
391 const environmentLayer = makeEnvironmentLayer(baseDir, true, {
392 T3CODE_OTLP_LOGS_URL: "https://collector.example.com/v1/logs",
393 T3CODE_OTLP_HEADERS: "x-scope=desktop",
394 });
395 const tracePath = yield* Effect.gen(function* () {
396 const environment = yield* DesktopEnvironment.DesktopEnvironment;
397 return environment.path.join(environment.logDir, "desktop.trace.ndjson");
398 }).pipe(Effect.provide(environmentLayer));
399
400 yield* Effect.scoped(
401 Effect.logInfo("desktop log export").pipe(
402 Effect.withSpan("desktop-log-export-test"),
403 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
404 ),
405 );
406
407 assert.lengthOf(requests, 1);
408 const [request] = requests;
409 assert.strictEqual(request?.url, "https://collector.example.com/v1/logs");
410 assert.include(request?.body ?? "", "desktop log export");
411 assert.include(request?.body ?? "", "service.runtime");
412 assert.strictEqual(request?.headers["x-scope"], "desktop");
413
414 // The log record is the export now, so the same message must not also
415 // ride along as an event on the span.
416 const record = (yield* fileSystem.readFileString(tracePath))
417 .trim()
418 .split("\n")
419 .filter((line) => line.length > 0)
420 .map((line) => decodeTraceRecordLine(line))
421 .find((entry) => entry.name === "desktop-log-export-test");
422 assert.notEqual(record, undefined);
423 assert.lengthOf(record?.events ?? [], 0);
424 }).pipe(
425 Effect.scoped,
426 Effect.provide(Layer.mergeAll(NodeServices.layer, collectorLayer(requests))),
427 );
428 });
429
430 it.effect("reads every signal endpoint from Settings when the environment names none", () => {
431 const requests: Array<ExportedRequest> = [];
432 return Effect.gen(function* () {
433 const fileSystem = yield* FileSystem.FileSystem;
434 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
435 prefix: "t3-desktop-observability-test-",
436 });
437 const environmentLayer = makeEnvironmentLayer(baseDir);
438 yield* writeObservabilitySettings(environmentLayer, {
439 otlpTracesUrl: "https://settings.example.com/v1/traces",
440 otlpLogsUrl: "https://settings.example.com/v1/logs",
441 // The main process records no metrics yet, so this endpoint must
442 // not produce a request.
443 otlpMetricsUrl: "https://settings.example.com/v1/metrics",
444 });
445
446 yield* Effect.scoped(
447 Effect.logInfo("desktop log export from settings").pipe(
448 Effect.withSpan("desktop-settings-export-test"),
449 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
450 ),
451 );
452
453 assert.deepEqual(requests.map((request) => request.url).toSorted(), [
454 "https://settings.example.com/v1/logs",
455 "https://settings.example.com/v1/traces",
456 ]);
457 assert.include(
458 requests.find((request) => request.url.endsWith("/v1/logs"))?.body ?? "",
459 "desktop log export from settings",
460 );
461 assert.include(
462 requests.find((request) => request.url.endsWith("/v1/traces"))?.body ?? "",
463 "desktop-settings-export-test",
464 );
465 }).pipe(
466 Effect.scoped,
467 Effect.provide(Layer.mergeAll(NodeServices.layer, collectorLayer(requests))),
468 );
469 });
470
471 it.effect("stays off the network when no endpoint is configured", () => {
472 const requests: Array<ExportedRequest> = [];
473 return Effect.gen(function* () {
474 const fileSystem = yield* FileSystem.FileSystem;
475 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
476 prefix: "t3-desktop-observability-test-",
477 });
478
479 yield* Effect.scoped(
480 Effect.logInfo("desktop log stays local").pipe(
481 Effect.withSpan("desktop-offline-test"),
482 Effect.provide(
483 DesktopObservability.layer.pipe(Layer.provideMerge(makeEnvironmentLayer(baseDir))),
484 ),
485 ),
486 );
487
488 assert.lengthOf(requests, 0);
489 }).pipe(
490 Effect.scoped,
491 Effect.provide(Layer.mergeAll(NodeServices.layer, collectorLayer(requests))),
492 );
493 });
494});