repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/good-job/storage.ts

Raw
File outline
import { randomUUID } from "node:crypto";
import { mkdir, open, readdir, readFile, rename, rm } from "node:fs/promises";
import { homedir } from "node:os";
import { basename, dirname, join, posix, win32 } from "node:path";
import type {
	GoodJobFailure,
	GoodJobJob,
	GoodJobRecord,
	LearningSource,
	ModelRef,
} from "./core.js";
import {
	boundedError,
	FAILURE_VERSION,
	JOB_VERSION,
	RECORD_VERSION,
} from "./core.js";

export interface GoodJobLayout {
	root: string;
	pending: string;
	processing: string;
	failed: string;
	records: string;
}

export interface GoodJobCounts {
	pending: number;
	processing: number;
	failed: number;
	records: number;
}

export interface ClaimedJob {
	job: GoodJobJob;
	path: string;
}

export interface LoadedRecords {
	records: GoodJobRecord[];
	errors: string[];
}

export function goodJobDataDirectory(
	env: NodeJS.ProcessEnv = process.env,
	platform = process.platform,
	home = homedir(),
): string {
	if (platform === "win32") {
		const base = env.LOCALAPPDATA?.trim() || env.APPDATA?.trim();
		return win32.join(
			base || win32.join(home, "AppData", "Local"),
			"pi",
			"good-job",
		);
	}
	if (platform === "darwin")
		return posix.join(home, "Library", "Application Support", "pi", "good-job");
	return posix.join(
		env.XDG_DATA_HOME?.trim() || posix.join(home, ".local", "share"),
		"pi",
		"good-job",
	);
}

export function layout(root = goodJobDataDirectory()): GoodJobLayout {
	return {
		root,
		pending: join(root, "queue", "pending"),
		processing: join(root, "queue", "processing"),
		failed: join(root, "queue", "failed"),
		records: join(root, "records"),
	};
}

export async function ensureLayout(paths: GoodJobLayout): Promise<void> {
	await Promise.all(
		[paths.pending, paths.processing, paths.failed, paths.records].map(
			(directory) => mkdir(directory, { recursive: true, mode: 0o700 }),
		),
	);
}

function isNodeError(error: unknown): error is NodeJS.ErrnoException {
	return error instanceof Error && "code" in error;
}

async function jsonFiles(directory: string): Promise<string[]> {
	try {
		return (await readdir(directory))
			.filter((file) => file.endsWith(".json"))
			.sort();
	} catch (error) {
		if (isNodeError(error) && error.code === "ENOENT") return [];
		throw error;
	}
}

async function syncDirectory(directory: string): Promise<void> {
	if (process.platform === "win32") return;
	try {
		const handle = await open(directory, "r");
		try {
			await handle.sync();
		} finally {
			await handle.close();
		}
	} catch {
		// File fsync plus rename is the portable durability floor.
	}
}

export async function atomicWriteJson(
	target: string,
	value: unknown,
): Promise<void> {
	const directory = dirname(target);
	await mkdir(directory, { recursive: true, mode: 0o700 });
	const temporary = join(
		directory,
		`.${basename(target)}.${process.pid}.${randomUUID()}.tmp`,
	);
	const file = await open(temporary, "wx", 0o600);
	try {
		await file.writeFile(`${JSON.stringify(value)}\n`, "utf8");
		await file.sync();
	} catch (error) {
		await file.close().catch(() => {});
		await rm(temporary, { force: true });
		throw error;
	}
	await file.close();
	try {
		await rename(temporary, target);
		await syncDirectory(directory);
	} catch (error) {
		await rm(temporary, { force: true });
		throw error;
	}
}

function modelRef(value: unknown): value is ModelRef {
	return (
		isObject(value) &&
		typeof value.provider === "string" &&
		value.provider.length > 0 &&
		typeof value.id === "string" &&
		value.id.length > 0
	);
}

