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

DesktopObservability.ts

744 lines27.1 KB

1import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
2import {
3 makeLocalFileTracer,
4 makeTraceSink,
5 type SignalExport,
6} from "@t3tools/shared/observability";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as SharedObservability from "@t3tools/shared/observability";
9import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
10import {
11 parsePersistedServerObservabilitySettings,
12 type PersistedServerObservabilitySettings,
13} from "@t3tools/shared/serverSettings";
14import * as Context from "effect/Context";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Logger from "effect/Logger";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import * as PlatformError from "effect/PlatformError";
23import * as References from "effect/References";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import * as Scope from "effect/Scope";
27import * as Semaphore from "effect/Semaphore";
28import * as SynchronizedRef from "effect/SynchronizedRef";
29import * as Tracer from "effect/Tracer";
30import { OtlpExporter, OtlpLogger, OtlpTracer } from "effect/observability";
31​
32import * as DesktopEnvironment from "./DesktopEnvironment.ts";
33​
34const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
35const DESKTOP_LOG_FILE_MAX_FILES = 10;
36const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
37const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
38const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
39const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
40​
41export interface RotatingLogFileWriter {
42 readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
43 readonly writeText: (chunk: string) => Effect.Effect<void>;
45​
46export interface DesktopBackendOutputLogShape {
47 readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
48 readonly writeOutputChunk: (
49 streamName: "stdout" | "stderr",
50 chunk: Uint8Array,
51 ) => Effect.Effect<void>;
52 readonly persistFailureSnapshot: (input: { readonly details: string }) => Effect.Effect<void>;
53 readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
54 readonly discardSession: Effect.Effect<void>;
56​
57// Factory for per-instance backend output logs. `forInstance(id)` returns
58// a writer that targets a distinct rotating log file — the primary
59// instance keeps `server-child.log` so the historical path stays stable
60// for ops; other instances get `server-child-<sanitized-id>.log`.
61//
62// Writers are cached per id within a single factory instance so repeated
63// `forInstance` calls (e.g. during a backend restart that re-resolves
64// services) reuse the same rotating writer rather than racing each other
65// on the same file.
66export class DesktopBackendOutputLogFactory extends Context.Service<
67 DesktopBackendOutputLogFactory,
68 {
69 readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
70 }
71>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
72​
73const textEncoder = new TextEncoder();
74const textDecoder = new TextDecoder();
75​
76export type DesktopLogAnnotations = Record<string, unknown>;
77​
78export interface DesktopComponentLogger {
79 readonly annotate: <A, E, R>(
80 effect: Effect.Effect<A, E, R>,
81 annotations?: DesktopLogAnnotations,
82 ) => Effect.Effect<A, E, R>;
83 readonly logDebug: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
84 readonly logInfo: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
85 readonly logWarning: (
86 message: string,
87 annotations?: DesktopLogAnnotations,
88 ) => Effect.Effect<void>;
89 readonly logError: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
91​
92export function makeComponentLogger(component: string): DesktopComponentLogger {
93 const annotate: DesktopComponentLogger["annotate"] = (effect, annotations) =>
94 effect.pipe(
95 Effect.annotateLogs({
96 component,
97 ...annotations,
98 }),
99 );
100​
101 return {
102 annotate,
103 logDebug: (message, annotations) => annotate(Effect.logDebug(message), annotations),
104 logInfo: (message, annotations) => annotate(Effect.logInfo(message), annotations),
105 logWarning: (message, annotations) => annotate(Effect.logWarning(message), annotations),
106 logError: (message, annotations) => annotate(Effect.logError(message), annotations),
107 };
109​
110class DesktopLogFileWriterConfigurationError extends Schema.TaggedError<DesktopLogFileWriterConfigurationError>()(
111 "DesktopLogFileWriterConfigurationError",
112 {
113 option: Schema.Literals(["maxBytes", "maxFiles"]),
114 value: Schema.Number,
115 },
116) {
117 override get message() {
118 return `${this.option} must be >= 1 (received ${this.value})`;
119 }
121​
122type DesktopLogFileWriterError =
123 | DesktopLogFileWriterConfigurationError
124 | PlatformError.PlatformError;
125​
126const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
127​
128const DesktopBackendChildLogRecord = Schema.Struct({
129 message: Schema.String,
130 level: Schema.Literals(["INFO", "ERROR"]),
131 timestamp: Schema.String,
132 annotations: Schema.Record(Schema.String, Schema.Unknown),
133 spans: Schema.Record(Schema.String, Schema.Unknown),
134 fiberId: Schema.String,
135});
136​
137const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
138 Schema.fromJsonString(DesktopBackendChildLogRecord),
139);
140​
141const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
142 beginSession: () => Effect.void,
143 writeOutputChunk: () => Effect.void,
144 persistFailureSnapshot: () => Effect.void,
145 persistFailure: () => Effect.void,
146 discardSession: Effect.void,
147};
148​
149interface BufferedBackendOutputChunk {
150 readonly streamName: "stdout" | "stderr";
151 readonly chunk: Uint8Array;
152 readonly offset: number;
154​
155interface BackendOutputSession {
156 readonly runId: string;
157 readonly startDetails: string;
158 readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
159 readonly byteLength: number;
161​
162export function appendBoundedOutputChunk(
163 session: BackendOutputSession,
164 streamName: "stdout" | "stderr",
165 chunk: Uint8Array,
166): BackendOutputSession {
167 if (chunk.byteLength === 0) {
168 return session;
169 }
170​
171 const retainedChunk =
172 chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
173 ? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
174 : chunk.slice();
175 const chunks = [...session.chunks, { streamName, chunk: retainedChunk, offset: 0 }];
176 let byteLength = session.byteLength + retainedChunk.byteLength;
177 let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
178 let firstRetainedIndex = 0;
179​
180 while (overflow > 0) {
181 const first = chunks[firstRetainedIndex];
182 if (!first) break;
183 const retainedByteLength = first.chunk.byteLength - first.offset;
184 if (retainedByteLength <= overflow) {
185 overflow -= retainedByteLength;
186 byteLength -= retainedByteLength;
187 firstRetainedIndex += 1;
188 continue;
189 }
190​
191 chunks[firstRetainedIndex] = {
192 ...first,
193 offset: first.offset + overflow,
194 };
195 byteLength -= overflow;
196 overflow = 0;
197 }
198​
199 const excessChunks = Math.max(
200 0,
201 chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
202 );
203 for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
204 const chunk = chunks[index];
205 byteLength -= chunk ? chunk.chunk.byteLength - chunk.offset : 0;
206 }
207 firstRetainedIndex += excessChunks;
208​
209 return {
210 ...session,
211 chunks: chunks.slice(firstRetainedIndex),
212 byteLength,
213 };
215​
216const currentDesktopRunId = Effect.gen(function* () {
217 const annotations = yield* References.CurrentLogAnnotations;
218 const runId = annotations.runId;
219 return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
220});
221​
222const refreshFileSize = (
223 fileSystem: FileSystem.FileSystem,
224 filePath: string,
225): Effect.Effect<number, never> =>
226 fileSystem.stat(filePath).pipe(
227 Effect.map((stat) => Number(stat.size)),
228 Effect.orElseSucceed(() => 0),
229 );
230​
231export const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
232 readonly filePath: string;
233 readonly maxBytes?: number;
234 readonly maxFiles?: number;
235}): Effect.fn.Return<
236 RotatingLogFileWriter,
237 DesktopLogFileWriterError,
238 FileSystem.FileSystem | Path.Path
239> {
240 const fileSystem = yield* FileSystem.FileSystem;
241 const path = yield* Path.Path;
242 const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
243 const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
244 const directory = path.dirname(input.filePath);
245 const baseName = path.basename(input.filePath);
246​
247 if (maxBytes < 1) {
248 return yield* new DesktopLogFileWriterConfigurationError({
249 option: "maxBytes",
250 value: maxBytes,
251 });
252 }
253 if (maxFiles < 1) {
254 return yield* new DesktopLogFileWriterConfigurationError({
255 option: "maxFiles",
256 value: maxFiles,
257 });
258 }
259​
260 yield* fileSystem.makeDirectory(directory, { recursive: true });
261​
262 const withSuffix = (index: number) => `${input.filePath}.${index}`;
263 const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
264 const mutex = yield* Semaphore.make(1);
265​
266 const pruneOverflowBackups = Effect.gen(function* () {
267 const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
268 for (const entry of entries) {
269 if (!entry.startsWith(`${baseName}.`)) continue;
270 const suffix = Number(entry.slice(baseName.length + 1));
271 if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
272 yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
273 }
274 });
275​
276 const rotate = Effect.gen(function* () {
277 yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
278 for (let index = maxFiles - 1; index >= 1; index -= 1) {
279 const source = withSuffix(index);
280 const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
281 if (sourceExists) {
282 yield* fileSystem.rename(source, withSuffix(index + 1));
283 }
284 }
285 const currentExists = yield* fileSystem
286 .exists(input.filePath)
287 .pipe(Effect.orElseSucceed(() => false));
288 if (currentExists) {
289 yield* fileSystem.rename(input.filePath, withSuffix(1));
290 }
291 yield* Ref.set(currentSize, 0);
292 }).pipe(
293 Effect.catch(() =>
294 refreshFileSize(fileSystem, input.filePath).pipe(
295 Effect.flatMap((size) => Ref.set(currentSize, size)),
296 ),
297 ),
298 );
299​
300 const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
301 if (chunk.byteLength === 0) return Effect.void;
302​
303 return mutex.withPermits(1)(
304 Effect.gen(function* () {
305 const beforeSize = yield* Ref.get(currentSize);
306 if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
307 yield* rotate;
308 }
309​
310 yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
311 const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
312 yield* Ref.set(currentSize, afterSize);
313​
314 if (afterSize > maxBytes) {
315 yield* rotate;
316 }
317 }).pipe(
318 Effect.catch(() =>
319 refreshFileSize(fileSystem, input.filePath).pipe(
320 Effect.flatMap((size) => Ref.set(currentSize, size)),
321 ),
322 ),
323 ),
324 );
325 };
326​
327 yield* pruneOverflowBackups;
328​
329 return {
330 writeBytes,
331 writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
332 } satisfies RotatingLogFileWriter;
333});
334​
335const noPersistedObservabilitySettings: PersistedServerObservabilitySettings = {
336 otlpTracesUrl: undefined,
337 otlpMetricsUrl: undefined,
338 otlpLogsUrl: undefined,
339};
340​
341const readPersistedObservabilitySettings: Effect.Effect<
342 PersistedServerObservabilitySettings,
343 never,
344 FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
345> = Effect.gen(function* () {
346 const fileSystem = yield* FileSystem.FileSystem;
347 const environment = yield* DesktopEnvironment.DesktopEnvironment;
348 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
349 return Option.isNone(raw)
350 ? noPersistedObservabilitySettings
351 : parsePersistedServerObservabilitySettings(raw.value);
352});
353​
354/**
355 * Resolved as the server resolves them, with persisted Settings as the
356 * fallback. Settings is read once for every signal, so the main process
357 * cannot resolve traces against one revision of the file and logs against
358 * another.
359 */
360const resolveOtlpEndpoints = Effect.gen(function* () {
361 const otel = yield* OtelEnvironment.load;
362 if (otel.disabled) {
363 return {
364 traces: undefined,
365 metrics: undefined,
366 logs: undefined,
367 warnings: otel.warnings,
368 resourceAttributes: otel.resourceAttributes,
369 };
370 }
371​
372 const environment = yield* DesktopEnvironment.DesktopEnvironment;
373 const persisted = yield* readPersistedObservabilitySettings;
374 const signalExport: SignalExport = {
375 protocol: environment.otlpProtocol,
376 headers: Option.getOrUndefined(environment.otlpHeaders),
377 exportIntervalMs: environment.otlpExportIntervalMs,
378 };
379 return {
380 traces: OtelEnvironment.resolveSignalEndpoint(
381 otel,
382 "traces",
383 { url: Option.getOrUndefined(environment.otlpTracesUrl), export: signalExport },
384 persisted.otlpTracesUrl,
385 ),
386 metrics: OtelEnvironment.resolveSignalEndpoint(
387 otel,
388 "metrics",
389 { url: Option.getOrUndefined(environment.otlpMetricsUrl), export: signalExport },
390 persisted.otlpMetricsUrl,
391 ),
392 logs: OtelEnvironment.resolveSignalEndpoint(
393 otel,
394 "logs",
395 { url: Option.getOrUndefined(environment.otlpLogsUrl), export: signalExport },
396 persisted.otlpLogsUrl,
397 ),
398 warnings: otel.warnings,
399 resourceAttributes: otel.resourceAttributes,
400 };
401});
402​
403const writeDevelopmentConsoleOutput = (
404 streamName: "stdout" | "stderr",
405 chunk: Uint8Array,
406): Effect.Effect<void> =>
407 Effect.sync(() => {
408 const output = streamName === "stderr" ? process.stderr : process.stdout;
409 output.write(chunk);
410 }).pipe(Effect.ignore);
411​
412const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
413 function* (
414 logFile: RotatingLogFileWriter,
415 input: {
416 readonly message: string;
417 readonly level: "INFO" | "ERROR";
418 readonly annotations: Record<string, unknown>;
419 },
420 ): Effect.fn.Return<void> {
421 return yield* Effect.gen(function* () {
422 const timestamp = DateTime.formatIso(yield* DateTime.now);
423 const encoded = yield* encodeDesktopBackendChildLogRecord({
424 message: input.message,
425 level: input.level,
426 timestamp,
427 annotations: input.annotations,
428 spans: {},
429 fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
430 });
431 yield* logFile.writeText(`${encoded}\n`);
432 }).pipe(Effect.ignore({ log: true }));
433 },
434);
435​
436const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
437​
438const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
439​
440const backendLogFilePathForInstance = (
441 environment: DesktopEnvironment.DesktopEnvironment["Service"],
442 id: string,
443): string => {
444 // Primary keeps the historical "server-child.log" path so ops scripts
445 // and packaged-build log inspection still find it where it always lived.
446 if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
447 return environment.path.join(environment.logDir, "server-child.log");
448 }
449 const sanitized = sanitizeInstanceIdForFileName(id);
450 return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
451};
452​
453// Just the IO sink. Cacheable by resolved file path so two ids that
454// sanitize to the same filename share a single RotatingLogFileWriter
455// (no race on currentSize tracking). Splitting the sink off from the
456// per-call shape lets the shape annotate writes with the *caller's*
457// id rather than whatever id created the cached writer first.
458const makeBackendOutputSinkForInstance = (
459 environment: DesktopEnvironment.DesktopEnvironment["Service"],
460 id: string,
461): Effect.Effect<
462 Option.Option<RotatingLogFileWriter>,
463 never,
464 FileSystem.FileSystem | Path.Path | Scope.Scope
465> =>
466 makeRotatingLogFileWriter({
467 filePath: backendLogFilePathForInstance(environment, id),
468 }).pipe(Effect.option);
469​
470const makeBackendOutputLogShape = (
471 environment: DesktopEnvironment.DesktopEnvironment["Service"],
472 id: string,
473 sink: Option.Option<RotatingLogFileWriter>,
474): Effect.Effect<DesktopBackendOutputLogShape> =>
475 Option.match(sink, {
476 onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
477 onSome: (logFile) =>
478 Effect.gen(function* () {
479 const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
480 const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
481 function* (session: BackendOutputSession, details: string) {
482 yield* writeBackendChildLogRecord(logFile, {
483 message: "backend child process failure output start",
484 level: "ERROR",
485 annotations: {
486 component: "desktop-backend-child",
487 runId: session.runId,
488 instanceId: id,
489 phase: "START",
490 details: session.startDetails,
491 },
492 });
493 for (const output of session.chunks) {
494 yield* writeBackendChildLogRecord(logFile, {
495 message: "backend child process output",
496 level: output.streamName === "stderr" ? "ERROR" : "INFO",
497 annotations: {
498 component: "desktop-backend-child",
499 runId: session.runId,
500 instanceId: id,
501 stream: output.streamName,
502 text: textDecoder.decode(output.chunk.subarray(output.offset)),
503 },
504 });
505 }
506 yield* writeBackendChildLogRecord(logFile, {
507 message: "backend child process failure output end",
508 level: "ERROR",
509 annotations: {
510 component: "desktop-backend-child",
511 runId: session.runId,
512 instanceId: id,
513 phase: "END",
514 details: sanitizeLogValue(details),
515 },
516 });
517 },
518 );
519 return {
520 beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
521 details,
522 }) {
523 const runId = yield* currentDesktopRunId;
524 yield* Ref.set(
525 sessionRef,
526 Option.some({
527 runId,
528 startDetails: sanitizeLogValue(details),
529 chunks: [],
530 byteLength: 0,
531 }),
532 );
533 }),
534 writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
535 if (environment.isDevelopment) {
536 yield* writeDevelopmentConsoleOutput(streamName, chunk);
537 }
538 yield* Ref.update(
539 sessionRef,
540 Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
541 );
542 }),
543 persistFailureSnapshot: Effect.fn(
544 "desktop.observability.backendOutput.persistFailureSnapshot",
545 )(function* ({ details }) {
546 const session = yield* Ref.get(sessionRef);
547 if (Option.isSome(session)) {
548 yield* writeFailure(session.value, details);
549 }
550 }),
551 persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
552 function* ({ details }) {
553 const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
554 if (Option.isNone(session)) return;
555 yield* writeFailure(session.value, details);
556 },
557 ),
558 discardSession: Ref.set(sessionRef, Option.none()),
559 } satisfies DesktopBackendOutputLogShape;
560 }),
561 });
562​
563const layerBackendOutputLogFactory = Layer.effect(
564 DesktopBackendOutputLogFactory,
565 Effect.gen(function* () {
566 const environment = yield* DesktopEnvironment.DesktopEnvironment;
567 const fileSystem = yield* FileSystem.FileSystem;
568 const path = yield* Path.Path;
569 const factoryScope = yield* Scope.Scope;
570 // Per-file-path cache of the IO sink only. The per-call shape
571 // wraps the sink with the caller's instance id so a cache hit on
572 // a path collision (e.g. "wsl:default" and "wsl_default" both
573 // resolve to server-child-wsl_default.log) doesn't attribute the
574 // second caller's writes to the first caller's id. Each sink pins
575 // itself to the factory's scope so all log resources tear down
576 // together at app exit. Mutex serializes concurrent first-time
577 // lookups for the same file path.
578 const cacheRef = yield* SynchronizedRef.make<
579 ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
580 >(new Map());
581​
582 const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
583 SynchronizedRef.modifyEffect(cacheRef, (cache) => {
584 const cacheKey = backendLogFilePathForInstance(environment, id);
585 const cached = cache.get(cacheKey);
586 if (cached !== undefined) {
587 return makeBackendOutputLogShape(environment, id, cached).pipe(
588 Effect.map((outputLog) => [outputLog, cache] as const),
589 );
590 }
591 return makeBackendOutputSinkForInstance(environment, id).pipe(
592 Effect.provideService(FileSystem.FileSystem, fileSystem),
593 Effect.provideService(Path.Path, path),
594 Scope.provide(factoryScope),
595 Effect.map((sink) => {
596 const next = new Map(cache);
597 next.set(cacheKey, sink);
598 return { sink, next };
599 }),
600 Effect.flatMap(({ sink, next }) =>
601 makeBackendOutputLogShape(environment, id, sink).pipe(
602 Effect.map(
603 (outputLog) =>
604 [
605 outputLog,
606 next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
607 ] as const,
608 ),
609 ),
610 ),
611 );
612 });
613​
614 return DesktopBackendOutputLogFactory.of({
615 forInstance: (id) => makeForId(id),
616 });
617 }),
618);
619​
620/**
621 * Logs and traces for the main process, assembled together because they share
622 * one read of the environment and Settings, and because a process gets exactly
623 * one logger set.
624 */
625const layerTelemetry = Layer.unwrap(
626 Effect.gen(function* () {
627 const environment = yield* DesktopEnvironment.DesktopEnvironment;
628 const endpoints = yield* resolveOtlpEndpoints;
629 // `host.name` keeps machines apart on a shared collector; one set in
630 // `OTEL_RESOURCE_ATTRIBUTES` wins, since explicit attributes override it.
631 const resource = {
632 serviceName: "t3code-desktop",
633 serviceVersion: environment.appVersion,
634 attributes: {
635 "service.namespace": "t3code",
636 "service.runtime": "desktop",
637 "service.mode": environment.isDevelopment ? "development" : "packaged",
638 "host.name": endpoints.resourceAttributes["host.name"] || (yield* HostProcess.Hostname),
639 },
640 };
641​
642 // `Logger.layer` writes the whole logger set rather than adding to it, so
643 // every logger the main process wants has to be named in this one call.
644 // Splitting the OTLP logger back out into a layer of its own silently
645 // drops either it or the console output.
646 //
647 // Swapping `Logger.tracerLogger` out for the OTLP logger matches the
648 // server: both reach a collector, but the tracer logger covers only
649 // messages logged inside a recorded span and files them under traces,
650 // while the OTLP logger carries every message as a log record stamped
651 // with its trace and span ids. Keeping both would export every in-span
652 // message twice.
653 const layerLogger = Logger.layer(
654 endpoints.logs === undefined
655 ? [Logger.consolePretty(), Logger.tracerLogger]
656 : [
657 Logger.consolePretty(),
658 OtlpLogger.make({
659 url: endpoints.logs.url,
660 exportInterval: `${endpoints.logs.export.exportIntervalMs} millis`,
661 headers: endpoints.logs.export.headers,
662 resource,
663 }),
664 ],
665 { mergeWithExisting: false },
666 ).pipe(
667 Layer.provide(OtlpExporter.layerFlusher),
668 Layer.provide(
669 SharedObservability.layerOtlpSerialization(
670 endpoints.logs?.export.protocol ?? environment.otlpProtocol,
671 ),
672 ),
673 );
674​
675 const layerTracer = Layer.unwrap(
676 Effect.gen(function* () {
677 const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
678 const sink = yield* makeTraceSink({
679 filePath: tracePath,
680 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
681 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
682 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
683 });
684 const delegate =
685 endpoints.traces === undefined
686 ? undefined
687 : yield* OtlpTracer.make({
688 url: endpoints.traces.url,
689 exportInterval: `${endpoints.traces.export.exportIntervalMs} millis`,
690 headers: endpoints.traces.export.headers,
691 resource,
692 }).pipe(
693 Effect.provide(
694 SharedObservability.layerOtlpSerialization(endpoints.traces.export.protocol),
695 ),
696 );
697 const tracer = yield* makeLocalFileTracer({
698 filePath: tracePath,
699 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
700 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
701 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
702 sink,
703 ...(delegate ? { delegate } : {}),
704 });
705​
706 return Layer.succeed(Tracer.Tracer, tracer);
707 }),
708 ).pipe(Layer.provide(OtlpExporter.layerFlusher));
709​
710 // Metrics stay off until the main process records one. `OtlpMetrics`
711 // exports on every interval even when the registry is empty, so wiring
712 // it up today would post an empty payload every ten seconds to any
713 // collector configured for the backend. Restore this when a desktop
714 // metric exists, and add it to the `Layer.mergeAll` below.
715 //
716 // const metricsLayer =
717 // endpoints.metrics === undefined
718 // ? Layer.empty
719 // : OtlpMetrics.layer({
720 // url: endpoints.metrics.url,
721 // exportInterval: `${endpoints.metrics.export.exportIntervalMs} millis`,
722 // headers: endpoints.metrics.export.headers,
723 // resource,
724 // }).pipe(Layer.provide(SharedObservability.layerOtlpSerialization(endpoints.metrics.export.protocol)));
725​
726 // Logged once the loggers above are installed, so the warnings use them.
727 const layerOtelWarnings = Layer.effectDiscard(
728 Effect.forEach(endpoints.warnings, (warning) => Effect.logWarning(warning)),
729 );
730​
731 return layerOtelWarnings.pipe(
732 Layer.provideMerge(Layer.mergeAll(layerLogger, layerTracer)),
733 Layer.provide(OtelEnvironment.layerResourceAttributes(endpoints.resourceAttributes)),
734 );
735 }),
736);
737​
738export const layer = Layer.mergeAll(
739 layerBackendOutputLogFactory,
740 layerTelemetry,
741 Layer.succeed(References.MinimumLogLevel, "Info"),
742 Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
743 Layer.succeed(References.TracerTimingEnabled, true),
744);