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

DesktopObservability.test.ts

331 lines13.8 KB

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