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 suffixText = entry.slice(baseName.length + 1);
267 const suffix = Number(suffixText);
268 if (!Number.isInteger(suffix) || String(suffix) !== suffixText || suffix <= maxFiles)
269 continue;
270 yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
271 }
272 });
273
274 const staged = `${input.filePath}.rotating`;
275 const publishStaged = Effect.gen(function* () {
276 yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
277 for (let index = maxFiles - 1; index >= 1; index -= 1) {
278 const source = withSuffix(index);
279 const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
280 if (sourceExists) {
281 yield* fileSystem.rename(source, withSuffix(index + 1));
282 }
283 }
284 yield* fileSystem.rename(staged, withSuffix(1));
285 });
286
287 const rotate = Effect.gen(function* () {
288 const exists = (filePath: string) =>
289 fileSystem.exists(filePath).pipe(Effect.orElseSucceed(() => false));
290 // A log left staged by an interrupted rotation becomes a backup first.
291 if (yield* exists(staged)) yield* publishStaged;
292 // Move the active log aside before touching backups: while it cannot move, none is aged out.
293 if (yield* exists(input.filePath)) {
294 yield* fileSystem.rename(input.filePath, staged);
295 yield* publishStaged;
296 }
297 yield* Ref.set(currentSize, 0);
298 }).pipe(
299 Effect.catch(() =>
300 refreshFileSize(fileSystem, input.filePath).pipe(
301 Effect.flatMap((size) => Ref.set(currentSize, size)),
302 ),
303 ),
304 );
305
306 const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
307 if (chunk.byteLength === 0) return Effect.void;
308
309 return mutex.withPermits(1)(
310 Effect.gen(function* () {
311 const beforeSize = yield* Ref.get(currentSize);
312 if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
313 yield* rotate;
314 }
315
316 yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
317 const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
318 yield* Ref.set(currentSize, afterSize);
319
320 if (afterSize > maxBytes) {
321 yield* rotate;
322 }
323 }).pipe(
324 Effect.catch(() =>
325 refreshFileSize(fileSystem, input.filePath).pipe(
326 Effect.flatMap((size) => Ref.set(currentSize, size)),
327 ),
328 ),
329 ),
330 );
331 };
332
333 yield* pruneOverflowBackups;
334
335 return {
336 writeBytes,
337 writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
338 } satisfies RotatingLogFileWriter;
339});
340
341const noPersistedObservabilitySettings: PersistedServerObservabilitySettings = {
342 otlpTracesUrl: undefined,
343 otlpMetricsUrl: undefined,
344 otlpLogsUrl: undefined,
345};
346
347const readPersistedObservabilitySettings: Effect.Effect<
348 PersistedServerObservabilitySettings,
349 never,
350 FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
351> = Effect.gen(function* () {
352 const fileSystem = yield* FileSystem.FileSystem;
353 const environment = yield* DesktopEnvironment.DesktopEnvironment;
354 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
355 return Option.isNone(raw)
356 ? noPersistedObservabilitySettings
357 : parsePersistedServerObservabilitySettings(raw.value);
358});
359
360const resolveOtlpEndpoints = Effect.gen(function* () {
361 const otel = yield* OtelEnvironment.load;
362 if (otel.disabled) {
363 return {
364 traces: undefined,
365 metrics: undefined,
366 logs: undefined,
367 warnings: otel.warnings,
368 resourceAttributes: otel.resourceAttributes,
369 };
370 }
371
372 const environment = yield* DesktopEnvironment.DesktopEnvironment;
373 const persisted = yield* readPersistedObservabilitySettings;
374 const signalExport: SignalExport = {
375 protocol: environment.otlpProtocol,
376 headers: Option.getOrUndefined(environment.otlpHeaders),
377 exportIntervalMs: environment.otlpExportIntervalMs,
378 };
379 return {
380 traces: OtelEnvironment.resolveSignalEndpoint(
381 otel,
382 "traces",
383 { url: Option.getOrUndefined(environment.otlpTracesUrl), export: signalExport },
384 { bootstrapUrl: undefined, settingsUrl: persisted.otlpTracesUrl },
385 ),
386 metrics: OtelEnvironment.resolveSignalEndpoint(
387 otel,
388 "metrics",
389 { url: Option.getOrUndefined(environment.otlpMetricsUrl), export: signalExport },
390 { bootstrapUrl: undefined, settingsUrl: persisted.otlpMetricsUrl },
391 ),
392 logs: OtelEnvironment.resolveSignalEndpoint(
393 otel,
394 "logs",
395 { url: Option.getOrUndefined(environment.otlpLogsUrl), export: signalExport },
396 { bootstrapUrl: undefined, settingsUrl: persisted.otlpLogsUrl },
397 ),
398 warnings: otel.warnings,
399 resourceAttributes: otel.resourceAttributes,
400 };
401});
402
403const writeDevelopmentConsoleOutput = (
404 streamName: "stdout" | "stderr",
405 chunk: Uint8Array,
406): Effect.Effect<void> =>
407 Effect.sync(() => {
408 const output = streamName === "stderr" ? process.stderr : process.stdout;
409 output.write(chunk);
410 }).pipe(Effect.ignore);
411
412const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
413 function* (
414 logFile: RotatingLogFileWriter,
415 input: {
416 readonly message: string;
417 readonly level: "INFO" | "ERROR";
418 readonly annotations: Record<string, unknown>;
419 },
420 ): Effect.fn.Return<void> {
421 return yield* Effect.gen(function* () {
422 const timestamp = DateTime.formatIso(yield* DateTime.now);
423 const encoded = yield* encodeDesktopBackendChildLogRecord({
424 message: input.message,
425 level: input.level,
426 timestamp,
427 annotations: input.annotations,
428 spans: {},
429 fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
430 });
431 yield* logFile.writeText(`${encoded}\n`);
432 }).pipe(Effect.ignore({ log: true }));
433 },
434);
435
436const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
437
438const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
439
440const backendLogFilePathForInstance = (
441 environment: DesktopEnvironment.DesktopEnvironment["Service"],
442 id: string,
443): string => {
444 // Keep the primary log path stable for ops scripts and packaged-build inspection.
445 if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
446 return environment.path.join(environment.logDir, "server-child.log");
447 }
448 const sanitized = sanitizeInstanceIdForFileName(id);
449 return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
450};
451
452// IDs sharing a sanitized filename must share a writer to avoid currentSize races.
453const makeBackendOutputSinkForInstance = (
454 environment: DesktopEnvironment.DesktopEnvironment["Service"],
455 id: string,
456): Effect.Effect<
457 Option.Option<RotatingLogFileWriter>,
458 never,
459 FileSystem.FileSystem | Path.Path | Scope.Scope
460> =>
461 makeRotatingLogFileWriter({
462 filePath: backendLogFilePathForInstance(environment, id),
463 }).pipe(Effect.option);
464
465const makeBackendOutputLogShape = (
466 environment: DesktopEnvironment.DesktopEnvironment["Service"],
467 id: string,
468 sink: Option.Option<RotatingLogFileWriter>,
469): Effect.Effect<DesktopBackendOutputLogShape> =>
470 Option.match(sink, {
471 onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
472 // The enclosing operation owns the span for this inline handler.
473 onSome: Effect.fnUntraced(function* (logFile) {
474 const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
475 const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(function* (
476 session: BackendOutputSession,
477 details: string,
478 ) {
479 yield* writeBackendChildLogRecord(logFile, {
480 message: "backend child process failure output start",
481 level: "ERROR",
482 annotations: {
483 component: "desktop-backend-child",
484 runId: session.runId,
485 instanceId: id,
486 phase: "START",
487 details: session.startDetails,
488 },
489 });
490 for (const output of session.chunks) {
491 yield* writeBackendChildLogRecord(logFile, {
492 message: "backend child process output",
493 level: output.streamName === "stderr" ? "ERROR" : "INFO",
494 annotations: {
495 component: "desktop-backend-child",
496 runId: session.runId,
497 instanceId: id,
498 stream: output.streamName,
499 text: textDecoder.decode(output.chunk.subarray(output.offset)),
500 },
501 });
502 }
503 yield* writeBackendChildLogRecord(logFile, {
504 message: "backend child process failure output end",
505 level: "ERROR",
506 annotations: {
507 component: "desktop-backend-child",
508 runId: session.runId,
509 instanceId: id,
510 phase: "END",
511 details: sanitizeLogValue(details),
512 },
513 });
514 });
515 return {
516 beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
517 details,
518 }) {
519 const runId = yield* currentDesktopRunId;
520 yield* Ref.set(
521 sessionRef,
522 Option.some({
523 runId,
524 startDetails: sanitizeLogValue(details),
525 chunks: [],
526 byteLength: 0,
527 }),
528 );
529 }),
530 writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
531 if (environment.isDevelopment) {
532 yield* writeDevelopmentConsoleOutput(streamName, chunk);
533 }
534 yield* Ref.update(
535 sessionRef,
536 Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
537 );
538 }),
539 persistFailureSnapshot: Effect.fn(
540 "desktop.observability.backendOutput.persistFailureSnapshot",
541 )(function* ({ details }) {
542 const session = yield* Ref.get(sessionRef);
543 if (Option.isSome(session)) {
544 yield* writeFailure(session.value, details);
545 }
546 }),
547 persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({
548 details,
549 }) {
550 const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
551 if (Option.isNone(session)) return;
552 yield* writeFailure(session.value, details);
553 }),
554 discardSession: Ref.set(sessionRef, Option.none()),
555 } satisfies DesktopBackendOutputLogShape;
556 }),
557 });
558
559const layerBackendOutputLogFactory = Layer.effect(
560 DesktopBackendOutputLogFactory,
561 Effect.gen(function* () {
562 const environment = yield* DesktopEnvironment.DesktopEnvironment;
563 const fileSystem = yield* FileSystem.FileSystem;
564 const path = yield* Path.Path;
565 const factoryScope = yield* Scope.Scope;
566 const cacheRef = yield* SynchronizedRef.make<
567 ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
568 >(new Map());
569
570 const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
571 SynchronizedRef.modifyEffect(cacheRef, (cache) => {
572 const cacheKey = backendLogFilePathForInstance(environment, id);
573 const cached = cache.get(cacheKey);
574 if (cached !== undefined) {
575 return makeBackendOutputLogShape(environment, id, cached).pipe(
576 Effect.map((outputLog) => [outputLog, cache] as const),
577 );
578 }
579 return makeBackendOutputSinkForInstance(environment, id).pipe(
580 Effect.provideService(FileSystem.FileSystem, fileSystem),
581 Effect.provideService(Path.Path, path),
582 Scope.provide(factoryScope),
583 Effect.map((sink) => {
584 const next = new Map(cache);
585 next.set(cacheKey, sink);
586 return { sink, next };
587 }),
588 Effect.flatMap(({ sink, next }) =>
589 makeBackendOutputLogShape(environment, id, sink).pipe(
590 Effect.map(
591 (outputLog) =>
592 [
593 outputLog,
594 next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
595 ] as const,
596 ),
597 ),
598 ),
599 );
600 });
601
602 return DesktopBackendOutputLogFactory.of({
603 forInstance: Effect.fn("DesktopBackendOutputLogFactory.forInstance")(function (id) {
604 return makeForId(id);
605 }),
606 });
607 }),
608);
609
610const layerTelemetry = Layer.unwrap(
611 Effect.gen(function* () {
612 const environment = yield* DesktopEnvironment.DesktopEnvironment;
613 const endpoints = yield* resolveOtlpEndpoints;
614 // Unpackaged runs launch a script, so Electron reports its own version.
615 const serviceVersion = environment.isPackaged
616 ? environment.appVersion
617 : desktopPackageJson.version;
618 const resource = {
619 serviceName: "t3code-desktop",
620 serviceVersion,
621 attributes: {
622 "service.namespace": "t3code",
623 "service.runtime": "desktop",
624 "t3code.desktop.mode": environment.isDevelopment ? "development" : "packaged",
625 "service.instance.id": processServiceInstanceId(endpoints.resourceAttributes),
626 ...releaseResourceAttributes(
627 environment.isDevelopment ? "dev" : releaseChannelOf(serviceVersion),
628 endpoints.resourceAttributes,
629 ),
630 "host.name": endpoints.resourceAttributes["host.name"] || (yield* HostProcess.Hostname),
631 ...nodeProcessRuntimeAttributes(),
632 },
633 };
634
635 // Logger.layer replaces the logger set. tracerLogger would duplicate OTLP in-span messages.
636 const layerLogger = Logger.layer(
637 endpoints.logs === undefined
638 ? [Logger.consolePretty(), Logger.tracerLogger]
639 : [
640 Logger.consolePretty(),
641 OtlpLogger.make({
642 url: endpoints.logs.url,
643 exportInterval: `${endpoints.logs.export.exportIntervalMs} millis`,
644 headers: endpoints.logs.export.headers,
645 resource,
646 }),
647 ],
648 { mergeWithExisting: false },
649 ).pipe(
650 Layer.provide(OtlpExporter.layerFlusher),
651 Layer.provide(
652 SharedObservability.layerOtlpSerialization(
653 endpoints.logs?.export.protocol ?? environment.otlpProtocol,
654 ),
655 ),
656 );
657
658 const layerTracer = Layer.unwrap(
659 Effect.gen(function* () {
660 const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
661 const sink = yield* makeTraceSink({
662 filePath: tracePath,
663 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
664 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
665 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
666 });
667 // Unscoped: Electron can exit without closing the app scope, e.g. when the display drops.
668 process.once("exit", sink.flushSync);
669 const delegate =
670 endpoints.traces === undefined
671 ? undefined
672 : yield* OtlpTracer.make({
673 url: endpoints.traces.url,
674 exportInterval: `${endpoints.traces.export.exportIntervalMs} millis`,
675 headers: endpoints.traces.export.headers,
676 resource,
677 }).pipe(
678 Effect.provide(
679 SharedObservability.layerOtlpSerialization(endpoints.traces.export.protocol),
680 ),
681 );
682 const tracer = yield* makeLocalFileTracer({
683 filePath: tracePath,
684 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
685 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
686 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
687 sink,
688 ...(delegate ? { delegate } : {}),
689 });
690
691 return Layer.succeed(Tracer.Tracer, tracer);
692 }),
693 ).pipe(Layer.provide(OtlpExporter.layerFlusher));
694
695 const layerOtelWarnings = Layer.effectDiscard(
696 Effect.forEach(endpoints.warnings, (warning) => Effect.logWarning(warning)),
697 );
698
699 return layerOtelWarnings.pipe(
700 Layer.provideMerge(Layer.mergeAll(layerLogger, layerTracer)),
701 Layer.provide(OtelEnvironment.layerResourceAttributes(endpoints.resourceAttributes)),
702 );
703 }),
704);
705
706export const layer = Layer.mergeAll(
707 layerBackendOutputLogFactory,
708 layerTelemetry,
709 Layer.succeed(References.MinimumLogLevel, "Info"),
710 Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
711 Layer.succeed(References.TracerTimingEnabled, true),
712);