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