import type { Actor, Attribution } from "./contract/actor.ts"; import type { EventKind, EventOf, RefsEvent, Stream } from "./contract/events.ts"; import type { CommitSummary } from "./contract/views.ts"; import { renderMarkdown } from "./markdown.ts"; import { raise } from "./outcomes.ts"; import { principal } from "./policy.ts"; type StoredData = K extends "task.commented" ? { body: string } : K extends "pull.commented" ? { body: string; thread?: number } : EventOf["data"]; interface EventRow { id: number; stream: Stream; kind: EventKind; data: string; actor_kind: "human" | "agent"; actor_id: string; actor_name: string | null; agent_runtime: string | null; on_behalf_of: string | null; behalf_name: string | null; session_id: string | null; parent: number | null; created_at: number; edited_at: number | null; } export function taskStream(taskId: number): Stream { return `task:${taskId}`; } export function pullStream(pullId: number): Stream { return `pull:${pullId}`; } export function repoStream(repoId: string): Stream { return `repo:${repoId}`; } /** Live socket tag for viewers who are not signed in. */ export const ANONYMOUS = "anonymous"; /** The stream of the task or pull request that an earlier statement in the same batch inserted: the newest row of that repository. */ export interface NewRowStream { readonly newest: "task" | "pull"; readonly repoId: string; } const NEW_ROW_TABLE = { task: "tasks", pull: "pulls" } as const; function streamValue(stream: Stream | NewRowStream): { sql: string; value: string } { if (typeof stream === "string") return { sql: "?", value: stream }; return { sql: `'${stream.newest}:' || (SELECT max(id) FROM ${NEW_ROW_TABLE[stream.newest]} WHERE repo_id = ?)`, value: stream.repoId }; } /** Whoever an event is recorded for: an actor, or refs itself for work no one asked for, such as recording a push it found by reconciling. */ export type Recorder = Actor | { readonly kind: "system" }; export const SYSTEM_ACTOR_ID = "refs"; function actorColumns(actor: Recorder): [kind: "human" | "agent", id: string, onBehalfOf: string | null, session: string | null] { if (actor.kind === "system") return ["agent", SYSTEM_ACTOR_ID, null, null]; const person = principal(actor); if (!person) raise("sign_in_required", "Only signed-in actors can make changes."); return actor.kind === "agent" ? ["agent", actor.agent.id, person.id, actor.sessionId] : ["human", person.id, null, null]; } /** A recorded event's id, stream and owning repository, telling the repository's hub that the stream moved. */ export interface Hint { readonly latestId: number; readonly stream: Stream; readonly repoId: string; } interface Recorded { id: number; stream: Stream; repo_id: string | null; } const HINTS = Symbol("hints"); const recorded = new WeakSet(); /** * Builds the statement that records one attributed event, to run in the same batch as the change it describes. * An event with a `dedupe` key is recorded at most once per stream and kind, so redelivered work can record it again safely. */ export function recordEvent(db: D1Database, actor: Recorder, stream: Stream | NewRowStream, kind: K, data: StoredData, at: number, parent: number | null = null, dedupe: string | null = null): D1PreparedStatement { const target = streamValue(stream); const statement = db .prepare( `INSERT${dedupe === null ? "" : " OR IGNORE"} INTO events (stream, kind, data, actor_kind, actor_id, on_behalf_of, session_id, parent, created_at, dedupe) VALUES (${target.sql}, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, stream, CASE substr(stream, 1, 5) WHEN 'repo:' THEN substr(stream, 6) WHEN 'task:' THEN (SELECT repo_id FROM tasks WHERE id = CAST(substr(stream, 6) AS INTEGER)) WHEN 'pull:' THEN (SELECT repo_id FROM pulls WHERE id = CAST(substr(stream, 6) AS INTEGER)) END AS repo_id`, ) .bind(target.value, kind, JSON.stringify(data), ...actorColumns(actor), parent, at, dedupe); const hint = (db as D1Database & { [HINTS]?: (results: D1Result[]) => void })[HINTS]; if (!hint) return statement; recorded.add(statement); const run = statement.run.bind(statement); statement.run = async () => { const result = await run(); hint([result]); return result; }; const unhinted = () => Promise.reject(new Error("Record an event with run() or db.batch(), so its live hint is sent.")); statement.first = unhinted; statement.all = unhinted; statement.raw = unhinted; return statement; } function hintsIn(results: readonly D1Result[]): Hint[] { const latest = new Map(); for (const row of results.flatMap((result) => result.results as Recorded[])) { if (row.repo_id) latest.set(row.stream, { latestId: row.id, stream: row.stream, repoId: row.repo_id }); } return [...latest.values()]; } /** * Wraps a database so that every event `recordEvent` builds on it is handed to `notify` once its statement or * batch commits, one hint per stream. Nothing is sent when the write fails. */ export function hinting(db: D1Database, notify: (hint: Hint) => void): D1Database { const send = (results: D1Result[]) => hintsIn(results).forEach(notify); return new Proxy(db, { get(target, key) { if (key === HINTS) return send; if (key === "batch") return async (statements: D1PreparedStatement[]) => { const results = await target.batch(statements); send(results.filter((_, index) => recorded.has(statements[index]))); return results; }; const value = Reflect.get(target, key); return typeof value === "function" ? value.bind(target) : value; }, }); } type ActorRow = Pick; function attribution(row: ActorRow): Attribution { const actor: Attribution["actor"] = row.actor_kind === "human" ? { kind: "human", id: row.actor_id, name: row.actor_name ?? "Former member" } : row.actor_id === SYSTEM_ACTOR_ID ? { kind: "agent", id: SYSTEM_ACTOR_ID, name: "refs", runtime: "refs:system" } : { kind: "agent", id: row.actor_id, name: row.agent_runtime ?? "agent", runtime: row.agent_runtime ?? "unknown" }; return { actor, ...(row.on_behalf_of ? { onBehalfOf: { id: row.on_behalf_of, name: row.behalf_name ?? "Former member" } } : {}), ...(row.session_id ? { sessionId: row.session_id } : {}), }; } function toEvent(row: EventRow): RefsEvent { const stored = JSON.parse(row.data); const data = row.kind === "task.commented" || row.kind === "pull.commented" ? { body: stored.body, html: renderMarkdown(stored.body ?? ""), editedAt: row.edited_at, ...(stored.thread ? { thread: stored.thread } : {}) } : stored; return { id: String(row.id), stream: row.stream, kind: row.kind, data, by: attribution(row), at: row.created_at, parent: row.parent === null ? null : String(row.parent) } as RefsEvent; } export async function readStream(db: D1Database, stream: Stream): Promise { const { results } = await db .prepare( "SELECT e.*, a.name AS actor_name, g.runtime AS agent_runtime, b.name AS behalf_name FROM events e LEFT JOIN users a ON a.id = e.actor_id LEFT JOIN agent_sessions g ON g.id = e.actor_id AND e.actor_kind = 'agent' LEFT JOIN users b ON b.id = e.on_behalf_of WHERE e.stream = ? ORDER BY e.id", ) .bind(stream) .all(); return results.map(toEvent); } /** Remembers who pushed each commit. The first push of a commit wins; pushes refs found by itself name no one. */ export function recordPushers(db: D1Database, actor: Recorder, repoId: string, shas: readonly string[]): D1PreparedStatement[] { if (actor.kind === "system" || !shas.length) return []; return [db.prepare("INSERT OR IGNORE INTO commit_pushes (repo_id, sha, actor_kind, actor_id, on_behalf_of, session_id) SELECT ?, value, ?, ?, ?, ? FROM json_each(?)").bind(repoId, ...actorColumns(actor), JSON.stringify(shas))]; } /** `commits`, each with who pushed it through refs when that is known. */ export async function withPushers(db: D1Database, repoId: string, commits: readonly T[]): Promise { if (!commits.length) return []; const { results } = await db .prepare( "SELECT c.*, a.name AS actor_name, g.runtime AS agent_runtime, b.name AS behalf_name FROM commit_pushes c LEFT JOIN users a ON a.id = c.actor_id LEFT JOIN agent_sessions g ON g.id = c.actor_id AND c.actor_kind = 'agent' LEFT JOIN users b ON b.id = c.on_behalf_of WHERE c.repo_id = ? AND c.sha IN (SELECT value FROM json_each(?))", ) .bind(repoId, JSON.stringify(commits.map((commit) => commit.hash))) .all(); const pushers = new Map(results.map((row) => [row.sha, attribution(row)])); return commits.map((commit) => { const pushedBy = pushers.get(commit.hash); return pushedBy ? { ...commit, pushedBy } : commit; }); }