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