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

DesktopObservability.ts

395 lines13.5 KB

1import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
2import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3import * as Context from "effect/Context";
4import * as Data from "effect/Data";
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 Semaphore from "effect/Semaphore";
17import * as Tracer from "effect/Tracer";
18import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
19​
20import * as DesktopEnvironment from "./DesktopEnvironment.ts";
21​
22const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
23const DESKTOP_LOG_FILE_MAX_FILES = 10;
24const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
25const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
26​
27export interface RotatingLogFileWriter {
28 readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
29 readonly writeText: (chunk: string) => Effect.Effect<void>;
31​
32export interface DesktopBackendOutputLogShape {
33 readonly writeSessionBoundary: (input: {
34 readonly phase: "START" | "END";
35 readonly details: string;
36 }) => Effect.Effect<void>;
37 readonly writeOutputChunk: (
38 streamName: "stdout" | "stderr",
39 chunk: Uint8Array,
40 ) => Effect.Effect<void>;
42​
43export class DesktopBackendOutputLog extends Context.Service<
44 DesktopBackendOutputLog,
45 DesktopBackendOutputLogShape
46>()("t3/desktop/BackendOutputLog") {}
47​
48const textEncoder = new TextEncoder();
49const textDecoder = new TextDecoder();
50​
51export type DesktopLogAnnotations = Record<string, unknown>;
52​
53export interface DesktopComponentLogger {
54 readonly annotate: <A, E, R>(
55 effect: Effect.Effect<A, E, R>,
56 annotations?: DesktopLogAnnotations,
57 ) => Effect.Effect<A, E, R>;
58 readonly logDebug: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
59 readonly logInfo: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
60 readonly logWarning: (
61 message: string,
62 annotations?: DesktopLogAnnotations,
63 ) => Effect.Effect<void>;
64 readonly logError: (message: string, annotations?: DesktopLogAnnotations) => Effect.Effect<void>;
66​
67export function makeComponentLogger(component: string): DesktopComponentLogger {
68 const annotate: DesktopComponentLogger["annotate"] = (effect, annotations) =>
69 effect.pipe(
70 Effect.annotateLogs({
71 component,
72 ...annotations,
73 }),
74 );
75​
76 return {
77 annotate,
78 logDebug: (message, annotations) => annotate(Effect.logDebug(message), annotations),
79 logInfo: (message, annotations) => annotate(Effect.logInfo(message), annotations),
80 logWarning: (message, annotations) => annotate(Effect.logWarning(message), annotations),
81 logError: (message, annotations) => annotate(Effect.logError(message), annotations),
82 };
84​
85class DesktopLogFileWriterConfigurationError extends Data.TaggedError(
86 "DesktopLogFileWriterConfigurationError",
87)<{
88 readonly option: "maxBytes" | "maxFiles";
89 readonly value: number;
90}> {
91 override get message() {
92 return `${this.option} must be >= 1 (received ${this.value})`;
93 }
95​
96type DesktopLogFileWriterError =
97 | DesktopLogFileWriterConfigurationError
98 | PlatformError.PlatformError;
99​
100const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
101​
102const DesktopBackendChildLogRecord = Schema.Struct({
103 message: Schema.String,
104 level: Schema.Literals(["INFO", "ERROR"]),
105 timestamp: Schema.String,
106 annotations: Schema.Record(Schema.String, Schema.Unknown),
107 spans: Schema.Record(Schema.String, Schema.Unknown),
108 fiberId: Schema.String,
109});
110​
111const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
112 Schema.fromJsonString(DesktopBackendChildLogRecord),
113);
114​
115const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
116 writeSessionBoundary: () => Effect.void,
117 writeOutputChunk: () => Effect.void,
118};
119​
120const currentDesktopRunId = Effect.gen(function* () {
121 const annotations = yield* References.CurrentLogAnnotations;
122 const runId = annotations.runId;
123 return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
124});
125​
126const refreshFileSize = (
127 fileSystem: FileSystem.FileSystem,
128 filePath: string,
129): Effect.Effect<number, never> =>
130 fileSystem.stat(filePath).pipe(
131 Effect.map((stat) => Number(stat.size)),
132 Effect.orElseSucceed(() => 0),
133 );
134​
135const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
136 readonly filePath: string;
137 readonly maxBytes?: number;
138 readonly maxFiles?: number;
139}): Effect.fn.Return<
140 RotatingLogFileWriter,
141 DesktopLogFileWriterError,
142 FileSystem.FileSystem | Path.Path
143> {
144 const fileSystem = yield* FileSystem.FileSystem;
145 const path = yield* Path.Path;
146 const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
147 const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
148 const directory = path.dirname(input.filePath);
149 const baseName = path.basename(input.filePath);
150​
151 if (maxBytes < 1) {
152 return yield* new DesktopLogFileWriterConfigurationError({
153 option: "maxBytes",
154 value: maxBytes,
155 });
156 }
157 if (maxFiles < 1) {
158 return yield* new DesktopLogFileWriterConfigurationError({
159 option: "maxFiles",
160 value: maxFiles,
161 });
162 }
163​
164 yield* fileSystem.makeDirectory(directory, { recursive: true });
165​
166 const withSuffix = (index: number) => `${input.filePath}.${index}`;
167 const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
168 const mutex = yield* Semaphore.make(1);
169​
170 const pruneOverflowBackups = Effect.gen(function* () {
171 const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
172 for (const entry of entries) {
173 if (!entry.startsWith(`${baseName}.`)) continue;
174 const suffix = Number(entry.slice(baseName.length + 1));
175 if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
176 yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
177 }
178 });
179​
180 const rotate = Effect.gen(function* () {
181 yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
182 for (let index = maxFiles - 1; index >= 1; index -= 1) {
183 const source = withSuffix(index);
184 const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
185 if (sourceExists) {
186 yield* fileSystem.rename(source, withSuffix(index + 1));
187 }
188 }
189 const currentExists = yield* fileSystem
190 .exists(input.filePath)
191 .pipe(Effect.orElseSucceed(() => false));
192 if (currentExists) {
193 yield* fileSystem.rename(input.filePath, withSuffix(1));
194 }
195 yield* Ref.set(currentSize, 0);
196 }).pipe(
197 Effect.catch(() =>
198 refreshFileSize(fileSystem, input.filePath).pipe(
199 Effect.flatMap((size) => Ref.set(currentSize, size)),
200 ),
201 ),
202 );
203​
204 const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
205 if (chunk.byteLength === 0) return Effect.void;
206​
207 return mutex.withPermits(1)(
208 Effect.gen(function* () {
209 const beforeSize = yield* Ref.get(currentSize);
210 if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
211 yield* rotate;
212 }
213​
214 yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
215 const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
216 yield* Ref.set(currentSize, afterSize);
217​
218 if (afterSize > maxBytes) {
219 yield* rotate;
220 }
221 }).pipe(
222 Effect.catch(() =>
223 refreshFileSize(fileSystem, input.filePath).pipe(
224 Effect.flatMap((size) => Ref.set(currentSize, size)),
225 ),
226 ),
227 ),
228 );
229 };
230​
231 yield* pruneOverflowBackups;
232​
233 return {
234 writeBytes,
235 writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
236 } satisfies RotatingLogFileWriter;
237});
238​
239const readPersistedOtlpTracesUrl: Effect.Effect<
240 Option.Option<string>,
241 never,
242 FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
243> = Effect.gen(function* () {
244 const fileSystem = yield* FileSystem.FileSystem;
245 const environment = yield* DesktopEnvironment.DesktopEnvironment;
246 const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
247 if (Option.isNone(raw)) {
248 return Option.none();
249 }
250​
251 const parsed = parsePersistedServerObservabilitySettings(raw.value);
252 return Option.fromNullishOr(parsed.otlpTracesUrl);
253});
254​
255const resolveOtlpTracesUrl = Effect.gen(function* () {
256 const environment = yield* DesktopEnvironment.DesktopEnvironment;
257 if (Option.isSome(environment.otlpTracesUrl)) {
258 return environment.otlpTracesUrl;
259 }
260 return yield* readPersistedOtlpTracesUrl;
261});
262​
263const writeDevelopmentConsoleOutput = (
264 streamName: "stdout" | "stderr",
265 chunk: Uint8Array,
266): Effect.Effect<void> =>
267 Effect.sync(() => {
268 const output = streamName === "stderr" ? process.stderr : process.stdout;
269 output.write(chunk);
270 }).pipe(Effect.ignore);
271​
272const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
273 function* (
274 logFile: RotatingLogFileWriter,
275 input: {
276 readonly message: string;
277 readonly level: "INFO" | "ERROR";
278 readonly annotations: Record<string, unknown>;
279 },
280 ): Effect.fn.Return<void> {
281 return yield* Effect.gen(function* () {
282 const timestamp = DateTime.formatIso(yield* DateTime.now);
283 const encoded = yield* encodeDesktopBackendChildLogRecord({
284 message: input.message,
285 level: input.level,
286 timestamp,
287 annotations: input.annotations,
288 spans: {},
289 fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
290 });
291 yield* logFile.writeText(`${encoded}\n`);
292 }).pipe(Effect.ignore({ log: true }));
293 },
294);
295​
296const backendOutputLogLayer = Layer.effect(
297 DesktopBackendOutputLog,
298 Effect.gen(function* () {
299 const environment = yield* DesktopEnvironment.DesktopEnvironment;
300​
301 const writer = yield* makeRotatingLogFileWriter({
302 filePath: environment.path.join(environment.logDir, "server-child.log"),
303 }).pipe(Effect.option);
304​
305 return Option.match(writer, {
306 onNone: () => DesktopBackendOutputLogNoop,
307 onSome: (logFile) =>
308 ({
309 writeSessionBoundary: Effect.fn(
310 "desktop.observability.backendOutput.writeSessionBoundary",
311 )(function* ({ phase, details }) {
312 const runId = yield* currentDesktopRunId;
313 yield* writeBackendChildLogRecord(logFile, {
314 message: `backend child process session ${phase.toLowerCase()}`,
315 level: "INFO",
316 annotations: {
317 component: "desktop-backend-child",
318 runId,
319 phase,
320 details: sanitizeLogValue(details),
321 },
322 });
323 }),
324 writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
325 function* (streamName, chunk) {
326 if (environment.isDevelopment) {
327 yield* writeDevelopmentConsoleOutput(streamName, chunk);
328 }
329 const runId = yield* currentDesktopRunId;
330 yield* writeBackendChildLogRecord(logFile, {
331 message: "backend child process output",
332 level: streamName === "stderr" ? "ERROR" : "INFO",
333 annotations: {
334 component: "desktop-backend-child",
335 runId,
336 stream: streamName,
337 text: textDecoder.decode(chunk),
338 },
339 });
340 },
341 ),
342 }) satisfies DesktopBackendOutputLogShape,
343 });
344 }),
345);
346​
347const desktopLoggerLayer = Layer.mergeAll(
348 Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
349 Layer.succeed(References.MinimumLogLevel, "Info"),
350);
351​
352const tracerLayer = Layer.unwrap(
353 Effect.gen(function* () {
354 const environment = yield* DesktopEnvironment.DesktopEnvironment;
355 const otlpTracesUrl = yield* resolveOtlpTracesUrl;
356 const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
357 const sink = yield* makeTraceSink({
358 filePath: tracePath,
359 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
360 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
361 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
362 });
363 const delegate = Option.isNone(otlpTracesUrl)
364 ? undefined
365 : yield* OtlpTracer.make({
366 url: otlpTracesUrl.value,
367 exportInterval: `${environment.otlpExportIntervalMs} millis`,
368 resource: {
369 serviceName: "desktop",
370 attributes: {
371 "service.runtime": "desktop",
372 "service.mode": environment.isDevelopment ? "development" : "packaged",
373 },
374 },
375 });
376 const tracer = yield* makeLocalFileTracer({
377 filePath: tracePath,
378 maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
379 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
380 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
381 sink,
382 ...(delegate ? { delegate } : {}),
383 });
384​
385 return Layer.succeed(Tracer.Tracer, tracer);
386 }),
387).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
388​
389export const layer = Layer.mergeAll(
390 backendOutputLogLayer,
391 desktopLoggerLayer,
392 tracerLayer,
393 Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
394 Layer.succeed(References.TracerTimingEnabled, true),
395);