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

DesktopObservability.ts

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