Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

database.ts

297 lines9.4 KB

1import type { Pool, PoolClient } from "pg";
2import {
3 APIError,
4 digest,
5 type DetailChange,
6 type JournalRecord,
7} from "./protocol.js";
8​
9export interface SQL {
10 query(
11 sql: string,
12 values?: any[],
13 ): Promise<{ rows: any[]; rowCount?: number | null }>;
15export interface Database extends SQL {
16 transaction<T>(fn: (q: SQL) => Promise<T>): Promise<T>;
18export function postgres(pool: Pool): Database {
19 return {
20 query: (s, v) => pool.query(s, v),
21 async transaction(fn) {
22 const q: PoolClient = await pool.connect();
23 try {
24 await q.query("BEGIN");
25 const value = await fn(q);
26 await q.query("COMMIT");
27 return value;
28 } catch (e) {
29 await q.query("ROLLBACK");
30 throw e;
31 } finally {
32 q.release();
33 }
34 },
35 };
37export async function ingest(
38 db: Database,
39 deviceID: string,
40 expeditionID: string,
41 start: number,
42 records: JournalRecord[],
43) {
44 return db.transaction(async (q) => {
45 // Lock the existing device first, including for a brand new expedition.
46 await q.query("SELECT id FROM jol_devices WHERE id=$1 FOR UPDATE", [
47 deviceID,
48 ]);
49 let exp = (
50 await q.query(
51 "SELECT cursor FROM jol_expeditions WHERE device_id=$1 AND id=$2",
52 [deviceID, expeditionID],
53 )
54 ).rows[0];
55 if (!exp) {
56 const first = records[0];
57 if (
58 start !== 1 ||
59 first.event !== "created" ||
60 first.expedition?.id !== expeditionID
61 )
62 throw new APIError(
63 409,
64 "A new stream must begin with its creation record",
65 );
66 await q.query(
67 "INSERT INTO jol_expeditions(device_id,id,title,created_at) VALUES($1,$2,$3,$4)",
68 [
69 deviceID,
70 expeditionID,
71 first.expedition.title,
72 new Date(first.expedition.date),
73 ],
74 );
75 exp = { cursor: 0 };
76 }
77 let cursor = exp.cursor as number;
78 for (let i = 0; i < records.length; i++) {
79 const sequence = start + i,
80 record = records[i],
81 hash = digest(record);
82 const prior = (
83 await q.query(
84 "SELECT event_id,digest FROM jol_events WHERE device_id=$1 AND expedition_id=$2 AND sequence=$3",
85 [deviceID, expeditionID, sequence],
86 )
87 ).rows[0];
88 if (prior) {
89 if (prior.event_id !== record.id || prior.digest !== hash)
90 throw new APIError(409, "Conflicting event at an accepted sequence");
91 continue;
92 }
93 if (sequence !== cursor + 1)
94 throw new APIError(409, `Expected sequence ${cursor + 1}`);
95 const duplicate = (
96 await q.query(
97 "SELECT sequence FROM jol_events WHERE device_id=$1 AND expedition_id=$2 AND event_id=$3",
98 [deviceID, expeditionID, record.id],
99 )
100 ).rows[0];
101 if (duplicate)
102 throw new APIError(409, "Event already belongs to another sequence");
103 await q.query(
104 "INSERT INTO jol_events(device_id,expedition_id,sequence,event_id,digest,payload) VALUES($1,$2,$3,$4,$5,$6)",
105 [
106 deviceID,
107 expeditionID,
108 sequence,
109 record.id,
110 hash,
111 JSON.stringify(record),
112 ],
113 );
114 await apply(q, deviceID, expeditionID, sequence, record);
115 cursor = sequence;
116 }
117 await q.query(
118 "UPDATE jol_expeditions SET cursor=$3 WHERE device_id=$1 AND id=$2",
119 [deviceID, expeditionID, cursor],
120 );
121 return cursor;
122 });
124​
125/** Add explicitly shared details to previously acknowledged records. The
126 * original digests still validate retries of the notes-only upload. */
127export async function shareDetails(
128 db: Database,
129 device: string,
130 expedition: string,
131 changes: DetailChange[],
132) {
133 await db.transaction(async (q) => {
134 await q.query("SELECT id FROM jol_devices WHERE id=$1 FOR UPDATE", [
135 device,
136 ]);
137 const entries = new Set<string>();
138 for (const { sequence, id, date, event, entryID, text } of changes) {
139 const prior = (
140 await q.query(
141 "SELECT payload FROM jol_events WHERE device_id=$1 AND expedition_id=$2 AND sequence=$3",
142 [device, expedition, sequence],
143 )
144 ).rows[0]?.payload as JournalRecord | undefined;
145 if (!prior || prior.id !== id || prior.date !== date)
146 throw new APIError(
147 409,
148 "Details do not match an accepted journal record",
149 );
150 if (event === "entry" && prior.event === "entry" && prior.entry) {
151 if (
152 prior.entry.id !== entryID ||
153 (prior.entry.details && prior.entry.details !== text)
154 )
155 throw new APIError(409, "Details do not match the journal entry");
156 prior.entry.details = text;
157 } else if (
158 event === "detailsAppended" &&
159 (prior.event === "redacted" ||
160 (prior.event === "detailsAppended" &&
161 prior.entryID === entryID &&
162 prior.text === text))
163 ) {
164 Object.assign(prior, { event, entryID, text });
165 } else {
166 throw new APIError(
167 409,
168 "Details do not match an accepted journal record",
169 );
170 }
171 entries.add(entryID);
172 await q.query(
173 "UPDATE jol_events SET payload=$4 WHERE device_id=$1 AND expedition_id=$2 AND sequence=$3",
174 [device, expedition, sequence, JSON.stringify(prior)],
175 );
176 }
177 for (const id of entries) {
178 const result = await q.query(
179 `UPDATE jol_entries SET details=(
180 SELECT COALESCE(string_agg(CASE WHEN payload->>'event'='entry'
181 THEN payload->'entry'->>'details' ELSE payload->>'text' END, '' ORDER BY sequence),'')
182 FROM jol_events WHERE device_id=$1 AND expedition_id=$2 AND (
183 (payload->>'event'='entry' AND payload->'entry'->>'id'=$3::text) OR
184 (payload->>'event'='detailsAppended' AND payload->>'entryID'=$3::text)
185 )
186 ) WHERE device_id=$1 AND expedition_id=$2 AND id=$3::uuid RETURNING id`,
187 [device, expedition, id],
188 );
189 if (!result.rows.length)
190 throw new APIError(409, "Journal entry not found");
191 }
192 });
194​
195async function apply(
196 q: SQL,
197 device: string,
198 exp: string,
199 sequence: number,
200 r: JournalRecord,
201) {
202 const keys = [device, exp];
203 if (r.event === "created" && r.expedition?.id !== exp)
204 throw new APIError(409, "Expedition does not match stream");
205 if (r.event === "entry" && r.entry) {
206 const e = r.entry;
207 await q.query(
208 "INSERT INTO jol_entries(device_id,expedition_id,id,position,kind,text,details,photo,created_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)",
209 [
210 ...keys,
211 e.id,
212 sequence,
213 e.kind,
214 e.text,
215 e.details,
216 e.photo ?? null,
217 new Date(e.date),
218 ],
219 );
220 } else if (
221 ["textAppended", "textReplaced", "detailsAppended"].includes(r.event)
222 ) {
223 const expression =
224 r.event === "textReplaced"
225 ? "text=$4"
226 : r.event === "textAppended"
227 ? "text=text || $4"
228 : "details=details || $4";
229 const result = await q.query(
230 `UPDATE jol_entries SET ${expression} WHERE device_id=$1 AND expedition_id=$2 AND id=$3 RETURNING id`,
231 [...keys, r.entryID, r.text],
232 );
233 if (!result.rows.length)
234 throw new APIError(409, "Text change precedes its journal entry");
235 } else if (r.event === "titleChanged")
236 await q.query(
237 "UPDATE jol_expeditions SET title=$3 WHERE device_id=$1 AND id=$2",
238 [...keys, r.text],
239 );
240 else if (r.event === "state")
241 await q.query(
242 "UPDATE jol_expeditions SET status=coalesce($3,status),is_running=coalesce($4,is_running),is_finished=coalesce($5,is_finished) WHERE device_id=$1 AND id=$2",
243 [...keys, r.status ?? null, r.isRunning ?? null, r.isFinished ?? null],
244 );
246​
247export async function claim(
248 db: Database,
249 device: string,
250 owner: string,
251 busy: boolean,
252) {
253 return db.transaction(async (q) => {
254 const d = (
255 await q.query(
256 "SELECT remote_enabled FROM jol_devices WHERE id=$1 AND owner_id=$2 AND NOT revoked FOR UPDATE",
257 [device, owner],
258 )
259 ).rows[0];
260 if (!d?.remote_enabled) return null;
261 await q.query(
262 "UPDATE jol_commands SET status='uncertain',result='Connection interrupted after execution began; give Jerry a fresh direction' WHERE device_id=$1 AND status='started' AND lease_until < now()",
263 [device],
264 );
265 await q.query(
266 "UPDATE jol_commands SET status='queued',lease_until=NULL WHERE device_id=$1 AND status='received' AND lease_until < now()",
267 [device],
268 );
269 await q.query(
270 "UPDATE jol_commands SET status='expired' WHERE device_id=$1 AND status='queued' AND expires_at < now()",
271 [device],
272 );
273 const command = (
274 await q.query(
275 `SELECT * FROM jol_commands WHERE device_id=$1 AND status='queued' AND expires_at > now() ${busy ? "AND kind='stop'" : ""} ORDER BY CASE WHEN kind='stop' THEN 0 ELSE 1 END,created_at,id LIMIT 1 FOR UPDATE`,
276 [device],
277 )
278 ).rows[0];
279 if (!command) return null;
280 if (
281 command.kind !== "stop" &&
282 (
283 await q.query(
284 "SELECT id FROM jol_commands WHERE device_id=$1 AND status IN ('received','started') LIMIT 1",
285 [device],
286 )
287 ).rows.length
288 )
289 return null;
290 return (
291 await q.query(
292 "UPDATE jol_commands SET status='received',fence=fence+1,lease_until=now()+interval '90 seconds' WHERE id=$1 RETURNING *",
293 [command.id],
294 )
295 ).rows[0];
296 });