Open History to see the last commit
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;
79}
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 yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
220 yield* outputLog.persistFailure({ details: "code=1" });
221 }).pipe(
222 Effect.annotateLogs({ runId: "test-run" }),
223 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
224 );
225
226 const records = yield* Effect.forEach(
227 (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
228 (line) => decodeDesktopBackendChildLogRecord(line),
229 );
230 assert.equal(
231 records.some((record) => record.annotations.text === "after timeout\n"),
232 true,
233 );
234 assert.equal(records.at(-1)?.annotations.details, "code=1");
235 }).pipe(
236 Effect.scoped,
237 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
238 ),
239 );
240
241 it.effect("retains only the last mebibyte of backend child output", () =>
242 Effect.gen(function* () {
243 const fileSystem = yield* FileSystem.FileSystem;
244 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
245 prefix: "t3-desktop-backend-output-bound-test-",
246 });
247 const layerEnvironment = layerEnvironmentFor(baseDir, false);
248 const logPath = yield* Effect.gen(function* () {
249 const environment = yield* DesktopEnvironment.DesktopEnvironment;
250 return environment.path.join(environment.logDir, "server-child.log");
251 }).pipe(Effect.provide(layerEnvironment));
252 const maxBufferedBytes = 1024 * 1024;
253 const discardedPrefixBytes = 128;
254 const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
255 output.fill("x".charCodeAt(0));
256 output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
257
258 yield* Effect.scoped(
259 Effect.gen(function* () {
260 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
261 const outputLog = yield* factory.forInstance("primary");
262 yield* outputLog.beginSession({ details: "pid=123" });
263 yield* outputLog.writeOutputChunk("stderr", output);
264 yield* outputLog.persistFailure({ details: "code=1" });
265 }).pipe(
266 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
267 ),
268 );
269
270 const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
271 const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
272 const text = record.annotations.text;
273 assert.equal(typeof text, "string");
274 if (typeof text !== "string") {
275 return;
276 }
277 assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
278 assert.isFalse(text.includes("y"));
279 }).pipe(
280 Effect.scoped,
281 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
282 ),
283 );
284
285 it.effect("startup prunes only canonical rotation suffixes", () =>
286 Effect.gen(function* () {
287 const fileSystem = yield* FileSystem.FileSystem;
288 const directory = yield* fileSystem.makeTempDirectoryScoped({
289 prefix: "t3-desktop-rotating-prune-test-",
290 });
291 const filePath = `${directory}/server-child.log`;
292 const retained = ["1", "3", "04", "4.0", "4e0", "0x4", "+4", "notes"];
293 for (const suffix of [...retained, "4", "50"]) {
294 yield* fileSystem.writeFileString(`${filePath}.${suffix}`, suffix);
295 }
296
297 yield* DesktopObservability.makeRotatingLogFileWriter({ filePath, maxFiles: 3 });
298
299 assert.deepEqual(
300 (yield* fileSystem.readDirectory(directory)).sort(),
301 retained.map((suffix) => `server-child.log.${suffix}`).sort(),
302 );
303 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
304 );
305
306 it.effect("keeps earlier backups while the active log cannot be renamed", () =>
307 Effect.gen(function* () {
308 const fileSystem = yield* FileSystem.FileSystem;
309 const directory = yield* fileSystem.makeTempDirectoryScoped({
310 prefix: "t3-desktop-rotating-locked-test-",
311 });
312 const filePath = `${directory}/server-child.log`;
313 yield* fileSystem.writeFileString(`${filePath}.1`, "previous");
314 yield* fileSystem.writeFileString(`${filePath}.2`, "oldest");
315 const writer = yield* DesktopObservability.makeRotatingLogFileWriter({
316 filePath,
317 maxBytes: 4,
318 maxFiles: 2,
319 }).pipe(
320 Effect.provideService(FileSystem.FileSystem, {
321 ...fileSystem,
322 rename: (source, target) =>
323 source === filePath
324 ? Effect.fail(
325 PlatformError.systemError({
326 _tag: "PermissionDenied",
327 module: "FileSystem",
328 method: "rename",
329 pathOrDescriptor: source,
330 }),
331 )
332 : fileSystem.rename(source, target),
333 }),
334 );
335
336 for (let attempt = 0; attempt < 3; attempt += 1) {
337 yield* writer.writeText("12345\n");
338 }
339
340 assert.deepEqual(
341 [
342 yield* fileSystem.readFileString(`${filePath}.1`),
343 yield* fileSystem.readFileString(`${filePath}.2`),
344 ],
345 ["previous", "oldest"],
346 );
347 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
348 );
349
350 it.effect("keeps a log left staged by an interrupted rotation as a backup", () =>
351 Effect.gen(function* () {
352 const fileSystem = yield* FileSystem.FileSystem;
353 const directory = yield* fileSystem.makeTempDirectoryScoped({
354 prefix: "t3-desktop-rotating-staged-test-",
355 });
356 const filePath = `${directory}/server-child.log`;
357 yield* fileSystem.writeFileString(filePath, "active");
358 yield* fileSystem.writeFileString(`${filePath}.rotating`, "staged");
359 yield* fileSystem.writeFileString(`${filePath}.1`, "previous");
360 const writer = yield* DesktopObservability.makeRotatingLogFileWriter({
361 filePath,
362 maxBytes: 8,
363 maxFiles: 3,
364 });
365
366 yield* writer.writeText("12345\n");
367
368 assert.deepEqual(
369 [
370 yield* fileSystem.readFileString(`${filePath}.1`),
371 yield* fileSystem.readFileString(`${filePath}.2`),
372 yield* fileSystem.readFileString(`${filePath}.3`),
373 yield* fileSystem.exists(`${filePath}.rotating`),
374 ],
375 ["active", "staged", "previous", false],
376 );
377 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
378 );
379
380 it.effect("stops every export when the OpenTelemetry SDK is disabled", () => {
381 const requests: Array<ExportedRequest> = [];
382 return Effect.gen(function* () {
383 const fileSystem = yield* FileSystem.FileSystem;
384 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
385 prefix: "t3-desktop-observability-test-",
386 });
387 const layerEnvironment = layerEnvironmentFor(baseDir);
388 yield* writeObservabilitySettings(layerEnvironment, {
389 otlpTracesUrl: "https://settings.example.com/v1/traces",
390 otlpLogsUrl: "https://settings.example.com/v1/logs",
391 });
392
393 yield* Effect.scoped(
394 Effect.logInfo("desktop log stays local when disabled").pipe(
395 Effect.withSpan("desktop-disabled-test"),
396 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
397 ),
398 );
399
400 assert.lengthOf(requests, 0);
401 }).pipe(
402 Effect.scoped,
403 Effect.provide(
404 Layer.mergeAll(
405 NodeServices.layer,
406 layerCollector(requests),
407 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })),
408 ),
409 ),
410 );
411 });
412
413 it.effect("reports the app's own version for an unpackaged desktop run", () => {
414 const requests: Array<ExportedRequest> = [];
415 return Effect.gen(function* () {
416 const fileSystem = yield* FileSystem.FileSystem;
417 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
418 prefix: "t3-desktop-observability-test-",
419 });
420 const layerEnvironment = layerEnvironmentFor(baseDir);
421 yield* writeObservabilitySettings(layerEnvironment, {
422 otlpLogsUrl: "https://settings.example.com/v1/logs",
423 });
424
425 yield* Effect.scoped(
426 Effect.logInfo("desktop resource under test").pipe(
427 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
428 ),
429 );
430
431 const body = requests.map((request) => request.body).join("\n");
432 assert.include(
433 body,
434 `"key":"service.version","value":{"stringValue":"${desktopPackageJson.version}"}`,
435 );
436 }).pipe(
437 Effect.scoped,
438 Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)),
439 );
440 });
441
442 it.effect("describes the Node runtime and the desktop mode under semantic or t3code keys", () => {
443 const requests: Array<ExportedRequest> = [];
444 return Effect.gen(function* () {
445 const fileSystem = yield* FileSystem.FileSystem;
446 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
447 prefix: "t3-desktop-observability-test-",
448 });
449 const layerEnvironment = layerEnvironmentFor(baseDir);
450 yield* writeObservabilitySettings(layerEnvironment, {
451 otlpLogsUrl: "https://settings.example.com/v1/logs",
452 });
453
454 yield* Effect.scoped(
455 Effect.logInfo("desktop resource under test").pipe(
456 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
457 ),
458 );
459
460 const body = requests.map((request) => request.body).join("\n");
461 assert.include(body, '"key":"process.runtime.name","value":{"stringValue":"nodejs"}');
462 assert.include(
463 body,
464 `"key":"process.runtime.version","value":{"stringValue":"${process.versions.node}"}`,
465 );
466 assert.include(body, '"key":"t3code.desktop.mode","value":{"stringValue":"development"}');
467 assert.notInclude(body, "service.mode");
468 }).pipe(
469 Effect.scoped,
470 Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)),
471 );
472 });
473});