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

serverLogger.test.ts

384 lines13.2 KB

1import * as NodePath from "@effect/platform-node/NodePath";
2import { assert, describe, it } from "@effect/vitest";
3import * as NodeOS from "node:os";
4import * as NodeUtil from "node:util";
5​
6import { ExternalLauncherBrowserSpawnError } from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import * as ConfigProvider from "effect/ConfigProvider";
9import * as Console from "effect/Console";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Layer from "effect/Layer";
13import * as Redactable from "effect/Redactable";
14import * as Path from "effect/Path";
15import * as Tracer from "effect/Tracer";
16import * as HttpClient from "effect/http/HttpClient";
17import * as HttpClientResponse from "effect/http/HttpClientResponse";
18import * as TestConsole from "effect/testing/TestConsole";
19​
20import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
21import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
22​
23import * as ServerConfig from "./config.ts";
24import * as ExternalLauncher from "./process/externalLauncher.ts";
25import * as ServerLogger from "./serverLogger.ts";
26import {
27 announceStartupPairingUrl,
28 logBrowserAutoOpenUnavailable,
29 maybeOpenBrowser,
30} from "./serverRuntimeStartup.ts";
31​
32interface ExportedRequest {
33 readonly url: string;
34 readonly headers: Readonly<Record<string, string>>;
35 readonly body: string;
37​
38const layerCollector = (requests: Array<ExportedRequest>) =>
39 Layer.succeed(
40 HttpClient.HttpClient,
41 HttpClient.make((request) =>
42 Effect.sync(() => {
43 requests.push({
44 url: request.url,
45 headers: request.headers,
46 body:
47 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
48 });
49 return HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }));
50 }),
51 ),
52 );
53​
54const layerConfig = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
55 Layer.effect(
56 ServerConfig.ServerConfig,
57 Effect.gen(function* () {
58 const path = yield* Path.Path;
59 const baseDir = path.join(NodeOS.tmpdir(), "t3-server-logger-test");
60 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
61 return ServerConfig.make({
62 logLevel: "Info",
63 traceMinLevel: "Info",
64 traceTimingEnabled: false,
65 traceBatchWindowMs: 200,
66 traceMaxBytes: 1024,
67 traceMaxFiles: 1,
68 otlpTracesUrl: undefined,
69 otlpMetricsUrl: undefined,
70 otlpLogsUrl: undefined,
71 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
72 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
73 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
74 otelEnvironment: OtelEnvironment.none,
75 cwd: baseDir,
76 baseDir,
77 ...derivedPaths,
78 mode: "web",
79 autoBootstrapProjectFromCwd: false,
80 logWebSocketEvents: false,
81 tailscaleServeEnabled: false,
82 tailscaleServePort: 443,
83 port: 0,
84 host: undefined,
85 desktopBootstrapToken: undefined,
86 desktopTelemetryFd: undefined,
87 desktopTelemetryControlFd: undefined,
88 resourceMonitorPath: undefined,
89 staticDir: undefined,
90 devUrl: undefined,
91 devAllowedOrigins: [],
92 noBrowser: false,
93 startupPresentation: "browser",
94 ...overrides,
95 });
96 }),
97 ).pipe(Layer.provide(NodePath.layer));
98​
99/**
100 * The export is asserted after the layer's scope closes, which is where the
101 * exporter flushes whatever the interval did not.
102 */
103const logThrough = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
104 Effect.gen(function* () {
105 const requests: Array<ExportedRequest> = [];
106 yield* Effect.log("server logger under test").pipe(
107 Effect.provide(
108 ServerLogger.layer.pipe(
109 Layer.provide(layerConfig(overrides)),
110 Layer.provide(layerCollector(requests)),
111 ),
112 ),
113 );
114 return requests;
115 });
116​
117/**
118 * Runs `program` (one log line by default) inside a span so the tracer logger
119 * has somewhere to attach an event, then reports both what the collector
120 * received and what landed on the span.
121 */
122const logInSpanThrough = (
123 overrides: Partial<ServerConfig.ServerConfig["Service"]>,
124 program: Effect.Effect<void> = Effect.log("server logger under test"),
125) =>
126 Effect.gen(function* () {
127 const requests: Array<ExportedRequest> = [];
128 const spans: Array<Tracer.NativeSpan> = [];
129 const layerTracer = Layer.succeed(
130 Tracer.Tracer,
131 Tracer.make({
132 span: (spanOptions) => {
133 const span = new Tracer.NativeSpan(spanOptions);
134 spans.push(span);
135 return span;
136 },
137 }),
138 );
139 yield* program.pipe(
140 Effect.withSpan("server-logger-test"),
141 Effect.provide(
142 Layer.mergeAll(
143 ServerLogger.layer.pipe(
144 Layer.provide(layerConfig(overrides)),
145 Layer.provide(layerCollector(requests)),
146 ),
147 layerTracer,
148 ),
149 ),
150 );
151 return { requests, spans };
152 });
153​
154/** Logs one warning through the server logger and returns what its console printed. */
155const printThroughConsole = (fields: object) =>
156 Effect.gen(function* () {
157 const printed: Array<string> = [];
158 const testConsole = {
159 ...globalThis.console,
160 log: (...args: ReadonlyArray<unknown>) => {
161 printed.push(NodeUtil.format(...args));
162 },
163 } satisfies Console.Console;
164 yield* Effect.logWarning("pull request watch check failed", fields).pipe(
165 Effect.provide(
166 ServerLogger.layer.pipe(Layer.provide(layerConfig({})), Layer.provide(layerCollector([]))),
167 ),
168 Effect.provideService(Console.Console, testConsole),
169 );
170 return printed.join("\n");
171 });
172​
173describe("ServerLoggerLive", () => {
174 it.effect("exports log records to the configured logs endpoint", () =>
175 Effect.gen(function* () {
176 const requests = yield* logThrough({
177 otlpLogsUrl: "https://collector.example.com/v1/logs",
178 });
179​
180 assert.lengthOf(requests, 1);
181 const [request] = requests;
182 assert.strictEqual(request?.url, "https://collector.example.com/v1/logs");
183 assert.include(request?.body ?? "", "server logger under test");
184 assert.include(request?.body ?? "", "t3code-server");
185 assert.include(request?.body ?? "", "service.runtime");
186 }),
187 );
188​
189 it.effect("keeps its service name while OTEL resource attributes add dimensions", () =>
190 Effect.gen(function* () {
191 const requests = yield* logThrough({
192 otlpLogsUrl: "https://collector.example.com/v1/logs",
193 }).pipe(
194 Effect.provide(
195 ConfigProvider.layer(
196 ConfigProvider.fromEnv({
197 env: {
198 OTEL_SERVICE_NAME: "renamed",
199 OTEL_RESOURCE_ATTRIBUTES:
200 "service.name=renamed,service.namespace=renamed,deployment.environment.name=development",
201 },
202 }),
203 ),
204 ),
205 );
206​
207 assert.lengthOf(requests, 1);
208 const body = requests[0]?.body ?? "";
209 assert.include(body, '"stringValue":"t3code-server"');
210 assert.include(body, "deployment.environment.name");
211 assert.include(body, '"key":"service.namespace","value":{"stringValue":"t3code"}');
212 assert.notInclude(body, "renamed");
213 }),
214 );
215​
216 it.effect("stays off the network when no logs endpoint is configured", () =>
217 Effect.gen(function* () {
218 const requests = yield* logThrough({});
219​
220 assert.lengthOf(requests, 0);
221 }),
222 );
223​
224 it.effect("sends the headers and wire format the log signal asked for", () =>
225 Effect.gen(function* () {
226 const requests = yield* logThrough({
227 otlpLogsUrl: "https://collector.example.com/v1/logs",
228 otlpLogsExport: {
229 ...DEFAULT_SIGNAL_EXPORT,
230 protocol: "http/protobuf",
231 headers: { "x-scope": "logs" },
232 },
233 });
234​
235 assert.lengthOf(requests, 1);
236 assert.strictEqual(requests[0]?.headers["x-scope"], "logs");
237 assert.strictEqual(requests[0]?.headers["content-type"], "application/x-protobuf");
238 }),
239 );
240​
241 it.effect("attaches log messages to the active span when no logs endpoint is configured", () =>
242 Effect.gen(function* () {
243 const { requests, spans } = yield* logInSpanThrough({});
244​
245 assert.lengthOf(requests, 0);
246 assert.lengthOf(spans, 1);
247 assert.deepEqual(
248 spans[0]?.events.map(([name]) => name),
249 ["server logger under test"],
250 );
251 }),
252 );
253​
254 it.effect("stops duplicating messages onto the span once log records are exported", () =>
255 Effect.gen(function* () {
256 const { requests, spans } = yield* logInSpanThrough({
257 otlpLogsUrl: "https://collector.example.com/v1/logs",
258 });
259​
260 assert.lengthOf(requests, 1);
261 assert.include(requests[0]?.body ?? "", "server logger under test");
262 assert.lengthOf(spans, 1);
263 assert.lengthOf(spans[0]?.events ?? [], 0);
264 }),
265 );
266​
267 it.effect("prints a cause passed as a log field instead of collapsing it", () =>
268 Effect.gen(function* () {
269 const output = yield* printThroughConsole({
270 threadId: "thread-1",
271 cause: Cause.fail(new Error("gh: HTTP 502 from api.github.com")),
272 });
273​
274 assert.include(output, "threadId: 'thread-1'");
275 assert.include(output, "gh: HTTP 502 from api.github.com");
276 assert.notInclude(output, "[Object]");
277 }),
278 );
279​
280 it.effect("leaves getters uncalled while printing a cause field", () =>
281 Effect.gen(function* () {
282 const output = yield* printThroughConsole({
283 cause: Cause.fail(new Error("upstream refused")),
284 get detail(): string {
285 throw new Error("getter must not run");
286 },
287 });
288​
289 assert.include(output, "upstream refused");
290 assert.notInclude(output, "getter must not run");
291 }),
292 );
293​
294 it.effect("leaves a message with its own redaction hook to that hook", () =>
295 Effect.gen(function* () {
296 const output = yield* printThroughConsole({
297 token: "secret-token-value",
298 cause: Cause.fail(new Error("upstream refused")),
299 [Redactable.symbolRedactable](this: { readonly cause: unknown }) {
300 return { token: "<redacted>", cause: Cause.isCause(this.cause) ? "cause" : "missing" };
301 },
302 });
303​
304 assert.include(output, "token: '<redacted>'");
305 assert.include(output, "cause: 'cause'");
306 assert.notInclude(output, "secret-token-value");
307 }),
308 );
309​
310 describe("startup pairing URL", () => {
311 const pairingToken = "PAIRTOKEN7Q4K9";
312 const pairingUrl = `http://localhost:3773/pair#token=${pairingToken}`;
313 const announce = announceStartupPairingUrl(pairingUrl).pipe(
314 Effect.andThen(logBrowserAutoOpenUnavailable),
315 );
316​
317 it.effect("prints the full URL but keeps its token out of exported log records", () =>
318 Effect.gen(function* () {
319 const { requests } = yield* logInSpanThrough(
320 { otlpLogsUrl: "https://collector.example.com/v1/logs" },
321 announce,
322 );
323​
324 const body = requests.map((request) => request.body).join("\n");
325 assert.include(body, "Authentication required");
326 assert.notInclude(body, pairingToken);
327 const printed = (yield* TestConsole.logLines).map((line) =>
328 Array.isArray(line) ? line.join(" ") : String(line),
329 );
330 assert.isTrue(printed.some((line) => line.includes(`pairingUrl: ${pairingUrl}`)));
331 }).pipe(Effect.provide(TestConsole.layer)),
332 );
333​
334 it.effect("keeps the token off the span events the trace file records", () =>
335 Effect.gen(function* () {
336 const { spans } = yield* logInSpanThrough({}, announce);
337​
338 const events = JSON.stringify(
339 spans.flatMap((span) => span.events.map(([name, , attributes]) => [name, attributes])),
340 );
341 assert.include(events, "Authentication required");
342 assert.notInclude(events, pairingToken);
343 }).pipe(Effect.provide(TestConsole.layer)),
344 );
345​
346 it.effect("keeps the token out of traces when the browser fails to open", () =>
347 Effect.gen(function* () {
348 // A failed launch records its error, which names the target, on its span.
349 const failingLaunch = maybeOpenBrowser(pairingUrl).pipe(
350 Effect.provide(
351 Layer.mergeAll(
352 layerConfig({ noBrowser: false }),
353 Layer.mock(ExternalLauncher.ExternalLauncher)({
354 launchBrowser: (target) =>
355 Effect.fail(
356 new ExternalLauncherBrowserSpawnError({
357 target,
358 command: "xdg-open",
359 args: [target],
360 cause: new Error("spawn xdg-open ENOENT"),
361 }),
362 ).pipe(Effect.withSpan("externalLauncher.launchBrowser")),
363 }),
364 ),
365 ),
366 );
367 const { spans } = yield* logInSpanThrough({}, failingLaunch);
368​
369 const recorded = JSON.stringify(
370 spans.map((span) => ({
371 name: span.name,
372 events: span.events.map(([name, , attributes]) => [name, attributes]),
373 exit:
374 span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
375 ? Cause.pretty(span.status.exit.cause)
376 : null,
377 })),
378 );
379 assert.include(recorded, "browser auto-open unavailable");
380 assert.notInclude(recorded, pairingToken);
381 }),
382 );
383 });
384});