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

serverLogger.test.ts

318 lines10.9 KB

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