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

DesktopBackendOutputLog.ts

385 lines12.6 KB

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