Skip to content
refs
History
191 lines · 8.9 KBRaw
1import type { Actor, Attribution } from "./contract/actor.ts";
2import type { EventKind, EventOf, RefsEvent, Stream } from "./contract/events.ts";
3import type { CommitSummary } from "./contract/views.ts";
4import { renderMarkdown } from "./markdown.ts";
5import { raise } from "./outcomes.ts";
6import { principal } from "./policy.ts";
7
8type StoredData<K extends EventKind> = K extends "task.commented" ? { body: string } : K extends "pull.commented" ? { body: string; thread?: number } : EventOf<K>["data"];
9
10interface EventRow {
11 id: number;
12 stream: Stream;
13 kind: EventKind;
14 data: string;
15 actor_kind: "human" | "agent";
16 actor_id: string;
17 actor_name: string | null;
18 agent_runtime: string | null;
19 on_behalf_of: string | null;
20 behalf_name: string | null;
21 session_id: string | null;
22 parent: number | null;
23 created_at: number;
24 edited_at: number | null;
25}
26
27export function taskStream(taskId: number): Stream {
28 return `task:${taskId}`;
29}
30
31export function pullStream(pullId: number): Stream {
32 return `pull:${pullId}`;
33}
34
35export function repoStream(repoId: string): Stream {
36 return `repo:${repoId}`;
37}
38
39/** Live socket tag for viewers who are not signed in. */
40export const ANONYMOUS = "anonymous";
41
42/** The stream of the task or pull request that an earlier statement in the same batch inserted: the newest row of that repository. */
43export interface NewRowStream {
44 readonly newest: "task" | "pull";
45 readonly repoId: string;
46}
47
48const NEW_ROW_TABLE = { task: "tasks", pull: "pulls" } as const;
49
50function streamValue(stream: Stream | NewRowStream): { sql: string; value: string } {
51 if (typeof stream === "string") return { sql: "?", value: stream };
52 return { sql: `'${stream.newest}:' || (SELECT max(id) FROM ${NEW_ROW_TABLE[stream.newest]} WHERE repo_id = ?)`, value: stream.repoId };
53}
54
55/** 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. */
56export type Recorder = Actor | { readonly kind: "system" };
57
58export const SYSTEM_ACTOR_ID = "refs";
59
60function actorColumns(actor: Recorder): [kind: "human" | "agent", id: string, onBehalfOf: string | null, session: string | null] {
61 if (actor.kind === "system") return ["agent", SYSTEM_ACTOR_ID, null, null];
62 const person = principal(actor);
63 if (!person) raise("sign_in_required", "Only signed-in actors can make changes.");
64 return actor.kind === "agent" ? ["agent", actor.agent.id, person.id, actor.sessionId] : ["human", person.id, null, null];
65}
66
67/** A recorded event's id, stream and owning repository, telling the repository's hub that the stream moved. */
68export interface Hint {
69 readonly latestId: number;
70 readonly stream: Stream;
71 readonly repoId: string;
72}
73
74interface Recorded {
75 id: number;
76 stream: Stream;
77 repo_id: string | null;
78}
79
80const HINTS = Symbol("hints");
81const recorded = new WeakSet<D1PreparedStatement>();
82
83/**
84 * Builds the statement that records one attributed event, to run in the same batch as the change it describes.
85 * An event with a `dedupe` key is recorded at most once per stream and kind, so redelivered work can record it again safely.
86 */
87export function recordEvent<K extends EventKind>(db: D1Database, actor: Recorder, stream: Stream | NewRowStream, kind: K, data: StoredData<K>, at: number, parent: number | null = null, dedupe: string | null = null): D1PreparedStatement {
88 const target = streamValue(stream);
89 const statement = db
90 .prepare(
91 `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`,
92 )
93 .bind(target.value, kind, JSON.stringify(data), ...actorColumns(actor), parent, at, dedupe);
94 const hint = (db as D1Database & { [HINTS]?: (results: D1Result[]) => void })[HINTS];
95 if (!hint) return statement;
96 recorded.add(statement);
97 const run = statement.run.bind(statement);
98 statement.run = async <T>() => {
99 const result = await run<T>();
100 hint([result]);
101 return result;
102 };
103 const unhinted = () => Promise.reject(new Error("Record an event with run() or db.batch(), so its live hint is sent."));
104 statement.first = unhinted;
105 statement.all = unhinted;
106 statement.raw = unhinted;
107 return statement;
108}
109
110function hintsIn(results: readonly D1Result[]): Hint[] {
111 const latest = new Map<Stream, Hint>();
112 for (const row of results.flatMap((result) => result.results as Recorded[])) {
113 if (row.repo_id) latest.set(row.stream, { latestId: row.id, stream: row.stream, repoId: row.repo_id });
114 }
115 return [...latest.values()];
116}
117
118/**
119 * Wraps a database so that every event `recordEvent` builds on it is handed to `notify` once its statement or
120 * batch commits, one hint per stream. Nothing is sent when the write fails.
121 */
122export function hinting(db: D1Database, notify: (hint: Hint) => void): D1Database {
123 const send = (results: D1Result[]) => hintsIn(results).forEach(notify);
124 return new Proxy(db, {
125 get(target, key) {
126 if (key === HINTS) return send;
127 if (key === "batch")
128 return async <T>(statements: D1PreparedStatement[]) => {
129 const results = await target.batch<T>(statements);
130 send(results.filter((_, index) => recorded.has(statements[index])));
131 return results;
132 };
133 const value = Reflect.get(target, key);
134 return typeof value === "function" ? value.bind(target) : value;
135 },
136 });
137}
138
139type ActorRow = Pick<EventRow, "actor_kind" | "actor_id" | "actor_name" | "agent_runtime" | "on_behalf_of" | "behalf_name" | "session_id">;
140
141function attribution(row: ActorRow): Attribution {
142 const actor: Attribution["actor"] =
143 row.actor_kind === "human"
144 ? { kind: "human", id: row.actor_id, name: row.actor_name ?? "Former member" }
145 : row.actor_id === SYSTEM_ACTOR_ID
146 ? { kind: "agent", id: SYSTEM_ACTOR_ID, name: "refs", runtime: "refs:system" }
147 : { kind: "agent", id: row.actor_id, name: row.agent_runtime ?? "agent", runtime: row.agent_runtime ?? "unknown" };
148 return {
149 actor,
150 ...(row.on_behalf_of ? { onBehalfOf: { id: row.on_behalf_of, name: row.behalf_name ?? "Former member" } } : {}),
151 ...(row.session_id ? { sessionId: row.session_id } : {}),
152 };
153}
154
155function toEvent(row: EventRow): RefsEvent {
156 const stored = JSON.parse(row.data);
157 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;
158 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;
159}
160
161export async function readStream(db: D1Database, stream: Stream): Promise<RefsEvent[]> {
162 const { results } = await db
163 .prepare(
164 "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",
165 )
166 .bind(stream)
167 .all<EventRow>();
168 return results.map(toEvent);
169}
170
171/** Remembers who pushed each commit. The first push of a commit wins; pushes refs found by itself name no one. */
172export function recordPushers(db: D1Database, actor: Recorder, repoId: string, shas: readonly string[]): D1PreparedStatement[] {
173 if (actor.kind === "system" || !shas.length) return [];
174 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))];
175}
176
177/** `commits`, each with who pushed it through refs when that is known. */
178export async function withPushers<T extends CommitSummary>(db: D1Database, repoId: string, commits: readonly T[]): Promise<T[]> {
179 if (!commits.length) return [];
180 const { results } = await db
181 .prepare(
182 "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(?))",
183 )
184 .bind(repoId, JSON.stringify(commits.map((commit) => commit.hash)))
185 .all<ActorRow & { sha: string }>();
186 const pushers = new Map(results.map((row) => [row.sha, attribution(row)]));
187 return commits.map((commit) => {
188 const pushedBy = pushers.get(commit.hash);
189 return pushedBy ? { ...commit, pushedBy } : commit;
190 });
191}