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