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