Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/devdocs/src/database.ts

Raw
import { type ChildProcess, spawn } from "node:child_process";
import { access } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import type { CacheStatus } from "./types.ts";
export class Cache {
	private child: ChildProcess | undefined;
	private pending = new Map<
		number,
		{
			resolve: (v: unknown) => void;
			reject: (e: Error) => void;
			timer: ReturnType<typeof setTimeout>;
		}
	>();
	private nextId = 0;
	private opening: Promise<void> | undefined;
	private closed = false;
	private path: string;
	constructor(path: string) {
		this.path = path;
	}
	private async open(): Promise<void> {
		if (this.closed) throw new Error("devdocs session closed");
		if (this.child) return;
		if (this.opening) return this.opening;
		this.opening = (async () => {
			let url = new URL("./database-worker.js", import.meta.url);
			try {
				await access(url);
			} catch {
				url = new URL("../database-worker.ts", import.meta.url);
			}
			if (this.closed) throw new Error("devdocs session closed");
			const child = spawn(
				process.execPath,
				["--no-warnings", fileURLToPath(url)],
				{ stdio: ["ignore", "ignore", "ignore", "ipc"] },
			);
			this.child = child;
			child.on(
				"message",
				(m: { id: number; value?: unknown; error?: string }) => {
					const p = this.pending.get(m.id);
					if (!p) return;
					this.pending.delete(m.id);
					clearTimeout(p.timer);
					if (m.error) p.reject(new Error(m.error));
					else p.resolve(m.value);
				},
			);
			const failed = () => {
				this.child = undefined;
				for (const p of this.pending.values()) {
					clearTimeout(p.timer);
					p.reject(new Error("devdocs database worker stopped"));
				}
				this.pending.clear();
			};
			child.on("error", failed);
			child.on("exit", failed);
		})();
		try {
			await this.opening;
		} finally {
			this.opening = undefined;
		}
	}
	async call<T>(
		operation: string,
		args: Record<string, unknown> = {},
	): Promise<T> {
		await this.open();
		if (this.pending.size >= 64) throw new Error("database request queue full");
		return new Promise<T>((resolve, reject) => {
			const id = ++this.nextId;
			const timer = setTimeout(() => {
				this.pending.delete(id);
				reject(new Error("database deadline exceeded"));
				this.child?.kill("SIGKILL");
			}, 15000);
			this.pending.set(id, { resolve: (v) => resolve(v as T), reject, timer });
			this.child?.send({ id, path: this.path, operation, args });
		});
	}
	async status(): Promise<CacheStatus> {
		const raw = await this.call<unknown>("status");
		if (!raw || typeof raw !== "object" || Array.isArray(raw))
			throw new Error("invalid cache status response");
		const number = (key: keyof CacheStatus): number => {
			const value = Reflect.get(raw, key);
			if (
				typeof value !== "number" ||
				!Number.isSafeInteger(value) ||
				value < 0
			)
				throw new Error("invalid cache status counter");
			return value;
		};
		return {
			bytes: number("bytes"),
			revisions: number("revisions"),
			refreshing: number("refreshing"),
		};
	}
	async close(): Promise<void> {
		this.closed = true;
		const child = this.child;
		this.child = undefined;
		if (!child) return;
		await new Promise<void>((resolve) => {
			const timer = setTimeout(() => child.kill("SIGKILL"), 1000);
			child.once("exit", () => {
				clearTimeout(timer);
				resolve();
			});
			if (child.connected) child.disconnect();
			else child.kill();
		});
	}
}