function source(value: unknown): value is LearningSource {
	return (
		isObject(value) &&
		typeof value.cwd === "string" &&
		(value.sessionPath === null || typeof value.sessionPath === "string") &&
		typeof value.sessionId === "string" &&
		(value.sessionName === null || typeof value.sessionName === "string") &&
		(value.leafId === null || typeof value.leafId === "string") &&
		(value.agentModel === null || modelRef(value.agentModel))
	);
}

function isObject(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === "object" && !Array.isArray(value);
}

function stringArray(value: unknown): value is string[] {
	return (
		Array.isArray(value) &&
		value.length > 0 &&
		value.every((item) => typeof item === "string" && item.length > 0)
	);
}

function nonnegativeInteger(value: unknown): value is number {
	return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
}

function recordUsage(value: unknown): boolean {
	return (
		isObject(value) &&
		nonnegativeInteger(value.input) &&
		nonnegativeInteger(value.output) &&
		nonnegativeInteger(value.cacheRead) &&
		nonnegativeInteger(value.cacheWrite) &&
		nonnegativeInteger(value.totalTokens) &&
		typeof value.cost === "number" &&
		Number.isFinite(value.cost) &&
		value.cost >= 0
	);
}

export function parseJob(value: unknown): GoodJobJob | undefined {
	if (
		!isObject(value) ||
		value.version !== JOB_VERSION ||
		typeof value.id !== "string" ||
		typeof value.createdAt !== "string" ||
		typeof value.praise !== "string" ||
		!source(value.source) ||
		!(value.analysisModel === null || modelRef(value.analysisModel))
	)
		return undefined;
	return value as unknown as GoodJobJob;
}

export function parseRecord(value: unknown): GoodJobRecord | undefined {
	if (
		!isObject(value) ||
		value.version !== RECORD_VERSION ||
		typeof value.id !== "string" ||
		typeof value.createdAt !== "string" ||
		typeof value.completedAt !== "string" ||
		typeof value.praise !== "string" ||
		!source(value.source) ||
		!modelRef(value.analysisModel) ||
		!isObject(value.learning) ||
		typeof value.learning.achievement !== "string" ||
		value.learning.achievement.length === 0 ||
		!stringArray(value.learning.evidence) ||
		!stringArray(value.learning.successfulBehaviors) ||
		!(
			value.learning.candidateRule === null ||
			typeof value.learning.candidateRule === "string"
		) ||
		!recordUsage(value.usage)
	)
		return undefined;
	return value as unknown as GoodJobRecord;
}

async function readJson(path: string): Promise<unknown> {
	return JSON.parse(await readFile(path, "utf8"));
}

export async function enqueueJob(
	job: GoodJobJob,
	paths: GoodJobLayout,
): Promise<void> {
	if (!parseJob(job))
		throw new Error("refusing to persist invalid good-job job");
	await atomicWriteJson(join(paths.pending, `${job.id}.json`), job);
}

export async function claimJob(
	id: string,
	paths: GoodJobLayout,
): Promise<ClaimedJob | undefined> {
	const pending = join(paths.pending, `${id}.json`);
	const processing = join(
		paths.processing,
		`${id}--${process.pid}--${randomUUID()}.json`,
	);
	await mkdir(paths.processing, { recursive: true, mode: 0o700 });
	try {
		await rename(pending, processing);
	} catch (error) {
		if (isNodeError(error) && error.code === "ENOENT") return undefined;
		throw error;
	}
	const job = parseJob(await readJson(processing));
	if (job) return { job, path: processing };
	await moveInvalidJob(processing, id, paths, "invalid queued job schema");
	return undefined;
}

async function moveInvalidJob(
	path: string,
	id: string,
	paths: GoodJobLayout,
	error: string,
): Promise<void> {
	const failed = {
		version: FAILURE_VERSION,
		job: null,
		failedAt: new Date().toISOString(),
		error,
	};
	await atomicWriteJson(join(paths.failed, `${id}.json`), failed);
	await rm(path, { force: true });
}

