Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopObservability.test.ts

507 lines20.7 KB

1import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
2import desktopPackageJson from "../../package.json" with { type: "json" };
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, describe, it } from "@effect/vitest";
5import * as ConfigProvider from "effect/ConfigProvider";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as PlatformError from "effect/PlatformError";
10import * as Schema from "effect/Schema";
11import * as HttpClient from "effect/http/HttpClient";
12import * as HttpClientResponse from "effect/http/HttpClientResponse";
13​
14import * as DesktopConfig from "./DesktopConfig.ts";
15import * as DesktopEnvironment from "./DesktopEnvironment.ts";
16import * as DesktopObservability from "./DesktopObservability.ts";
17​
18const DesktopBackendChildLogRecord = Schema.Struct({
19 message: Schema.String,
20 level: Schema.Literals(["INFO", "ERROR"]),
21 timestamp: Schema.String,
22 annotations: Schema.Record(Schema.String, Schema.Unknown),
23 spans: Schema.Record(Schema.String, Schema.Unknown),
24 fiberId: Schema.String,
25});
26​
27const decodeDesktopBackendChildLogRecord = Schema.decodeEffect(
28 Schema.fromJsonString(DesktopBackendChildLogRecord),
29);
30​
31const TraceRecordLine = Schema.Struct({
32 name: Schema.String,
33 attributes: Schema.Record(Schema.String, Schema.Unknown),
34 events: Schema.Array(
35 Schema.Struct({
36 name: Schema.String,
37 attributes: Schema.Record(Schema.String, Schema.Unknown),
38 }),
39 ),
40});
41​
42const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
43​
44const environmentInput = (baseDir: string) =>
45 ({
46 dirname: "/repo/apps/desktop/dist-electron",
47 homeDirectory: baseDir,
48 platform: "darwin",
49 processArch: "arm64",
50 appVersion: "1.2.3",
51 appPath: "/repo",
52 isPackaged: false,
53 resourcesPath: "/repo/resources",
54 runningUnderArm64Translation: false,
55 }) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
56​
57const layerEnvironmentFor = (
58 baseDir: string,
59 isDevelopment = true,
60 env: Readonly<Record<string, string | undefined>> = {},
61) =>
62 DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
63 Layer.provide(
64 Layer.mergeAll(
65 NodeServices.layer,
66 DesktopConfig.layerTest({
67 T3CODE_HOME: baseDir,
68 VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
69 ...env,
70 }),
71 ),
72 ),
73 );
74​
75interface ExportedRequest {
76 readonly url: string;
77 readonly headers: Readonly<Record<string, string>>;
78 readonly body: string;
80​
81const layerCollector = (requests: Array<ExportedRequest>) =>
82 Layer.succeed(
83 HttpClient.HttpClient,
84 HttpClient.make((request) =>
85 Effect.sync(() => {
86 requests.push({
87 url: request.url,
88 headers: request.headers,
89 body:
90 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
91 });
92 return HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }));
93 }),
94 ),
95 );
96​
97// A developer's own OTEL_* variables would otherwise pick the endpoints.
98const layerEmptyEnv = ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }));
99​
100const encodeObservabilitySettingsFile = Schema.encodeSync(
101 Schema.fromJsonString(
102 Schema.Struct({ observability: Schema.Record(Schema.String, Schema.String) }),
103 ),
104);
105​
106const writeObservabilitySettings = Effect.fn(function* (
107 environmentLayer: ReturnType<typeof layerEnvironmentFor>,
108 observability: Readonly<Record<string, string>>,
109) {
110 const fileSystem = yield* FileSystem.FileSystem;
111 const { path, serverSettingsPath } = yield* Effect.gen(function* () {
112 const environment = yield* DesktopEnvironment.DesktopEnvironment;
113 return environment;
114 }).pipe(Effect.provide(environmentLayer));
115 yield* fileSystem.makeDirectory(path.dirname(serverSettingsPath), { recursive: true });
116 yield* fileSystem.writeFileString(
117 serverSettingsPath,
118 encodeObservabilitySettingsFile({ observability }),
119 );
120});
121​
122describe("DesktopObservability", () => {
123 it.effect("buffers backend child output and persists it only when a failure is reported", () =>
124 Effect.gen(function* () {
125 const fileSystem = yield* FileSystem.FileSystem;
126 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
127 prefix: "t3-desktop-backend-output-log-test-",
128 });
129 const layerEnvironment = layerEnvironmentFor(baseDir, false);
130 const logPath = yield* Effect.gen(function* () {
131 const environment = yield* DesktopEnvironment.DesktopEnvironment;
132 return environment.path.join(environment.logDir, "server-child.log");
133 }).pipe(Effect.provide(layerEnvironment));
134 const tracePath = yield* Effect.gen(function* () {
135 const environment = yield* DesktopEnvironment.DesktopEnvironment;
136 return environment.path.join(environment.logDir, "desktop.trace.ndjson");
137 }).pipe(Effect.provide(layerEnvironment));
138​
139 yield* Effect.gen(function* () {
140 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
141 const outputLog = yield* factory.forInstance("primary");
142 yield* outputLog.beginSession({
143 details: "pid=123 port=3773 cwd=/repo",
144 });
145 yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
146 assert.isFalse(yield* fileSystem.exists(logPath));
147 yield* outputLog.persistFailure({ details: "code=1" });
148 yield* outputLog.beginSession({ details: "pid=456" });
149 yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n"));
150 yield* outputLog.discardSession;
151 }).pipe(
152 Effect.annotateLogs({ runId: "test-run" }),
153 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
154 );
155​
156 const log = yield* fileSystem.readFileString(logPath);
157 const lines = log.trimEnd().split("\n");
158 const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
159 const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
160 const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
161​
162 assert.equal(lines.length, 3);
163 assert.equal(start.message, "backend child process failure output start");
164 assert.equal(start.level, "ERROR");
165 assert.equal(start.annotations.component, "desktop-backend-child");
166 assert.equal(start.annotations.runId, "test-run");
167 assert.equal(start.annotations.instanceId, "primary");
168 assert.equal(start.annotations.phase, "START");
169 assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
170​
171 assert.equal(output.message, "backend child process output");
172 assert.equal(output.level, "INFO");
173 assert.equal(output.annotations.component, "desktop-backend-child");
174 assert.equal(output.annotations.runId, "test-run");
175 assert.equal(output.annotations.instanceId, "primary");
176 assert.equal(output.annotations.stream, "stdout");
177 assert.equal(output.annotations.text, "hello server\n");
178​
179 assert.equal(end.message, "backend child process failure output end");
180 assert.equal(end.level, "ERROR");
181 assert.equal(end.annotations.instanceId, "primary");
182 assert.equal(end.annotations.phase, "END");
183 assert.equal(end.annotations.details, "code=1");
184​
185 const traceRecords = (yield* fileSystem.readFileString(tracePath))
186 .trim()
187 .split("\n")
188 .filter((line) => line.length > 0)
189 .map((line) => decodeTraceRecordLine(line));
190 assert.isFalse(
191 traceRecords.some(
192 (record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
193 ),
194 );
195 }).pipe(
196 Effect.scoped,
197 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
198 ),
199 );
200​
201 it.effect("keeps buffering output after a non-terminal failure snapshot", () =>
202 Effect.gen(function* () {
203 const fileSystem = yield* FileSystem.FileSystem;
204 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
205 prefix: "t3-desktop-backend-output-snapshot-test-",
206 });
207 const layerEnvironment = layerEnvironmentFor(baseDir, false);
208 const logPath = yield* Effect.gen(function* () {
209 const environment = yield* DesktopEnvironment.DesktopEnvironment;
210 return environment.path.join(environment.logDir, "server-child.log");
211 }).pipe(Effect.provide(layerEnvironment));
212​
213 yield* Effect.gen(function* () {
214 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
215 const outputLog = yield* factory.forInstance("primary");
216 yield* outputLog.beginSession({ details: "pid=123" });
217 yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
218 yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
219 const prefix = "after timeout: ";
220 const message = new TextEncoder().encode(`${prefix}échec\n`);
221 const split = prefix.length + 1;
222 yield* outputLog.writeOutputChunk("stderr", message.subarray(0, split));
223 yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("interleaved\n"));
224 yield* outputLog.persistFailureSnapshot({ details: "mid-character snapshot" });
225 yield* outputLog.writeOutputChunk("stderr", message.subarray(split));
226 yield* outputLog.persistFailure({ details: "code=1" });
227 }).pipe(
228 Effect.annotateLogs({ runId: "test-run" }),
229 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
230 );
231​
232 const records = yield* Effect.forEach(
233 (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
234 (line) => decodeDesktopBackendChildLogRecord(line),
235 );
236 const stderrBySession: Array<string> = [];
237 for (const record of records) {
238 if (record.annotations.phase === "START") stderrBySession.push("");
239 if (record.annotations.stream === "stderr") {
240 stderrBySession[stderrBySession.length - 1] += String(record.annotations.text);
241 }
242 }
243 assert.equal(stderrBySession.at(-1), "after timeout: échec\n");
244 assert.deepEqual(stderrBySession.slice(0, -1), ["", "after timeout: "]);
245 assert.equal(records.at(-1)?.annotations.details, "code=1");
246 }).pipe(
247 Effect.scoped,
248 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
249 ),
250 );
251​
252 it.effect("retains only the last mebibyte of backend child output", () =>
253 Effect.gen(function* () {
254 const fileSystem = yield* FileSystem.FileSystem;
255 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
256 prefix: "t3-desktop-backend-output-bound-test-",
257 });
258 const layerEnvironment = layerEnvironmentFor(baseDir, false);
259 const logPath = yield* Effect.gen(function* () {
260 const environment = yield* DesktopEnvironment.DesktopEnvironment;
261 return environment.path.join(environment.logDir, "server-child.log");
262 }).pipe(Effect.provide(layerEnvironment));
263 const maxBufferedBytes = 1024 * 1024;
264 const discardedPrefixBytes = 128;
265 const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
266 output.fill("x".charCodeAt(0));
267 output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
268 output.set(new TextEncoder().encode("échec\n"), discardedPrefixBytes - 1);
269​
270 yield* Effect.scoped(
271 Effect.gen(function* () {
272 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
273 const outputLog = yield* factory.forInstance("primary");
274 yield* outputLog.beginSession({ details: "pid=123" });
275 const pipeReadBytes = 64 * 1024;
276 for (let offset = 0; offset < output.length; offset += pipeReadBytes) {
277 yield* outputLog.writeOutputChunk(
278 "stderr",
279 output.subarray(offset, offset + pipeReadBytes),
280 );
281 }
282 yield* outputLog.persistFailure({ details: "code=1" });
283 yield* outputLog.beginSession({ details: "pid=456" });
284 yield* outputLog.writeOutputChunk("stderr", output);
285 yield* outputLog.persistFailure({ details: "code=1" });
286 const err = (...bytes: Array<number>) =>
287 outputLog.writeOutputChunk("stderr", Uint8Array.of(...bytes));
288 const out = (reads: number) =>
289 outputLog
290 .writeOutputChunk("stdout", Uint8Array.of(0x7a))
291 .pipe(Effect.repeat({ times: reads - 1 }));
292 yield* outputLog.beginSession({ details: "pid=789" });
293 yield* Effect.all([err(0xf0), err(0x9f), out(254), err(0x98, 0x80, 0x6f, 0x6b)]);
294 yield* outputLog.persistFailureSnapshot({ details: "evicted lead byte" });
295 yield* Effect.all([err(0xc3), out(256), err(0xa9, 0x6f, 0x6b)]);
296 yield* outputLog.persistFailure({ details: "code=1" });
297 }).pipe(
298 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
299 ),
300 );
301​
302 const records = yield* Effect.forEach(
303 (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
304 (line) => decodeDesktopBackendChildLogRecord(line),
305 );
306 const text = records
307 .filter((record) => record.annotations.stream === "stderr")
308 .map((record) => String(record.annotations.text))
309 .join("");
310 assert.equal(text.split("\n", 1)[0], "chec");
311 assert.equal(new TextEncoder().encode(text).byteLength, 2 * (maxBufferedBytes - 1) + 4);
312 assert.isFalse(text.includes("y"));
313 }).pipe(
314 Effect.scoped,
315 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
316 ),
317 );
318​
319 it.effect("startup prunes only canonical rotation suffixes", () =>
320 Effect.gen(function* () {
321 const fileSystem = yield* FileSystem.FileSystem;
322 const directory = yield* fileSystem.makeTempDirectoryScoped({
323 prefix: "t3-desktop-rotating-prune-test-",
324 });
325 const filePath = `${directory}/server-child.log`;
326 const retained = ["1", "3", "04", "4.0", "4e0", "0x4", "+4", "notes"];
327 for (const suffix of [...retained, "4", "50"]) {
328 yield* fileSystem.writeFileString(`${filePath}.${suffix}`, suffix);
329 }
330​
331 yield* DesktopObservability.makeRotatingLogFileWriter({ filePath, maxFiles: 3 });
332​
333 assert.deepEqual(
334 (yield* fileSystem.readDirectory(directory)).sort(),
335 retained.map((suffix) => `server-child.log.${suffix}`).sort(),
336 );
337 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
338 );
339​
340 it.effect("keeps earlier backups while the active log cannot be renamed", () =>
341 Effect.gen(function* () {
342 const fileSystem = yield* FileSystem.FileSystem;
343 const directory = yield* fileSystem.makeTempDirectoryScoped({
344 prefix: "t3-desktop-rotating-locked-test-",
345 });
346 const filePath = `${directory}/server-child.log`;
347 yield* fileSystem.writeFileString(`${filePath}.1`, "previous");
348 yield* fileSystem.writeFileString(`${filePath}.2`, "oldest");
349 const writer = yield* DesktopObservability.makeRotatingLogFileWriter({
350 filePath,
351 maxBytes: 4,
352 maxFiles: 2,
353 }).pipe(
354 Effect.provideService(FileSystem.FileSystem, {
355 ...fileSystem,
356 rename: (source, target) =>
357 source === filePath
358 ? Effect.fail(
359 PlatformError.systemError({
360 _tag: "PermissionDenied",
361 module: "FileSystem",
362 method: "rename",
363 pathOrDescriptor: source,
364 }),
365 )
366 : fileSystem.rename(source, target),
367 }),
368 );
369​
370 for (let attempt = 0; attempt < 3; attempt += 1) {
371 yield* writer.writeText("12345\n");
372 }
373​
374 assert.deepEqual(
375 [
376 yield* fileSystem.readFileString(`${filePath}.1`),
377 yield* fileSystem.readFileString(`${filePath}.2`),
378 ],
379 ["previous", "oldest"],
380 );
381 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
382 );
383​
384 it.effect("keeps a log left staged by an interrupted rotation as a backup", () =>
385 Effect.gen(function* () {
386 const fileSystem = yield* FileSystem.FileSystem;
387 const directory = yield* fileSystem.makeTempDirectoryScoped({
388 prefix: "t3-desktop-rotating-staged-test-",
389 });
390 const filePath = `${directory}/server-child.log`;
391 yield* fileSystem.writeFileString(filePath, "active");
392 yield* fileSystem.writeFileString(`${filePath}.rotating`, "staged");
393 yield* fileSystem.writeFileString(`${filePath}.1`, "previous");
394 const writer = yield* DesktopObservability.makeRotatingLogFileWriter({
395 filePath,
396 maxBytes: 8,
397 maxFiles: 3,
398 });
399​
400 yield* writer.writeText("12345\n");
401​
402 assert.deepEqual(
403 [
404 yield* fileSystem.readFileString(`${filePath}.1`),
405 yield* fileSystem.readFileString(`${filePath}.2`),
406 yield* fileSystem.readFileString(`${filePath}.3`),
407 yield* fileSystem.exists(`${filePath}.rotating`),
408 ],
409 ["active", "staged", "previous", false],
410 );
411 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
412 );
413​
414 it.effect("stops every export when the OpenTelemetry SDK is disabled", () => {
415 const requests: Array<ExportedRequest> = [];
416 return Effect.gen(function* () {
417 const fileSystem = yield* FileSystem.FileSystem;
418 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
419 prefix: "t3-desktop-observability-test-",
420 });
421 const layerEnvironment = layerEnvironmentFor(baseDir);
422 yield* writeObservabilitySettings(layerEnvironment, {
423 otlpTracesUrl: "https://settings.example.com/v1/traces",
424 otlpLogsUrl: "https://settings.example.com/v1/logs",
425 });
426​
427 yield* Effect.scoped(
428 Effect.logInfo("desktop log stays local when disabled").pipe(
429 Effect.withSpan("desktop-disabled-test"),
430 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
431 ),
432 );
433​
434 assert.lengthOf(requests, 0);
435 }).pipe(
436 Effect.scoped,
437 Effect.provide(
438 Layer.mergeAll(
439 NodeServices.layer,
440 layerCollector(requests),
441 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })),
442 ),
443 ),
444 );
445 });
446​
447 it.effect("reports the app's own version for an unpackaged desktop run", () => {
448 const requests: Array<ExportedRequest> = [];
449 return Effect.gen(function* () {
450 const fileSystem = yield* FileSystem.FileSystem;
451 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
452 prefix: "t3-desktop-observability-test-",
453 });
454 const layerEnvironment = layerEnvironmentFor(baseDir);
455 yield* writeObservabilitySettings(layerEnvironment, {
456 otlpLogsUrl: "https://settings.example.com/v1/logs",
457 });
458​
459 yield* Effect.scoped(
460 Effect.logInfo("desktop resource under test").pipe(
461 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
462 ),
463 );
464​
465 const body = requests.map((request) => request.body).join("\n");
466 assert.include(
467 body,
468 `"key":"service.version","value":{"stringValue":"${desktopPackageJson.version}"}`,
469 );
470 }).pipe(
471 Effect.scoped,
472 Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)),
473 );
474 });
475​
476 it.effect("describes the Node runtime and the desktop mode under semantic or t3code keys", () => {
477 const requests: Array<ExportedRequest> = [];
478 return Effect.gen(function* () {
479 const fileSystem = yield* FileSystem.FileSystem;
480 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
481 prefix: "t3-desktop-observability-test-",
482 });
483 const layerEnvironment = layerEnvironmentFor(baseDir);
484 yield* writeObservabilitySettings(layerEnvironment, {
485 otlpLogsUrl: "https://settings.example.com/v1/logs",
486 });
487​
488 yield* Effect.scoped(
489 Effect.logInfo("desktop resource under test").pipe(
490 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
491 ),
492 );
493​
494 const body = requests.map((request) => request.body).join("\n");
495 assert.include(body, '"key":"process.runtime.name","value":{"stringValue":"nodejs"}');
496 assert.include(
497 body,
498 `"key":"process.runtime.version","value":{"stringValue":"${process.versions.node}"}`,
499 );
500 assert.include(body, '"key":"t3code.desktop.mode","value":{"stringValue":"development"}');
501 assert.notInclude(body, "service.mode");
502 }).pipe(
503 Effect.scoped,
504 Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)),
505 );
506 });
507});