Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

database.test.ts

313 lines9.8 KB

1import { migrate } from "../ingest/migrate";
2import { test } from "node:test";
3import assert from "node:assert/strict";
4import { Pool } from "pg";
5import { Leases, LostLease } from "../ingest/lease";
6import { publish } from "../ingest/store";
7import type { ThreadSnapshot } from "../ingest/threads";
8test(
9 "database fencing, atomic membership and conditional updates",
10 { skip: !process.env.RUN_DB_TESTS },
11 async () => {
12 const schema = `hn_test_${Date.now()}`;
13 const admin = new Pool({
14 connectionString: process.env.DATABASE_URL_UNPOOLED,
15 });
16 await admin.query(`CREATE SCHEMA ${schema}`);
17 const pool = new Pool({
18 connectionString: process.env.DATABASE_URL_UNPOOLED,
19 options: `-c search_path=${schema}`,
20 max: 4,
21 });
22 try {
23 await migrate(pool);
24 const a = new Leases(pool, "a", Date.now() + 120000, 60000, 30000);
25 const b = new Leases(pool, "b", Date.now() + 120000, 60000, 30000);
26 const [first, second] = await Promise.all([a.acquire(), b.acquire()]);
27 assert.equal(
28 [first, second].filter((result) => result.role === "active").length,
29 1,
30 );
31 const winner = first.role === "active" ? a : b;
32 const winnerToken =
33 first.role === "active" ? first.fencing : second.fencing;
34 const loser = winner === a ? b : a;
35 const snapshot = {
36 feeds: { top: [1, 2], new: [2, 1] },
37 items: new Map([
38 [1, { id: 1, title: "One", score: 1 }],
39 [2, { id: 2, title: "Two", score: 2 }],
40 ]),
41 revision: 1,
42 receivedAt: Date.now(),
43 reconciledAt: Date.now(),
44 };
45 assert.equal(await publish(pool, winner, winnerToken, snapshot), 6);
46 assert.equal(
47 (await pool.query("SELECT count(*) FROM hn_events")).rows[0].count,
48 "6",
49 );
50 assert.equal(await publish(pool, winner, winnerToken, snapshot), 0);
51 assert.equal(
52 (await pool.query("SELECT count(*) FROM hn_events")).rows[0].count,
53 "6",
54 );
55 await assert.rejects(
56 publish(pool, loser, winnerToken, snapshot),
57 LostLease,
58 );
59 const broken = { ...snapshot, feeds: { top: [3], new: [] } };
60 await assert.rejects(
61 publish(pool, winner, winnerToken, broken),
62 /incomplete/,
63 );
64 assert.equal(
65 (await pool.query("SELECT count(*) FROM hn_feed_entries")).rows[0]
66 .count,
67 "4",
68 );
69 await pool.query("INSERT INTO hn_threads(story_id) VALUES(1)");
70 const thread: ThreadSnapshot = {
71 story: snapshot.items.get(1)!,
72 truncated: false,
73 receivedAt: Date.now(),
74 rows: [
75 {
76 item: {
77 id: 11,
78 type: "comment",
79 text: "hello",
80 by: "alice",
81 time: 123,
82 },
83 parentId: 1,
84 path: "000001",
85 depth: 0,
86 },
87 {
88 item: { id: 12, type: "comment", text: "reply" },
89 parentId: 11,
90 path: "000001.000001",
91 depth: 1,
92 },
93 ],
94 };
95 assert.equal(
96 await publish(pool, winner, winnerToken, {
97 ...snapshot,
98 threads: [thread],
99 }),
100 2,
101 );
102 assert.equal(
103 await publish(pool, winner, winnerToken, {
104 ...snapshot,
105 threads: [thread],
106 }),
107 0,
108 );
109 const edited = {
110 ...thread,
111 rows: [
112 {
113 ...thread.rows[0],
114 item: { ...thread.rows[0].item, text: "edited" },
115 },
116 ],
117 };
118 assert.equal(
119 await publish(pool, winner, winnerToken, {
120 ...snapshot,
121 threads: [edited],
122 }),
123 2,
124 );
125 assert.equal(
126 (await pool.query("SELECT text FROM hn_comments WHERE story_id=1"))
127 .rows[0].text,
128 "edited",
129 );
130 const invalid = {
131 ...thread,
132 rows: [{ ...thread.rows[0], parentId: 99 }],
133 };
134 const eventsBeforeRollback = (
135 await pool.query("SELECT count(*) FROM hn_events")
136 ).rows[0].count;
137 await assert.rejects(
138 publish(pool, winner, winnerToken, {
139 ...snapshot,
140 feeds: { top: [2, 1], new: [1] },
141 threads: [invalid],
142 }),
143 /Invalid thread snapshot/,
144 );
145 assert.equal(
146 (await pool.query("SELECT count(*) FROM hn_events")).rows[0].count,
147 eventsBeforeRollback,
148 );
149 assert.deepEqual(
150 (
151 await pool.query(
152 "SELECT item_id FROM hn_feed_entries WHERE feed='top' ORDER BY rank",
153 )
154 ).rows.map((row) => row.item_id),
155 [1, 2],
156 );
157 assert.equal(
158 (await pool.query("SELECT text FROM hn_comments WHERE story_id=1"))
159 .rows[0].text,
160 "edited",
161 );
162 const deleted = {
163 ...edited,
164 rows: [
165 {
166 ...edited.rows[0],
167 item: { ...edited.rows[0].item, text: "", deleted: true },
168 },
169 ],
170 };
171 assert.equal(
172 await publish(pool, winner, winnerToken, {
173 ...snapshot,
174 threads: [deleted],
175 }),
176 1,
177 );
178 await assert.rejects(
179 publish(pool, loser, winnerToken, { ...snapshot, threads: [thread] }),
180 LostLease,
181 );
182 assert.equal(
183 (await pool.query("SELECT deleted FROM hn_comments WHERE story_id=1"))
184 .rows[0].deleted,
185 true,
186 );
187 await pool.query(
188 "UPDATE ingest_leases SET active_session_end=clock_timestamp()+interval '10 seconds'",
189 );
190 const standby = await loser.acquire();
191 assert.equal(standby.role, "standby");
192 await loser.renew("standby", standby.fencing, true);
193 assert.equal(await winner.handoff(winnerToken), loser.owner);
194 const promoted = await loser.promoteIfNeeded();
195 assert.ok(promoted);
196 assert.notEqual(promoted.fencing, winnerToken);
197 await assert.rejects(
198 publish(pool, winner, winnerToken, snapshot),
199 LostLease,
200 );
201 await publish(pool, loser, promoted.fencing, {
202 ...snapshot,
203 feeds: { top: [2, 1], new: [2] },
204 });
205 assert.deepEqual(
206 (
207 await pool.query(
208 "SELECT item_id FROM hn_feed_entries WHERE feed='top' ORDER BY rank,item_id",
209 )
210 ).rows.map((row) => row.item_id),
211 [2, 1],
212 );
213 const lease = (
214 await pool.query(
215 "SELECT active_session_end,active_deadline FROM ingest_leases",
216 )
217 ).rows[0];
218 assert.ok(+lease.active_session_end <= +lease.active_deadline - 10000);
219 await pool.query(
220 "UPDATE ingest_leases SET active_until=clock_timestamp()-interval '1 second'",
221 );
222 const replacement = await winner.acquire();
223 assert.equal(replacement.role, "active");
224 await assert.rejects(
225 publish(pool, loser, promoted.fencing, snapshot),
226 LostLease,
227 );
228 await publish(pool, winner, replacement.fencing, snapshot);
229 } finally {
230 await pool.end();
231 await admin.query(`DROP SCHEMA ${schema} CASCADE`);
232 await admin.end();
233 }
234 },
235);
236​
237test(
238 "event journal covers all mirrored fields, movement, removals and retention",
239 { skip: !process.env.RUN_DB_TESTS },
240 async () => {
241 const schema = `hn_events_test_${Date.now()}`;
242 const admin = new Pool({
243 connectionString: process.env.DATABASE_URL_UNPOOLED,
244 });
245 await admin.query(`CREATE SCHEMA ${schema}`);
246 const pool = new Pool({
247 connectionString: process.env.DATABASE_URL_UNPOOLED,
248 options: `-c search_path=${schema}`,
249 max: 1,
250 });
251 try {
252 await migrate(pool);
253 await pool.query(
254 "INSERT INTO hn_items(id,type,title,created,committed_at) VALUES(99,'story','Off-page story',0,'initial')",
255 );
256 await pool.query(
257 "INSERT INTO hn_feed_entries(feed,item_id,rank) VALUES('top',99,75)",
258 );
259 await pool.query(
260 "UPDATE hn_items SET score=5,comments=2,title='Edited title',dead=true WHERE id=99",
261 );
262 const update = (
263 await pool.query("SELECT * FROM hn_events WHERE kind='story-updated'")
264 ).rows[0];
265 assert.equal(update.item_id, 99);
266 assert.deepEqual(Object.keys(JSON.parse(update.details)).sort(), [
267 "comments",
268 "dead",
269 "score",
270 "title",
271 ]);
272 await pool.query(
273 "UPDATE hn_items SET committed_at='no domain change' WHERE id=99",
274 );
275 assert.equal(
276 (await pool.query("SELECT count(*) FROM hn_events")).rows[0].count,
277 "3",
278 );
279 await pool.query("UPDATE hn_feed_entries SET rank=1 WHERE item_id=99");
280 await pool.query("DELETE FROM hn_feed_entries WHERE item_id=99");
281 await pool.query(
282 "INSERT INTO hn_comments(story_id,item_id,parent_id,path,depth,created,text,deleted,dead,committed_at) VALUES(99,100,99,'000001',0,0,'hello',false,false,'initial')",
283 );
284 await pool.query(
285 "UPDATE hn_comments SET text='edited',path='000002',deleted=true WHERE item_id=100",
286 );
287 await pool.query("DELETE FROM hn_comments WHERE item_id=100");
288 const kinds = (
289 await pool.query("SELECT kind FROM hn_events ORDER BY id")
290 ).rows.map((row) => row.kind);
291 assert.deepEqual(kinds, [
292 "story-added",
293 "top-entered",
294 "story-updated",
295 "top-moved",
296 "top-left",
297 "comment-added",
298 "comment-updated",
299 "comment-removed",
300 ]);
301 await pool.query("UPDATE hn_events SET occurred_at=0 WHERE id=1");
302 await pool.query("UPDATE hn_items SET score=score WHERE id=99");
303 assert.equal(
304 (await pool.query("SELECT count(*) FROM hn_events")).rows[0].count,
305 "7",
306 );
307 } finally {
308 await pool.end();
309 await admin.query(`DROP SCHEMA ${schema} CASCADE`);
310 await admin.end();
311 }
312 },
313);