export async function pendingJobIds(paths: GoodJobLayout): Promise<string[]> {
	return (await jsonFiles(paths.pending)).map((file) => file.slice(0, -5));
}

export async function recoverProcessing(paths: GoodJobLayout): Promise<void> {
	for (const file of await jsonFiles(paths.processing)) {
		const claim = parseClaimFile(file);
		const processing = join(paths.processing, file);
		if (!claim) {
			await moveInvalidJob(
				processing,
				file.slice(0, -5),
				paths,
				"invalid processing claim name",
			);
			continue;
		}
		const recordFile = `${claim.id}.json`;
		if (
			(await exists(join(paths.records, recordFile))) ||
			(await exists(join(paths.failed, recordFile)))
		) {
			await rm(processing, { force: true });
			continue;
		}
		if (claim.pid !== process.pid && processExists(claim.pid)) continue;
		const pending = join(paths.pending, recordFile);
		if (await exists(pending)) {
			await rm(processing, { force: true });
			continue;
		}
		await rename(processing, pending);
	}
}

function parseClaimFile(file: string): { id: string; pid: number } | undefined {
	const match = /^(.*)--([1-9][0-9]*)--[^/\\]+\.json$/.exec(file);
	if (!match?.[1] || !match[2]) return undefined;
	const pid = Number(match[2]);
	return Number.isSafeInteger(pid) ? { id: match[1], pid } : undefined;
}

function processExists(pid: number): boolean {
	try {
		process.kill(pid, 0);
		return true;
	} catch (error) {
		return !(isNodeError(error) && error.code === "ESRCH");
	}
}

async function exists(path: string): Promise<boolean> {
	try {
		const file = await open(path, "r");
		await file.close();
		return true;
	} catch (error) {
		if (isNodeError(error) && error.code === "ENOENT") return false;
		throw error;
	}
}

export async function commitRecord(
	record: GoodJobRecord,
	claimPath: string,
	paths: GoodJobLayout,
): Promise<void> {
	if (!parseRecord(record))
		throw new Error("refusing to persist invalid good-job record");
	await atomicWriteJson(join(paths.records, `${record.id}.json`), record);
	await rm(claimPath, { force: true });
}

export async function commitFailure(
	job: GoodJobJob,
	error: unknown,
	claimPath: string,
	paths: GoodJobLayout,
): Promise<void> {
	const failure: GoodJobFailure = {
		version: FAILURE_VERSION,
		job,
		failedAt: new Date().toISOString(),
		error: boundedError(error),
	};
	await atomicWriteJson(join(paths.failed, `${job.id}.json`), failure);
	await rm(claimPath, { force: true });
}

export async function loadRecords(
	paths: GoodJobLayout,
): Promise<LoadedRecords> {
	const files = await jsonFiles(paths.records);
	// Records are independent files; concurrent reads avoid serial filesystem
	// latency when opening a large learning list, especially on Windows.
	const loaded = await Promise.all(
		files.map(async (file) => {
			try {
				const record = parseRecord(await readJson(join(paths.records, file)));
				if (!record) throw new Error("invalid record schema");
				return { record };
			} catch (error) {
				return { error: `${file}: ${boundedError(error)}` };
			}
		}),
	);
	const records: GoodJobRecord[] = [];
	const errors: string[] = [];
	for (const result of loaded) {
		if (result.record) records.push(result.record);
		else if (result.error) errors.push(result.error);
	}
	records.sort((left, right) =>
		right.completedAt.localeCompare(left.completedAt),
	);
	return { records, errors };
}

export async function counts(paths: GoodJobLayout): Promise<GoodJobCounts> {
	const [pending, processing, failed, records] = await Promise.all([
		jsonFiles(paths.pending),
		jsonFiles(paths.processing),
		jsonFiles(paths.failed),
		jsonFiles(paths.records),
	]);
	return {
		pending: pending.length,
		processing: processing.length,
		failed: failed.length,
		records: records.length,
	};
}