repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/chrome-cdp/debug.ts

Raw
File outline
import { constants } from "node:fs";
import { type FileHandle, open } from "node:fs/promises";

// Metadata only: never log CDP params, responses, events, screenshots, cookies, or URLs.
export type Diagnostic = {
	event: string;
	operation?: number;
	kind?: string;
	method?: string;
	wireId?: number;
	sessionId?: string;
	elapsedMs?: number;
	bytes?: number;
	count?: number;
	code?: number;
	outcome?: string;
};

export class DebugLog {
	private writes = Promise.resolve();
	private bytes = 0;
	private error?: Error;
	private readonly limit = 8 * 1024 * 1024;
	private readonly file: FileHandle;

	private constructor(file: FileHandle) {
		this.file = file;
	}

	static async open(path: string): Promise<DebugLog> {
		const file = await open(
			path,
			constants.O_WRONLY |
				constants.O_APPEND |
				constants.O_CREAT |
				(constants.O_NOFOLLOW || 0),
			0o600,
		);
		try {
			const info = await file.stat();
			if (!info.isFile()) throw new Error("debug path is not a regular file");
			if ((info.mode & 0o077) !== 0)
				throw new Error("debug log must not be accessible by group or others");
			if (info.size >= 8 * 1024 * 1024)
				throw new Error("debug log reached 8 MiB limit; choose a new file");
			const log = new DebugLog(file);
			log.bytes = info.size;
			return log;
		} catch (e) {
			await file.close();
			throw e;
		}
	}

	record(data: Diagnostic): void {
		if (this.error || this.bytes >= this.limit) return;
		const row =
			JSON.stringify({
				time: new Date().toISOString(),
				...data,
				method:
					data.method && /^[A-Za-z][A-Za-z0-9_.]*$/.test(data.method)
						? data.method
						: undefined,
				sessionId:
					data.sessionId && /^[A-Za-z0-9_-]{1,128}$/.test(data.sessionId)
						? data.sessionId
						: undefined,
			}) + "\n";
		const size = Buffer.byteLength(row);
		if (this.bytes + size + 128 > this.limit) {
			const notice =
				JSON.stringify({
					time: new Date().toISOString(),
					event: "debug.limit",
					bytes: this.bytes,
				}) + "\n";
			this.writes = this.writes
				.then(async () => {
					await this.file.write(notice);
				})
				.catch((e) => {
					this.error = e instanceof Error ? e : new Error(String(e));
				});
			this.bytes = this.limit;
			return;
		}
		this.bytes += size;
		this.writes = this.writes
			.then(async () => {
				await this.file.write(row);
			})
			.catch((e) => {
				this.error = e instanceof Error ? e : new Error(String(e));
			});
	}

	async close(): Promise<void> {
		await this.writes;
		await this.file.close();
		if (this.error) throw this.error;
	}
}