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

DesktopObservability.ts

489 lines17.7 KB

1import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
2import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
3import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as PlatformError from "effect/PlatformError";
13import * as References from "effect/References";
14import * as Ref from "effect/Ref";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as Semaphore from "effect/Semaphore";
18import * as SynchronizedRef from "effect/SynchronizedRef";
19import * as Tracer from "effect/Tracer";
20import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
21​
22import * as DesktopEnvironment from "./DesktopEnvironment.ts";
23​
24const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
25const DESKTOP_LOG_FILE_MAX_FILES = 10;
26const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
27const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
28​
29export interface RotatingLogFileWriter {
30 readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
31 readonly writeText: (chunk: string) => Effect.Effect<void>;
33​
34export interface DesktopBackendOutputLogShape {
35 readonly writeSessionBoundary: (input: {
36 readonly phase: "START" | "END";
37 readonly details: string;
38 }) => Effect.Effect<void>;
39 readonly writeOutputChunk: (
40 streamName: "stdout" | "stderr",
41 chunk: Uint8Array,
42 ) => Effect.Effect<void>;
44​
45// Factory for per-instance backend output logs. `forInstance(id)` returns
46// a writer that targets a distinct rotating log file — the primary
47// instance keeps `server-child.log` so the historical path stays stable
48// for ops; other instances get `server-child-<sanitized-id>.log`.
49//
50// Writers are cached per id within a single factory instance so repeated
51// `forInstance` calls (e.g. during a backend restart that re-resolves
52// services) reuse the same rotating writer rather than racing each other
53// on the same file.
54export class DesktopBackendOutputLogFactory extends Context.Service<
55 DesktopBackendOutputLogFactory,
56 {
57 readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
58 }
59>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
60​
61const textEncoder = new TextEncoder();
62const textDecoder = new TextDecoder();
63​
64export type DesktopLogAnnotations = Record<string, unknown>;
65​
66export interface DesktopComponentLogger {
67 readonly annotate: <A, E, R>(
68 effect: Effect.Effect<A, E, R>,
69 annotations?: DesktopLogAnnotations,
70 ) => Effect.Effect<A, E, R>;
71 readonly logDebug: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
72 readonly logInfo: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
73 readonly logWarning: (
74 message: string,
75 annotations?: DesktopLogAnnotations,
76 ) => Effect.Effect<void>;
77 readonly logError: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
79​
80export function makeComponentLogger(component: string): DesktopComponentLogger {
81 const annotate: DesktopComponentLogger["annotate"] = (effect, annotations) =>
82 effect.pipe(
83 Effect.annotateLogs({
84 component,
85 ...annotations,
86 }),
87 );
88​
89 return {
90 annotate,
91 logDebug: (message, annotations) => annotate(Effect.logDebug(message), annotations),
92 logInfo: (message, annotations) => annotate(Effect.logInfo(message), annotations),
93 logWarning: (message, annotations) => annotate(Effect.logWarning(message), annotations),
94 logError: (message, annotations) => annotate(Effect.logError(message), annotations),
95 };
97​
98class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
99 "DesktopLogFileWriterConfigurationError",
100 {
101 option: Schema.Literals(["maxBytes", "maxFiles"]),
102 value: Schema.Number,
103 },
104) {
105 override get message() {
106 return `${this.option} must be >= 1 (received ${this.value})`;
107 }
109​
110type DesktopLogFileWriterError =
111 | DesktopLogFileWriterConfigurationError
112 | PlatformError.PlatformError;
113​
114const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
115​
116const DesktopBackendChildLogRecord = Schema.Struct({
117 message: Schema.String,
118 level: Schema.Literals(["INFO", "ERROR"]),
119 timestamp: Schema.String,
120 annotations: Schema.Record(Schema.String, Schema.Unknown),
121 spans: Schema.Record(Schema.String, Schema.Unknown),
122 fiberId: Schema.String,
123});
124​
125const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
126 Schema.fromJsonString(DesktopBackendChildLogRecord),
127);
128​
129const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
130 writeSessionBoundary: () => Effect.void,
131 writeOutputChunk: () => Effect.void,
132};
133​
134const currentDesktopRunId = Effect.gen(function* () {
135 const annotations = yield* References.CurrentLogAnnotations;
136 const runId = annotations.runId;
137 return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
138});
139​
140const refreshFileSize = (
141 fileSystem: FileSystem.FileSystem,
142 filePath: string,
143): Effect.Effect<number, never> =>
144 fileSystem.stat(filePath).pipe(
145 Effect.map((stat) => Number(stat.size)),
146 Effect.orElseSucceed(() => 0),
147 );
148​
149const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
150 readonly filePath: string;
151 readonly maxBytes?: number;
152 readonly maxFiles?: number;
153}): Effect.fn.Return<
154 RotatingLogFileWriter,
155 DesktopLogFileWriterError,
156 FileSystem.FileSystem | Path.Path
157> {
158 const fileSystem = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
161 const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
162 const directory = path.dirname(input.filePath);
163 const baseName = path.basename(input.filePath);
164​
165 if (maxBytes < 1) {
166 return yield* new DesktopLogFileWriterConfigurationError({
167 option: "maxBytes",
168 value: maxBytes,
169 });
170 }
171 if (maxFiles < 1) {
172 return yield* new DesktopLogFileWriterConfigurationError({
173 option: "maxFiles",
174 value: maxFiles,
175 });
176 }
177​
178 yield* fileSystem.makeDirectory(directory, { recursive: true });
179​
180 const withSuffix = (index: number) => `${input.filePath}.${index}`;
181 const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
182 const mutex = yield* Semaphore.make(1);
183​
184 const pruneOverflowBackups = Effect.gen(function* () {
185 const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
186 for (const entry of entries) {
187 if (!entry.startsWith(`${baseName}.`)) continue;
188 const suffix = Number(entry.slice(baseName.length + 1));
189 if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
190 yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
191 }
192 });
193​
194 const rotate = Effect.gen(function* () {
195 yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
196 for (let index = maxFiles - 1; index >= 1; index -= 1) {
197 const source = withSuffix(index);
198 const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
199 if (sourceExists) {
200 yield* fileSystem.rename(source, withSuffix(index + 1));
201 }
202 }
203 const currentExists = yield* fileSystem
204 .exists(input.filePath)
205 .pipe(Effect.orElseSucceed(() => false));
206 if (currentExists) {
207 yield* fileSystem.rename(input.filePath, withSuffix(1));
208 }
209 yield* Ref.set(currentSize, 0);
210 }).pipe(
211 Effect.catch(() =>
212 refreshFileSize(fileSystem, input.filePath).pipe(
213 Effect.flatMap((size) => Ref.set(currentSize, size)),
214 ),
215 ),
216 );
217​
218 const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
219 if (chunk.byteLength === 0) return Effect.void;
220​
221 return mutex.withPermits(1)(
222 Effect.gen(function* () {
223 const beforeSize = yield* Ref.get(currentSize);
224 if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
225 yield* rotate;
226 }
227​
228 yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
229 const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
230 yield* Ref.set(currentSize, afterSize);
231​
232 if (afterSize > maxBytes) {
233 yield* rotate;
234 }
235 }).pipe(
236 Effect.catch(() =>
237 refreshFileSize(fileSystem, input.filePath).pipe(
238 Effect.flatMap((size) => Ref.set(currentSize, size)),
239 ),
240 ),
241 ),
242 );
243 };
244​
245 yield* pruneOverflowBackups;
246​
247 return {
248 writeBytes,
249 writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
250 } satisfies RotatingLogFileWriter;
251});
252​
253const readPersistedOtlpTracesUrl: Effect.Effect<
254 Option.Option<string>,
255 never,
256 FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
257> = Effect.gen(function* () {
258 const fileSystem = yield* FileSystem.FileSystem;
259 const environment = yield* DesktopEnvironment.DesktopEnvironment;
260 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
261 if (Option.isNone(raw)) {
262 return Option.none();
263 }
264​
265 const parsed = parsePersistedServerObservabilitySettings(raw.value);
266 return Option.fromNullishOr(parsed.otlpTracesUrl);
267});
268​
269const resolveOtlpTracesUrl = Effect.gen(function* () {
270 const environment = yield* DesktopEnvironment.DesktopEnvironment;
271 if (Option.isSome(environment.otlpTracesUrl)) {
272 return environment.otlpTracesUrl;
273 }
274 return yield* readPersistedOtlpTracesUrl;
275});
276​
277const writeDevelopmentConsoleOutput = (
278 streamName: "stdout" | "stderr",
279 chunk: Uint8Array,
280): Effect.Effect<void> =>
281 Effect.sync(() => {
282 const output = streamName === "stderr" ? process.stderr : process.stdout;
283 output.write(chunk);
284 }).pipe(Effect.ignore);
285​
286const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
287 function* (
288 logFile: RotatingLogFileWriter,
289 input: {
290 readonly message: string;
291 readonly level: "INFO" | "ERROR";
292 readonly annotations: Record<string, unknown>;
293 },
294 ): Effect.fn.Return<void> {
295 return yield* Effect.gen(function* () {
296 const timestamp = DateTime.formatIso(yield* DateTime.now);
297 const encoded = yield* encodeDesktopBackendChildLogRecord({
298 message: input.message,
299 level: input.level,
300 timestamp,
301 annotations: input.annotations,
302 spans: {},
303 fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
304 });
305 yield* logFile.writeText(`${encoded}\n`);
306 }).pipe(Effect.ignore({ log: true }));
307 },
308);
309​
310const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
311​
312const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
313​
314const backendLogFilePathForInstance = (
315 environment: DesktopEnvironment.DesktopEnvironment["Service"],
316 id: string,
317): string => {
318 // Primary keeps the historical "server-child.log" path so ops scripts
319 // and packaged-build log inspection still find it where it always lived.
320 if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
321 return environment.path.join(environment.logDir, "server-child.log");
322 }
323 const sanitized = sanitizeInstanceIdForFileName(id);
324 return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
325};
326​
327// Just the IO sink. Cacheable by resolved file path so two ids that
328// sanitize to the same filename share a single RotatingLogFileWriter
329// (no race on currentSize tracking). Splitting the sink off from the
330// per-call shape lets the shape annotate writes with the *caller's*
331// id rather than whatever id created the cached writer first.
332const makeBackendOutputSinkForInstance = (
333 environment: DesktopEnvironment.DesktopEnvironment["Service"],
334 id: string,
335): Effect.Effect<
336 Option.Option<RotatingLogFileWriter>,
337 never,
338 FileSystem.FileSystem | Path.Path | Scope.Scope
339> =>
340 makeRotatingLogFileWriter({
341 filePath: backendLogFilePathForInstance(environment, id),
342 }).pipe(Effect.option);
343​
344const makeBackendOutputLogShape = (
345 environment: DesktopEnvironment.DesktopEnvironment["Service"],
346 id: string,
347 sink: Option.Option<RotatingLogFileWriter>,
348): DesktopBackendOutputLogShape =>
349 Option.match(sink, {
350 onNone: () => DesktopBackendOutputLogNoop,
351 onSome: (logFile) =>
352 ({
353 writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
354 function* ({ phase, details }) {
355 const runId = yield* currentDesktopRunId;
356 yield* writeBackendChildLogRecord(logFile, {
357 message: `backend child process session ${phase.toLowerCase()}`,
358 level: "INFO",
359 annotations: {
360 component: "desktop-backend-child",
361 runId,
362 instanceId: id,
363 phase,
364 details: sanitizeLogValue(details),
365 },
366 });
367 },
368 ),
369 writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
370 function* (streamName, chunk) {
371 if (environment.isDevelopment) {
372 yield* writeDevelopmentConsoleOutput(streamName, chunk);
373 }
374 const runId = yield* currentDesktopRunId;
375 yield* writeBackendChildLogRecord(logFile, {
376 message: "backend child process output",
377 level: streamName === "stderr" ? "ERROR" : "INFO",
378 annotations: {
379 component: "desktop-backend-child",
380 runId,
381 instanceId: id,
382 stream: streamName,
383 text: textDecoder.decode(chunk),
384 },
385 });
386 },
387 ),
388 }) satisfies DesktopBackendOutputLogShape,
389 });
390​
391const backendOutputLogFactoryLayer = Layer.effect(
392 DesktopBackendOutputLogFactory,
393 Effect.gen(function* () {
394 const environment = yield* DesktopEnvironment.DesktopEnvironment;
395 const fileSystem = yield* FileSystem.FileSystem;
396 const path = yield* Path.Path;
397 const factoryScope = yield* Scope.Scope;
398 // Per-file-path cache of the IO sink only. The per-call shape
399 // wraps the sink with the caller's instance id so a cache hit on
400 // a path collision (e.g. "wsl:default" and "wsl_default" both
401 // resolve to server-child-wsl_default.log) doesn't attribute the
402 // second caller's writes to the first caller's id. Each sink pins
403 // itself to the factory's scope so all log resources tear down
404 // together at app exit. Mutex serializes concurrent first-time
405 // lookups for the same file path.
406 const cacheRef = yield* SynchronizedRef.make<
407 ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
408 >(new Map());
409​
410 const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
411 SynchronizedRef.modifyEffect(cacheRef, (cache) => {
412 const cacheKey = backendLogFilePathForInstance(environment, id);
413 const cached = cache.get(cacheKey);
414 if (cached !== undefined) {
415 return Effect.succeed([
416 makeBackendOutputLogShape(environment, id, cached),
417 cache,
418 ] as const);
419 }
420 return makeBackendOutputSinkForInstance(environment, id).pipe(
421 Effect.provideService(FileSystem.FileSystem, fileSystem),
422 Effect.provideService(Path.Path, path),
423 Scope.provide(factoryScope),
424 Effect.map((sink) => {
425 const next = new Map(cache);
426 next.set(cacheKey, sink);
427 return [
428 makeBackendOutputLogShape(environment, id, sink),
429 next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
430 ] as const;
431 }),
432 );
433 });
434​
435 return DesktopBackendOutputLogFactory.of({
436 forInstance: (id) => makeForId(id),
437 });
438 }),
439);
440​
441const desktopLoggerLayer = Layer.mergeAll(
442 Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
443 Layer.succeed(References.MinimumLogLevel, "Info"),
444);
445​
446const tracerLayer = Layer.unwrap(
447 Effect.gen(function* () {
448 const environment = yield* DesktopEnvironment.DesktopEnvironment;
449 const otlpTracesUrl = yield* resolveOtlpTracesUrl;
450 const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
451 const sink = yield* makeTraceSink({
452 filePath: tracePath,
453 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
454 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
455 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
456 });
457 const delegate = Option.isNone(otlpTracesUrl)
458 ? undefined
459 : yield* OtlpTracer.make({
460 url: otlpTracesUrl.value,
461 exportInterval: `${environment.otlpExportIntervalMs} millis`,
462 resource: {
463 serviceName: "desktop",
464 attributes: {
465 "service.runtime": "desktop",
466 "service.mode": environment.isDevelopment ? "development" : "packaged",
467 },
468 },
469 });
470 const tracer = yield* makeLocalFileTracer({
471 filePath: tracePath,
472 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
473 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
474 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
475 sink,
476 ...(delegate ? { delegate } : {}),
477 });
478​
479 return Layer.succeed(Tracer.Tracer, tracer);
480 }),
481).pipe(Layer.provide(OtlpExporter.layerFlusher), Layer.provideMerge(OtlpSerialization.layerJson));
482​
483export const layer = Layer.mergeAll(
484 backendOutputLogFactoryLayer,
485 desktopLoggerLayer,
486 tracerLayer,
487 Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
488 Layer.succeed(References.TracerTimingEnabled, true),
489);