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 // Keep the primary log path stable for ops scripts and packaged-build inspection.
432 if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
433 return environment.path.join(environment.logDir, "server-child.log");
434 }
435 const sanitized = sanitizeInstanceIdForFileName(id);
436 return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
437};
438
439// IDs sharing a sanitized filename must share a writer to avoid currentSize races.
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 // Unpackaged runs launch a script, so Electron reports its own version.
601 serviceVersion: environment.isPackaged ? environment.appVersion : desktopPackageJson.version,
602 attributes: {
603 "service.namespace": "t3code",
604 "service.runtime": "desktop",
605 "service.mode": environment.isDevelopment ? "development" : "packaged",
606 "host.name": endpoints.resourceAttributes["host.name"] || (yield* HostProcess.Hostname),
607 },
608 };
609
610 // Logger.layer replaces the logger set. tracerLogger would duplicate OTLP in-span messages.
611 const layerLogger = Logger.layer(
612 endpoints.logs === undefined
613 ? [Logger.consolePretty(), Logger.tracerLogger]
614 : [
615 Logger.consolePretty(),
616 OtlpLogger.make({
617 url: endpoints.logs.url,
618 exportInterval: `${endpoints.logs.export.exportIntervalMs} millis`,
619 headers: endpoints.logs.export.headers,
620 resource,
621 }),
622 ],
623 { mergeWithExisting: false },
624 ).pipe(
625 Layer.provide(OtlpExporter.layerFlusher),
626 Layer.provide(
627 SharedObservability.layerOtlpSerialization(
628 endpoints.logs?.export.protocol ?? environment.otlpProtocol,
629 ),
630 ),
631 );
632
633 const layerTracer = Layer.unwrap(
634 Effect.gen(function* () {
635 const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
636 const sink = yield* makeTraceSink({
637 filePath: tracePath,
638 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
639 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
640 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
641 });
642 const delegate =
643 endpoints.traces === undefined
644 ? undefined
645 : yield* OtlpTracer.make({
646 url: endpoints.traces.url,
647 exportInterval: `${endpoints.traces.export.exportIntervalMs} millis`,
648 headers: endpoints.traces.export.headers,
649 resource,
650 }).pipe(
651 Effect.provide(
652 SharedObservability.layerOtlpSerialization(endpoints.traces.export.protocol),
653 ),
654 );
655 const tracer = yield* makeLocalFileTracer({
656 filePath: tracePath,
657 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
658 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
659 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
660 sink,
661 ...(delegate ? { delegate } : {}),
662 });
663
664 return Layer.succeed(Tracer.Tracer, tracer);
665 }),
666 ).pipe(Layer.provide(OtlpExporter.layerFlusher));
667
668 const layerOtelWarnings = Layer.effectDiscard(
669 Effect.forEach(endpoints.warnings, (warning) => Effect.logWarning(warning)),
670 );
671
672 return layerOtelWarnings.pipe(
673 Layer.provideMerge(Layer.mergeAll(layerLogger, layerTracer)),
674 Layer.provide(OtelEnvironment.layerResourceAttributes(endpoints.resourceAttributes)),
675 );
676 }),
677);
678
679export const layer = Layer.mergeAll(
680 layerBackendOutputLogFactory,
681 layerTelemetry,
682 Layer.succeed(References.MinimumLogLevel, "Info"),
683 Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
684 Layer.succeed(References.TracerTimingEnabled, true),
685);