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

DesktopObservability.ts

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