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

serverLogger.test.ts

273 lines9.6 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 Console from "effect/Console";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Layer from "effect/Layer";
12import * as Redactable from "effect/Redactable";
13import * as Path from "effect/Path";
14import * as Tracer from "effect/Tracer";
15import * as HttpClient from "effect/http/HttpClient";
16import * as HttpClientResponse from "effect/http/HttpClientResponse";
17import * as TestConsole from "effect/testing/TestConsole";
18​
19import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
20import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
21​
22import * as ServerConfig from "./config.ts";
23import * as ExternalLauncher from "./process/externalLauncher.ts";
24import * as ServerLogger from "./serverLogger.ts";
25import {
26 announceStartupPairingUrl,
27 logBrowserAutoOpenUnavailable,
28 maybeOpenBrowser,
29} from "./serverRuntimeStartup.ts";
30​
31interface ExportedRequest {
32 readonly url: string;
33 readonly headers: Readonly<Record<string, string>>;
34 readonly body: string;
36​
37const layerCollector = (requests: Array<ExportedRequest>) =>
38 Layer.succeed(
39 HttpClient.HttpClient,
40 HttpClient.make((request) =>
41 Effect.sync(() => {
42 requests.push({
43 url: request.url,
44 headers: request.headers,
45 body:
46 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
47 });
48 return HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }));
49 }),
50 ),
51 );
52​
53const layerConfig = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
54 Layer.effect(
55 ServerConfig.ServerConfig,
56 Effect.gen(function* () {
57 const path = yield* Path.Path;
58 const baseDir = path.join(NodeOS.tmpdir(), "t3-server-logger-test");
59 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
60 return ServerConfig.make({
61 logLevel: "Info",
62 traceMinLevel: "Info",
63 traceTimingEnabled: false,
64 traceBatchWindowMs: 200,
65 traceMaxBytes: 1024,
66 traceMaxFiles: 1,
67 otlpTracesUrl: undefined,
68 otlpMetricsUrl: undefined,
69 otlpLogsUrl: undefined,
70 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
71 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
72 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
73 otelEnvironment: OtelEnvironment.none,
74 cwd: baseDir,
75 baseDir,
76 ...derivedPaths,
77 mode: "web",
78 autoBootstrapProjectFromCwd: false,
79 logWebSocketEvents: false,
80 tailscaleServeEnabled: false,
81 tailscaleServePort: 443,
82 port: 0,
83 host: undefined,
84 desktopBootstrapToken: undefined,
85 desktopTelemetryFd: undefined,
86 desktopTelemetryControlFd: undefined,
87 resourceMonitorPath: undefined,
88 staticDir: undefined,
89 devUrl: undefined,
90 devAllowedOrigins: [],
91 noBrowser: false,
92 startupPresentation: "browser",
93 ...overrides,
94 });
95 }),
96 ).pipe(Layer.provide(NodePath.layer));
97​
98/**
99 * Runs `program` (one log line by default) inside a span so the tracer logger
100 * has somewhere to attach an event, then reports both what the collector
101 * received and what landed on the span.
102 */
103const logInSpanThrough = (
104 overrides: Partial<ServerConfig.ServerConfig["Service"]>,
105 program: Effect.Effect<void> = Effect.log("server logger under test"),
106) =>
107 Effect.gen(function* () {
108 const requests: Array<ExportedRequest> = [];
109 const spans: Array<Tracer.NativeSpan> = [];
110 const layerTracer = Layer.succeed(
111 Tracer.Tracer,
112 Tracer.make({
113 span: (spanOptions) => {
114 const span = new Tracer.NativeSpan(spanOptions);
115 spans.push(span);
116 return span;
117 },
118 }),
119 );
120 yield* program.pipe(
121 Effect.withSpan("server-logger-test"),
122 Effect.provide(
123 Layer.mergeAll(
124 ServerLogger.layer.pipe(
125 Layer.provide(layerConfig(overrides)),
126 Layer.provide(layerCollector(requests)),
127 ),
128 layerTracer,
129 ),
130 ),
131 );
132 return { requests, spans };
133 });
134​
135/** Logs one warning through the server logger and returns what its console printed. */
136const printThroughConsole = (fields: object) =>
137 Effect.gen(function* () {
138 const printed: Array<string> = [];
139 const testConsole = {
140 ...globalThis.console,
141 log: (...args: ReadonlyArray<unknown>) => {
142 printed.push(NodeUtil.format(...args));
143 },
144 } satisfies Console.Console;
145 yield* Effect.logWarning("pull request watch check failed", fields).pipe(
146 Effect.provide(
147 ServerLogger.layer.pipe(Layer.provide(layerConfig({})), Layer.provide(layerCollector([]))),
148 ),
149 Effect.provideService(Console.Console, testConsole),
150 );
151 return printed.join("\n");
152 });
153​
154describe("ServerLoggerLive", () => {
155 it.effect("prints a cause passed as a log field instead of collapsing it", () =>
156 Effect.gen(function* () {
157 const output = yield* printThroughConsole({
158 threadId: "thread-1",
159 cause: Cause.fail(new Error("gh: HTTP 502 from api.github.com")),
160 });
161​
162 assert.include(output, "threadId: 'thread-1'");
163 assert.include(output, "gh: HTTP 502 from api.github.com");
164 assert.notInclude(output, "[Object]");
165 }),
166 );
167​
168 // regression: #16642 logs printed causes as [Object]
169 it.effect("leaves getters uncalled while printing a cause field", () =>
170 Effect.gen(function* () {
171 const output = yield* printThroughConsole({
172 cause: Cause.fail(new Error("upstream refused")),
173 get detail(): string {
174 throw new Error("getter must not run");
175 },
176 });
177​
178 assert.include(output, "upstream refused");
179 assert.notInclude(output, "getter must not run");
180 }),
181 );
182​
183 it.effect("leaves a message with its own redaction hook to that hook", () =>
184 Effect.gen(function* () {
185 const output = yield* printThroughConsole({
186 token: "secret-token-value",
187 cause: Cause.fail(new Error("upstream refused")),
188 [Redactable.symbolRedactable](this: { readonly cause: unknown }) {
189 return { token: "<redacted>", cause: Cause.isCause(this.cause) ? "cause" : "missing" };
190 },
191 });
192​
193 assert.include(output, "token: '<redacted>'");
194 assert.include(output, "cause: 'cause'");
195 assert.notInclude(output, "secret-token-value");
196 }),
197 );
198​
199 describe("startup pairing URL", () => {
200 const pairingToken = "PAIRTOKEN7Q4K9";
201 const pairingUrl = `http://localhost:3773/pair#token=${pairingToken}`;
202 const announce = announceStartupPairingUrl(pairingUrl).pipe(
203 Effect.andThen(logBrowserAutoOpenUnavailable),
204 );
205​
206 it.effect("prints the full URL but keeps its token out of exported log records", () =>
207 Effect.gen(function* () {
208 const { requests } = yield* logInSpanThrough(
209 { otlpLogsUrl: "https://collector.example.com/v1/logs" },
210 announce,
211 );
212​
213 const body = requests.map((request) => request.body).join("\n");
214 assert.include(body, "Authentication required");
215 assert.notInclude(body, pairingToken);
216 const printed = (yield* TestConsole.logLines).map((line) =>
217 Array.isArray(line) ? line.join(" ") : String(line),
218 );
219 assert.isTrue(printed.some((line) => line.includes(`pairingUrl: ${pairingUrl}`)));
220 }).pipe(Effect.provide(TestConsole.layer)),
221 );
222​
223 it.effect("keeps the token off the span events the trace file records", () =>
224 Effect.gen(function* () {
225 const { spans } = yield* logInSpanThrough({}, announce);
226​
227 const events = JSON.stringify(
228 spans.flatMap((span) => span.events.map(([name, , attributes]) => [name, attributes])),
229 );
230 assert.include(events, "Authentication required");
231 assert.notInclude(events, pairingToken);
232 }).pipe(Effect.provide(TestConsole.layer)),
233 );
234​
235 it.effect("keeps the token out of traces when the browser fails to open", () =>
236 Effect.gen(function* () {
237 // A failed launch records its error, which names the target, on its span.
238 const failingLaunch = maybeOpenBrowser(pairingUrl).pipe(
239 Effect.provide(
240 Layer.mergeAll(
241 layerConfig({ noBrowser: false }),
242 Layer.mock(ExternalLauncher.ExternalLauncher)({
243 launchBrowser: (target) =>
244 Effect.fail(
245 new ExternalLauncherBrowserSpawnError({
246 target,
247 command: "xdg-open",
248 args: [target],
249 cause: new Error("spawn xdg-open ENOENT"),
250 }),
251 ).pipe(Effect.withSpan("externalLauncher.launchBrowser")),
252 }),
253 ),
254 ),
255 );
256 const { spans } = yield* logInSpanThrough({}, failingLaunch);
257​
258 const recorded = JSON.stringify(
259 spans.map((span) => ({
260 name: span.name,
261 events: span.events.map(([name, , attributes]) => [name, attributes]),
262 exit:
263 span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
264 ? Cause.pretty(span.status.exit.cause)
265 : null,
266 })),
267 );
268 assert.include(recorded, "browser auto-open unavailable");
269 assert.notInclude(recorded, pairingToken);
270 }),
271 );
272 });
273});