repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/diff-review/server.ts

Raw
File outline
import { randomBytes, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import {
	createServer,
	type IncomingMessage,
	type Server,
	type ServerResponse,
} from "node:http";
import { extname, resolve, sep } from "node:path";
import { staticDir } from "./bundle.js";
import {
	ANCHOR_CONTEXT_LINES,
	HEARTBEAT_CHECK_INTERVAL_MS,
	HEARTBEAT_LOST_MS,
	REQUEST_BODY_MAX_BYTES,
	REVIEW_PORT,
	TOKEN_COOKIE,
} from "./constants.js";
import type {
	BrowserResult,
	CollectedDiff,
	Finding,
	FindingDraft,
	ReviewCategory,
	ReviewPayload,
	ReviewSeverity,
	ReviewSide,
	ReviewState,
} from "./types.js";

export type ReviewServer = {
	id: string;
	url: string;
	result: Promise<Extract<BrowserResult, { type: "cancel" }>>;
	close(reason: CancelReason): void;
};

type CancelReason = Extract<BrowserResult, { type: "cancel" }>["reason"];
type StartServerOptions = {
	diff: CollectedDiff;
	state: ReviewState;
	round: number;
	token?: string;
	timeoutMs?: number;
	refreshDiff?: () => Promise<CollectedDiff>;
	onSubmit?: (
		result: Extract<BrowserResult, { type: "submit" }>,
		diff: CollectedDiff,
	) => Promise<void> | void;
	onHeartbeatLost?: () => void;
};
type RouteContext = StartServerOptions & {
	token: string;
	diff: CollectedDiff;
	finish(event: ServerEvent): void;
};
type ServerEvent = Extract<BrowserResult, { type: "cancel" }> | "heartbeat";

type Route = {
	method: string;
	path: string;
	handle(
		req: IncomingMessage,
		res: ServerResponse,
		ctx: RouteContext,
	): Promise<void> | void;
};

const REVIEW_CATEGORIES = new Set<ReviewCategory>([
	"bug",
	"style",
	"perf",
	"question",
]);
const REVIEW_SEVERITIES = new Set<ReviewSeverity>(["high", "medium", "low"]);
const REVIEW_SIDES = new Set<ReviewSide>(["additions", "deletions"]);
const ROUTES: readonly Route[] = [
	{ method: "GET", path: "/api/review", handle: getReview },
	{ method: "POST", path: "/api/heartbeat", handle: heartbeat },
	{ method: "POST", path: "/api/cancel", handle: cancel },
	{ method: "POST", path: "/api/finding/validate", handle: validateFinding },
	{ method: "POST", path: "/api/submit", handle: submitReview },
];

export async function startReviewServer(
	options: StartServerOptions,
): Promise<ReviewServer> {
	const token = options.token ?? randomBytes(32).toString("base64url");
	const id = randomUUID();
	let server: Server;
	let finished = false;
	let lastHeartbeatAt = Date.now();
	let heartbeatWarned = false;
	let resolveResult!: (
		result: Extract<BrowserResult, { type: "cancel" }>,
	) => void;
	const result = new Promise<Extract<BrowserResult, { type: "cancel" }>>(
		(resolve) => {
			resolveResult = resolve;
		},
	);

	const finish = (event: ServerEvent) => {
		if (event === "heartbeat") {
			lastHeartbeatAt = Date.now();
			heartbeatWarned = false;
			return;
		}
		if (finished) return;
		finished = true;
		clearInterval(heartbeatTimer);
		if (timeoutTimer) clearTimeout(timeoutTimer);
		server.close();
		resolveResult(event);
	};
	const ctx: RouteContext = { ...options, token, finish };

	const heartbeatTimer = setInterval(() => {
		if (heartbeatWarned || Date.now() - lastHeartbeatAt <= HEARTBEAT_LOST_MS)
			return;
		heartbeatWarned = true;
		options.onHeartbeatLost?.();
		finish({ type: "cancel", reason: "browser" });
	}, HEARTBEAT_CHECK_INTERVAL_MS);
	heartbeatTimer.unref();

	const timeoutTimer =
		options.timeoutMs === undefined
			? undefined
			: setTimeout(
					() => finish({ type: "cancel", reason: "timeout" }),
					options.timeoutMs,
				);
	timeoutTimer?.unref();

	server = createServer((req, res) => void dispatch(req, res, ctx));
	try {
		await listen(server, REVIEW_PORT);
	} catch (err) {
		clearInterval(heartbeatTimer);
		if (timeoutTimer) clearTimeout(timeoutTimer);
		server.close();
		throw err;
	}

	const address = server.address();
	if (!address || typeof address === "string")
		throw new Error("Failed to bind review server");
	return {
		id,
		url: `http://127.0.0.1:${address.port}/?token=${encodeURIComponent(token)}`,
		result,
		close: (reason) => finish({ type: "cancel", reason }),
	};
}

async function dispatch(
	req: IncomingMessage,
	res: ServerResponse,
	ctx: RouteContext,
) {
	try {
		const url = new URL(req.url ?? "/", "http://127.0.0.1");
		if (req.method === "GET" && url.pathname === "/")
			return serveIndex(res, ctx.token, url);
		if (req.method === "GET" && url.pathname.startsWith("/static/"))
			return serveStatic(
				req,
				res,
				ctx.token,
				url.pathname.slice("/static/".length),
			);
		if (!authorized(req, ctx.token))
			return json(res, 401, { error: "unauthorized" });

		const route = ROUTES.find(
			(candidate) =>
				candidate.method === req.method && candidate.path === url.pathname,
		);
		if (!route) return json(res, 404, { error: "not found" });
		await route.handle(req, res, ctx);
	} catch (err) {
		const status = err instanceof HttpError ? err.status : 500;
		json(res, status, { error: errorMessage(err) });
	}
}

async function getReview(
	_req: IncomingMessage,
	res: ServerResponse,
	ctx: RouteContext,
) {
	if (ctx.refreshDiff) ctx.diff = await ctx.refreshDiff();
	json(res, 200, reviewPayload(ctx));
}

function reviewPayload(ctx: RouteContext): ReviewPayload {
	return {
		round: ctx.round,
		source: ctx.diff.source,
		diffText: ctx.diff.diffText,
		files: ctx.diff.files,
		skippedFiles: ctx.diff.skippedFiles,
		carriedFindings: ctx.state.findings.filter(
			(finding) => finding.status === "open",
		),
	};
}

function heartbeat(
	_req: IncomingMessage,
	res: ServerResponse,
	ctx: RouteContext,
) {
	ctx.finish("heartbeat");
	json(res, 200, { ok: true });
}

function cancel(_req: IncomingMessage, res: ServerResponse, ctx: RouteContext) {
	json(res, 200, { ok: true });
	ctx.finish({ type: "cancel", reason: "browser" });
}

async function validateFinding(
	req: IncomingMessage,
	res: ServerResponse,
	ctx: RouteContext,
) {
	const draft = await readJson<FindingDraft>(req, parseFindingDraft);
	json(res, 200, { ok: true, anchor: anchorForDraft(ctx.diff, draft) });
}

async function submitReview(
	req: IncomingMessage,
	res: ServerResponse,
	ctx: RouteContext,
) {
	if (ctx.refreshDiff) ctx.diff = await ctx.refreshDiff();
	const body = await readJson<{ notes?: string; findings: FindingDraft[] }>(
		req,
		parseSubmitBody,
	);
	const result: Extract<BrowserResult, { type: "submit" }> = {
		type: "submit",
		notes: body.notes,
		findings: body.findings.map((draft) =>
			findingFromDraft(ctx.round, ctx.diff, draft),
		),
	};
	await ctx.onSubmit?.(result, ctx.diff);
	json(res, 200, { ok: true });
}

function serveIndex(res: ServerResponse, token: string, url: URL) {
	if (url.searchParams.get("token") !== token)
		return json(res, 401, { error: "unauthorized" });
	res.setHeader(
		"Set-Cookie",
		`${TOKEN_COOKIE}=${token}; SameSite=Strict; Path=/`,
	);
	serveFile(res, resolve(staticDir(), "index.html"));
}

function serveStatic(
	req: IncomingMessage,
	res: ServerResponse,
	token: string,
	path: string,
) {
	if (!cookieAuthorized(req, token))
		return json(res, 401, { error: "unauthorized" });
	const file = staticFilePath(path);
	if (!file) return json(res, 404, { error: "not found" });
	serveFile(res, file);
}

function staticFilePath(rawPath: string) {
	try {
		const root = resolve(staticDir());
		const file = resolve(root, decodeURIComponent(rawPath));
		return file === root || file.startsWith(root + sep) ? file : undefined;
	} catch {
		return undefined;
	}
}

async function serveFile(res: ServerResponse, path: string) {
	try {
		const info = await stat(path);
		if (!info.isFile()) return json(res, 404, { error: "not found" });
		res.statusCode = 200;
		res.setHeader("Content-Type", contentType(path));
		res.setHeader("Cache-Control", "no-store");
		createReadStream(path).pipe(res);
	} catch {
		json(res, 404, { error: "not found" });
	}
}

function authorized(req: IncomingMessage, token: string) {
	return (
		req.headers.authorization === `Bearer ${token}` ||
		cookieAuthorized(req, token)
	);
}

function cookieAuthorized(req: IncomingMessage, token: string) {
	return (req.headers.cookie ?? "")
		.split(/;\s*/)
		.some((cookie) => cookie === `${TOKEN_COOKIE}=${token}`);
}

function json(res: ServerResponse, status: number, data: unknown) {
	if (res.writableEnded) return;
	res.statusCode = status;
	res.setHeader("Content-Type", "application/json; charset=utf-8");
	res.end(JSON.stringify(data));
}

function contentType(path: string) {
	switch (extname(path)) {
		case ".html":
			return "text/html; charset=utf-8";
		case ".js":
			return "text/javascript; charset=utf-8";
		case ".css":
			return "text/css; charset=utf-8";
		case ".json":
			return "application/json; charset=utf-8";
		case ".svg":
			return "image/svg+xml";
		case ".woff2":
			return "font/woff2";
		default:
			return "application/octet-stream";
	}
}

async function readJson<T>(
	req: IncomingMessage,
	parse: (value: unknown) => T,
): Promise<T> {
	const body = await readBody(req);
	try {
		return parse(body ? JSON.parse(body) : {});
	} catch (err) {
		if (err instanceof HttpError) throw err;
		throw new HttpError(
			400,
			err instanceof SyntaxError ? "invalid JSON" : errorMessage(err),
		);
	}
}

async function readBody(req: IncomingMessage) {
	let body = "";
	for await (const chunk of req) {
		body += String(chunk);
		if (Buffer.byteLength(body, "utf8") > REQUEST_BODY_MAX_BYTES)
			throw new HttpError(413, "request body too large");
	}
	return body;
}

function parseSubmitBody(value: unknown): {
	notes?: string;
	findings: FindingDraft[];
} {
	if (!isRecord(value)) throw new Error("request body must be an object");
	const notes = optionalString(value.notes, "notes")?.trim();
	const rawFindings = value.findings ?? [];
	if (!Array.isArray(rawFindings)) throw new Error("findings must be an array");
	return {
		...(notes && { notes }),
		findings: rawFindings.map(parseFindingDraft),
	};
}

function parseFindingDraft(value: unknown): FindingDraft {
	if (!isRecord(value)) throw new Error("finding must be an object");
	const startLine = positiveInteger(value.startLine, "startLine");
	const endLine = positiveInteger(value.endLine, "endLine");
	if (endLine < startLine) throw new Error("endLine must be >= startLine");
	const comment = requiredString(value.comment, "comment").trim();
	if (!comment) throw new Error("comment required");
	const notes = optionalString(value.notes, "notes")?.trim();
	const prevFile = optionalString(value.prevFile, "prevFile");
	return {
		file: requiredString(value.file, "file"),
		...(prevFile && { prevFile }),
		side: enumValue(value.side, REVIEW_SIDES, "side"),
		startLine,
		endLine,
		category: enumValue(value.category, REVIEW_CATEGORIES, "category"),
		severity: enumValue(value.severity, REVIEW_SEVERITIES, "severity"),
		comment,
		...(notes && { notes }),
	};
}

function findingFromDraft(
	round: number,
	diff: CollectedDiff,
	draft: FindingDraft,
): Finding {
	return {
		id: randomUUID(),
		round,
		file: draft.file,
		...(draft.prevFile && { prevFile: draft.prevFile }),
		side: draft.side,
		startLine: draft.startLine,
		endLine: draft.endLine,
		category: draft.category,
		severity: draft.severity,
		comment: draft.comment,
		...(draft.notes && { notes: draft.notes }),
		status: "open",
		anchor: anchorForDraft(diff, draft),
	};
}

function anchorForDraft(diff: CollectedDiff, draft: FindingDraft) {
	const file = diff.diffIndex.get(draft.file);
	if (!file) throw new HttpError(400, `Unknown file: ${draft.file}`);
	const lines = draft.side === "additions" ? file.newLines : file.oldLines;
	return {
		before: nearby(
			lines,
			draft.startLine - ANCHOR_CONTEXT_LINES,
			draft.startLine - 1,
		),
		selected: selectedLines(lines, draft),
		after: nearby(
			lines,
			draft.endLine + 1,
			draft.endLine + ANCHOR_CONTEXT_LINES,
		),
	};
}

function selectedLines(lines: Map<number, string>, draft: FindingDraft) {
	const selected: string[] = [];
	for (let line = draft.startLine; line <= draft.endLine; line++) {
		const text = lines.get(line);
		if (text === undefined)
			throw new HttpError(
				400,
				`Selected line is not in rendered diff context: ${draft.file}:${line}`,
			);
		selected.push(text);
	}
	return selected.join("\n");
}

function nearby(lines: Map<number, string>, start: number, end: number) {
	const out: string[] = [];
	for (let line = start; line <= end; line++) {
		const text = lines.get(line);
		if (text !== undefined) out.push(text);
	}
	return out.join("\n");
}

function requiredString(value: unknown, name: string) {
	if (typeof value !== "string") throw new Error(`${name} must be a string`);
	return value;
}

function optionalString(value: unknown, name: string) {
	if (value === undefined) return undefined;
	return requiredString(value, name);
}

function positiveInteger(value: unknown, name: string) {
	if (!Number.isInteger(value) || (value as number) < 1)
		throw new Error(`${name} must be a positive integer`);
	return value as number;
}

function enumValue<T extends string>(
	value: unknown,
	choices: ReadonlySet<T>,
	name: string,
): T {
	if (typeof value === "string" && choices.has(value as T)) return value as T;
	throw new Error(`invalid ${name}`);
}

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

function listen(server: Server, preferredPort: number) {
	return new Promise<void>((resolveListen, reject) => {
		const onError = (err: NodeJS.ErrnoException) => {
			server.off("error", onError);
			if (err.code !== "EADDRINUSE") return reject(err);
			server.listen(0, "127.0.0.1", () => resolveListen());
		};
		server.once("error", onError);
		server.listen(preferredPort, "127.0.0.1", () => {
			server.off("error", onError);
			resolveListen();
		});
	});
}

function errorMessage(err: unknown) {
	return err instanceof Error ? err.message : String(err);
}

class HttpError extends Error {
	constructor(
		readonly status: number,
		message: string,
	) {
		super(message);
	}
}