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

DesktopObservability.ts

697 lines24.6 KB

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>;
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>;
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>;
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 };
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 }
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;
150​
151interface BackendOutputSession {
152 readonly runId: string;
153 readonly startDetails: string;
154 readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
155 readonly byteLength: number;
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 };
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 onSome: (logFile) =>
463 Effect.gen(function* () {
464 const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
465 const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
466 function* (session: BackendOutputSession, details: string) {
467 yield* writeBackendChildLogRecord(logFile, {
468 message: "backend child process failure output start",
469 level: "ERROR",
470 annotations: {
471 component: "desktop-backend-child",
472 runId: session.runId,
473 instanceId: id,
474 phase: "START",
475 details: session.startDetails,
476 },
477 });
478 for (const output of session.chunks) {
479 yield* writeBackendChildLogRecord(logFile, {
480 message: "backend child process output",
481 level: output.streamName === "stderr" ? "ERROR" : "INFO",
482 annotations: {
483 component: "desktop-backend-child",
484 runId: session.runId,
485 instanceId: id,
486 stream: output.streamName,
487 text: textDecoder.decode(output.chunk.subarray(output.offset)),
488 },
489 });
490 }
491 yield* writeBackendChildLogRecord(logFile, {
492 message: "backend child process failure output end",
493 level: "ERROR",
494 annotations: {
495 component: "desktop-backend-child",
496 runId: session.runId,
497 instanceId: id,
498 phase: "END",
499 details: sanitizeLogValue(details),
500 },
501 });
502 },
503 );
504 return {
505 beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
506 details,
507 }) {
508 const runId = yield* currentDesktopRunId;
509 yield* Ref.set(
510 sessionRef,
511 Option.some({
512 runId,
513 startDetails: sanitizeLogValue(details),
514 chunks: [],
515 byteLength: 0,
516 }),
517 );
518 }),
519 writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
520 if (environment.isDevelopment) {
521 yield* writeDevelopmentConsoleOutput(streamName, chunk);
522 }
523 yield* Ref.update(
524 sessionRef,
525 Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
526 );
527 }),
528 persistFailureSnapshot: Effect.fn(
529 "desktop.observability.backendOutput.persistFailureSnapshot",
530 )(function* ({ details }) {
531 const session = yield* Ref.get(sessionRef);
532 if (Option.isSome(session)) {
533 yield* writeFailure(session.value, details);
534 }
535 }),
536 persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
537 function* ({ details }) {
538 const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
539 if (Option.isNone(session)) return;
540 yield* writeFailure(session.value, details);
541 },
542 ),
543 discardSession: Ref.set(sessionRef, Option.none()),
544 } satisfies DesktopBackendOutputLogShape;
545 }),
546 });
547​
548const layerBackendOutputLogFactory = Layer.effect(
549 DesktopBackendOutputLogFactory,
550 Effect.gen(function* () {
551 const environment = yield* DesktopEnvironment.DesktopEnvironment;
552 const fileSystem = yield* FileSystem.FileSystem;
553 const path = yield* Path.Path;
554 const factoryScope = yield* Scope.Scope;
555 const cacheRef = yield* SynchronizedRef.make<
556 ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
557 >(new Map());
558​
559 const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
560 SynchronizedRef.modifyEffect(cacheRef, (cache) => {
561 const cacheKey = backendLogFilePathForInstance(environment, id);
562 const cached = cache.get(cacheKey);
563 if (cached !== undefined) {
564 return makeBackendOutputLogShape(environment, id, cached).pipe(
565 Effect.map((outputLog) => [outputLog, cache] as const),
566 );
567 }
568 return makeBackendOutputSinkForInstance(environment, id).pipe(
569 Effect.provideService(FileSystem.FileSystem, fileSystem),
570 Effect.provideService(Path.Path, path),
571 Scope.provide(factoryScope),
572 Effect.map((sink) => {
573 const next = new Map(cache);
574 next.set(cacheKey, sink);
575 return { sink, next };
576 }),
577 Effect.flatMap(({ sink, next }) =>
578 makeBackendOutputLogShape(environment, id, sink).pipe(
579 Effect.map(
580 (outputLog) =>
581 [
582 outputLog,
583 next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
584 ] as const,
585 ),
586 ),
587 ),
588 );
589 });
590​
591 return DesktopBackendOutputLogFactory.of({
592 forInstance: (id) => makeForId(id),
593 });
594 }),
595);
596​
597const layerTelemetry = Layer.unwrap(
598 Effect.gen(function* () {
599 const environment = yield* DesktopEnvironment.DesktopEnvironment;
600 const endpoints = yield* resolveOtlpEndpoints;
601 // Unpackaged runs launch a script, so Electron reports its own version.
602 const serviceVersion = environment.isPackaged
603 ? environment.appVersion
604 : desktopPackageJson.version;
605 const resource = {
606 serviceName: "t3code-desktop",
607 serviceVersion,
608 attributes: {
609 "service.namespace": "t3code",
610 "service.runtime": "desktop",
611 "t3code.desktop.mode": environment.isDevelopment ? "development" : "packaged",
612 "service.instance.id": processServiceInstanceId(endpoints.resourceAttributes),
613 ...releaseResourceAttributes(
614 environment.isDevelopment ? "dev" : releaseChannelOf(serviceVersion),
615 endpoints.resourceAttributes,
616 ),
617 "host.name": endpoints.resourceAttributes["host.name"] || (yield* HostProcess.Hostname),
618 ...nodeProcessRuntimeAttributes(),
619 },
620 };
621​
622 // Logger.layer replaces the logger set. tracerLogger would duplicate OTLP in-span messages.
623 const layerLogger = Logger.layer(
624 endpoints.logs === undefined
625 ? [Logger.consolePretty(), Logger.tracerLogger]
626 : [
627 Logger.consolePretty(),
628 OtlpLogger.make({
629 url: endpoints.logs.url,
630 exportInterval: `${endpoints.logs.export.exportIntervalMs} millis`,
631 headers: endpoints.logs.export.headers,
632 resource,
633 }),
634 ],
635 { mergeWithExisting: false },
636 ).pipe(
637 Layer.provide(OtlpExporter.layerFlusher),
638 Layer.provide(
639 SharedObservability.layerOtlpSerialization(
640 endpoints.logs?.export.protocol ?? environment.otlpProtocol,
641 ),
642 ),
643 );
644​
645 const layerTracer = Layer.unwrap(
646 Effect.gen(function* () {
647 const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
648 const sink = yield* makeTraceSink({
649 filePath: tracePath,
650 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
651 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
652 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
653 });
654 const delegate =
655 endpoints.traces === undefined
656 ? undefined
657 : yield* OtlpTracer.make({
658 url: endpoints.traces.url,
659 exportInterval: `${endpoints.traces.export.exportIntervalMs} millis`,
660 headers: endpoints.traces.export.headers,
661 resource,
662 }).pipe(
663 Effect.provide(
664 SharedObservability.layerOtlpSerialization(endpoints.traces.export.protocol),
665 ),
666 );
667 const tracer = yield* makeLocalFileTracer({
668 filePath: tracePath,
669 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
670 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
671 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
672 sink,
673 ...(delegate ? { delegate } : {}),
674 });
675​
676 return Layer.succeed(Tracer.Tracer, tracer);
677 }),
678 ).pipe(Layer.provide(OtlpExporter.layerFlusher));
679​
680 const layerOtelWarnings = Layer.effectDiscard(
681 Effect.forEach(endpoints.warnings, (warning) => Effect.logWarning(warning)),
682 );
683​
684 return layerOtelWarnings.pipe(
685 Layer.provideMerge(Layer.mergeAll(layerLogger, layerTracer)),
686 Layer.provide(OtelEnvironment.layerResourceAttributes(endpoints.resourceAttributes)),
687 );
688 }),
689);
690​
691export const layer = Layer.mergeAll(
692 layerBackendOutputLogFactory,
693 layerTelemetry,
694 Layer.succeed(References.MinimumLogLevel, "Info"),
695 Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
696 Layer.succeed(References.TracerTimingEnabled, true),
697);