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 Schema from "effect/Schema";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientResponse from "effect/http/HttpClientResponse";
12
13import * as DesktopConfig from "./DesktopConfig.ts";
14import * as DesktopEnvironment from "./DesktopEnvironment.ts";
15import * as DesktopObservability from "./DesktopObservability.ts";
16
17const DesktopBackendChildLogRecord = Schema.Struct({
18 message: Schema.String,
19 level: Schema.Literals(["INFO", "ERROR"]),
20 timestamp: Schema.String,
21 annotations: Schema.Record(Schema.String, Schema.Unknown),
22 spans: Schema.Record(Schema.String, Schema.Unknown),
23 fiberId: Schema.String,
24});
25
26const decodeDesktopBackendChildLogRecord = Schema.decodeEffect(
27 Schema.fromJsonString(DesktopBackendChildLogRecord),
28);
29
30const TraceRecordLine = Schema.Struct({
31 name: Schema.String,
32 attributes: Schema.Record(Schema.String, Schema.Unknown),
33 events: Schema.Array(
34 Schema.Struct({
35 name: Schema.String,
36 attributes: Schema.Record(Schema.String, Schema.Unknown),
37 }),
38 ),
39});
40
41const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
42
43const environmentInput = (baseDir: string) =>
44 ({
45 dirname: "/repo/apps/desktop/dist-electron",
46 homeDirectory: baseDir,
47 platform: "darwin",
48 processArch: "arm64",
49 appVersion: "1.2.3",
50 appPath: "/repo",
51 isPackaged: false,
52 resourcesPath: "/repo/resources",
53 runningUnderArm64Translation: false,
54 }) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
55
56const layerEnvironmentFor = (
57 baseDir: string,
58 isDevelopment = true,
59 env: Readonly<Record<string, string | undefined>> = {},
60) =>
61 DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
62 Layer.provide(
63 Layer.mergeAll(
64 NodeServices.layer,
65 DesktopConfig.layerTest({
66 T3CODE_HOME: baseDir,
67 VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
68 ...env,
69 }),
70 ),
71 ),
72 );
73
74interface ExportedRequest {
75 readonly url: string;
76 readonly headers: Readonly<Record<string, string>>;
77 readonly body: string;
78}
79
80const layerCollector = (requests: Array<ExportedRequest>) =>
81 Layer.succeed(
82 HttpClient.HttpClient,
83 HttpClient.make((request) =>
84 Effect.sync(() => {
85 requests.push({
86 url: request.url,
87 headers: request.headers,
88 body:
89 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
90 });
91 return HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }));
92 }),
93 ),
94 );
95
96// A developer's own OTEL_* variables would otherwise pick the endpoints.
97const layerEmptyEnv = ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }));
98
99const encodeObservabilitySettingsFile = Schema.encodeSync(
100 Schema.fromJsonString(
101 Schema.Struct({ observability: Schema.Record(Schema.String, Schema.String) }),
102 ),
103);
104
105const writeObservabilitySettings = Effect.fn(function* (
106 environmentLayer: ReturnType<typeof layerEnvironmentFor>,
107 observability: Readonly<Record<string, string>>,
108) {
109 const fileSystem = yield* FileSystem.FileSystem;
110 const { path, serverSettingsPath } = yield* Effect.gen(function* () {
111 const environment = yield* DesktopEnvironment.DesktopEnvironment;
112 return environment;
113 }).pipe(Effect.provide(environmentLayer));
114 yield* fileSystem.makeDirectory(path.dirname(serverSettingsPath), { recursive: true });
115 yield* fileSystem.writeFileString(
116 serverSettingsPath,
117 encodeObservabilitySettingsFile({ observability }),
118 );
119});
120
121describe("DesktopObservability", () => {
122 it.effect("buffers backend child output and persists it only when a failure is reported", () =>
123 Effect.gen(function* () {
124 const fileSystem = yield* FileSystem.FileSystem;
125 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
126 prefix: "t3-desktop-backend-output-log-test-",
127 });
128 const layerEnvironment = layerEnvironmentFor(baseDir, false);
129 const logPath = yield* Effect.gen(function* () {
130 const environment = yield* DesktopEnvironment.DesktopEnvironment;
131 return environment.path.join(environment.logDir, "server-child.log");
132 }).pipe(Effect.provide(layerEnvironment));
133 const tracePath = yield* Effect.gen(function* () {
134 const environment = yield* DesktopEnvironment.DesktopEnvironment;
135 return environment.path.join(environment.logDir, "desktop.trace.ndjson");
136 }).pipe(Effect.provide(layerEnvironment));
137
138 yield* Effect.gen(function* () {
139 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
140 const outputLog = yield* factory.forInstance("primary");
141 yield* outputLog.beginSession({
142 details: "pid=123 port=3773 cwd=/repo",
143 });
144 yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
145 assert.isFalse(yield* fileSystem.exists(logPath));
146 yield* outputLog.persistFailure({ details: "code=1" });
147 yield* outputLog.beginSession({ details: "pid=456" });
148 yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n"));
149 yield* outputLog.discardSession;
150 }).pipe(
151 Effect.annotateLogs({ runId: "test-run" }),
152 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
153 );
154
155 const log = yield* fileSystem.readFileString(logPath);
156 const lines = log.trimEnd().split("\n");
157 const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
158 const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
159 const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
160
161 assert.equal(lines.length, 3);
162 assert.equal(start.message, "backend child process failure output start");
163 assert.equal(start.level, "ERROR");
164 assert.equal(start.annotations.component, "desktop-backend-child");
165 assert.equal(start.annotations.runId, "test-run");
166 assert.equal(start.annotations.instanceId, "primary");
167 assert.equal(start.annotations.phase, "START");
168 assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
169
170 assert.equal(output.message, "backend child process output");
171 assert.equal(output.level, "INFO");
172 assert.equal(output.annotations.component, "desktop-backend-child");
173 assert.equal(output.annotations.runId, "test-run");
174 assert.equal(output.annotations.instanceId, "primary");
175 assert.equal(output.annotations.stream, "stdout");
176 assert.equal(output.annotations.text, "hello server\n");
177
178 assert.equal(end.message, "backend child process failure output end");
179 assert.equal(end.level, "ERROR");
180 assert.equal(end.annotations.instanceId, "primary");
181 assert.equal(end.annotations.phase, "END");
182 assert.equal(end.annotations.details, "code=1");
183
184 const traceRecords = (yield* fileSystem.readFileString(tracePath))
185 .trim()
186 .split("\n")
187 .filter((line) => line.length > 0)
188 .map((line) => decodeTraceRecordLine(line));
189 assert.isFalse(
190 traceRecords.some(
191 (record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
192 ),
193 );
194 }).pipe(
195 Effect.scoped,
196 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
197 ),
198 );
199
200 it.effect("keeps buffering output after a non-terminal failure snapshot", () =>
201 Effect.gen(function* () {
202 const fileSystem = yield* FileSystem.FileSystem;
203 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
204 prefix: "t3-desktop-backend-output-snapshot-test-",
205 });
206 const layerEnvironment = layerEnvironmentFor(baseDir, false);
207 const logPath = yield* Effect.gen(function* () {
208 const environment = yield* DesktopEnvironment.DesktopEnvironment;
209 return environment.path.join(environment.logDir, "server-child.log");
210 }).pipe(Effect.provide(layerEnvironment));
211
212 yield* Effect.gen(function* () {
213 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
214 const outputLog = yield* factory.forInstance("primary");
215 yield* outputLog.beginSession({ details: "pid=123" });
216 yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
217 yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
218 yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
219 yield* outputLog.persistFailure({ details: "code=1" });
220 }).pipe(
221 Effect.annotateLogs({ runId: "test-run" }),
222 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
223 );
224
225 const records = yield* Effect.forEach(
226 (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
227 (line) => decodeDesktopBackendChildLogRecord(line),
228 );
229 assert.equal(
230 records.some((record) => record.annotations.text === "after timeout\n"),
231 true,
232 );
233 assert.equal(records.at(-1)?.annotations.details, "code=1");
234 }).pipe(
235 Effect.scoped,
236 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
237 ),
238 );
239
240 it.effect("retains only the last mebibyte of backend child output", () =>
241 Effect.gen(function* () {
242 const fileSystem = yield* FileSystem.FileSystem;
243 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
244 prefix: "t3-desktop-backend-output-bound-test-",
245 });
246 const layerEnvironment = layerEnvironmentFor(baseDir, false);
247 const logPath = yield* Effect.gen(function* () {
248 const environment = yield* DesktopEnvironment.DesktopEnvironment;
249 return environment.path.join(environment.logDir, "server-child.log");
250 }).pipe(Effect.provide(layerEnvironment));
251 const maxBufferedBytes = 1024 * 1024;
252 const discardedPrefixBytes = 128;
253 const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
254 output.fill("x".charCodeAt(0));
255 output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
256
257 yield* Effect.scoped(
258 Effect.gen(function* () {
259 const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
260 const outputLog = yield* factory.forInstance("primary");
261 yield* outputLog.beginSession({ details: "pid=123" });
262 yield* outputLog.writeOutputChunk("stderr", output);
263 yield* outputLog.persistFailure({ details: "code=1" });
264 }).pipe(
265 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
266 ),
267 );
268
269 const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
270 const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
271 const text = record.annotations.text;
272 assert.equal(typeof text, "string");
273 if (typeof text !== "string") {
274 return;
275 }
276 assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
277 assert.isFalse(text.includes("y"));
278 }).pipe(
279 Effect.scoped,
280 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)),
281 ),
282 );
283
284 it.effect("stops every export when the OpenTelemetry SDK is disabled", () => {
285 const requests: Array<ExportedRequest> = [];
286 return Effect.gen(function* () {
287 const fileSystem = yield* FileSystem.FileSystem;
288 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
289 prefix: "t3-desktop-observability-test-",
290 });
291 const layerEnvironment = layerEnvironmentFor(baseDir);
292 yield* writeObservabilitySettings(layerEnvironment, {
293 otlpTracesUrl: "https://settings.example.com/v1/traces",
294 otlpLogsUrl: "https://settings.example.com/v1/logs",
295 });
296
297 yield* Effect.scoped(
298 Effect.logInfo("desktop log stays local when disabled").pipe(
299 Effect.withSpan("desktop-disabled-test"),
300 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
301 ),
302 );
303
304 assert.lengthOf(requests, 0);
305 }).pipe(
306 Effect.scoped,
307 Effect.provide(
308 Layer.mergeAll(
309 NodeServices.layer,
310 layerCollector(requests),
311 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })),
312 ),
313 ),
314 );
315 });
316
317 it.effect("reports the app's own version for an unpackaged desktop run", () => {
318 const requests: Array<ExportedRequest> = [];
319 return Effect.gen(function* () {
320 const fileSystem = yield* FileSystem.FileSystem;
321 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
322 prefix: "t3-desktop-observability-test-",
323 });
324 const layerEnvironment = layerEnvironmentFor(baseDir);
325 yield* writeObservabilitySettings(layerEnvironment, {
326 otlpLogsUrl: "https://settings.example.com/v1/logs",
327 });
328
329 yield* Effect.scoped(
330 Effect.logInfo("desktop resource under test").pipe(
331 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
332 ),
333 );
334
335 const body = requests.map((request) => request.body).join("\n");
336 assert.include(
337 body,
338 `"key":"service.version","value":{"stringValue":"${desktopPackageJson.version}"}`,
339 );
340 }).pipe(
341 Effect.scoped,
342 Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)),
343 );
344 });
345
346 it.effect("describes the Node runtime and the desktop mode under semantic or t3code keys", () => {
347 const requests: Array<ExportedRequest> = [];
348 return Effect.gen(function* () {
349 const fileSystem = yield* FileSystem.FileSystem;
350 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
351 prefix: "t3-desktop-observability-test-",
352 });
353 const layerEnvironment = layerEnvironmentFor(baseDir);
354 yield* writeObservabilitySettings(layerEnvironment, {
355 otlpLogsUrl: "https://settings.example.com/v1/logs",
356 });
357
358 yield* Effect.scoped(
359 Effect.logInfo("desktop resource under test").pipe(
360 Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))),
361 ),
362 );
363
364 const body = requests.map((request) => request.body).join("\n");
365 assert.include(body, '"key":"process.runtime.name","value":{"stringValue":"nodejs"}');
366 assert.include(
367 body,
368 `"key":"process.runtime.version","value":{"stringValue":"${process.versions.node}"}`,
369 );
370 assert.include(body, '"key":"t3code.desktop.mode","value":{"stringValue":"development"}');
371 assert.notInclude(body, "service.mode");
372 }).pipe(
373 Effect.scoped,
374 Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)),
375 );
376 });
377});