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

DesktopObservability.ts

706 lines25.8 KB

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