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

smoothing-database.test.ts

381 lines11.8 KB

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import { Pool } from "pg";
4import { migrate } from "../ingest/migrate";
5import { Leases, LostLease } from "../ingest/lease";
6import { SmoothingPublisher } from "../ingest/smoothing";
7import type { SourceSnapshot } from "../ingest/source";
8import type { ThreadSnapshot } from "../ingest/comment-tree";
9​
10test(
11 "durable smoothing preserves deadlines, atomic trees/ranks, handoffs and immediate mode",
12 { skip: !process.env.RUN_DB_TESTS, timeout: 60000 },
13 async () => {
14 const schema = `hn_smoothing_${Date.now()}`;
15 const admin = new Pool({
16 connectionString: process.env.DATABASE_URL_UNPOOLED,
17 });
18 const pool = new Pool({
19 connectionString: process.env.DATABASE_URL_UNPOOLED,
20 options: `-c search_path=${schema}`,
21 max: 4,
22 });
23 let heartbeat: ReturnType<typeof setInterval> | undefined;
24 let renewing: Promise<unknown> | undefined;
25 try {
26 await admin.query(`CREATE SCHEMA ${schema}`);
27 await migrate(pool);
28 const first = new Leases(
29 pool,
30 "first",
31 Date.now() + 120000,
32 90000,
33 60000,
34 );
35 const token = (await first.acquire()).fencing;
36 let keeper = { lease: first, token };
37 heartbeat = setInterval(() => {
38 if (!renewing)
39 renewing = keeper.lease
40 .renew("active", keeper.token, true)
41 .finally(() => {
42 renewing = undefined;
43 });
44 }, 5000);
45 const publisher = new SmoothingPublisher(pool, first, 28000);
46 const snapshot: SourceSnapshot = {
47 feeds: { top: [1, 2, 3, 4, 5, 6], new: [6, 5, 4, 3, 2, 1] },
48 items: new Map(
49 [1, 2, 3, 4, 5, 6].map((id) => [
50 id,
51 { id, title: `Story ${id}`, score: 0 },
52 ]),
53 ),
54 revision: 1,
55 receivedAt: Date.now(),
56 reconciledAt: Date.now(),
57 };
58 assert.equal(
59 await publisher.tick(token, snapshot),
60 18,
61 "Empty feed fills immediately",
62 );
63 const burst: SourceSnapshot = {
64 ...snapshot,
65 revision: 2,
66 receivedAt: Date.now(),
67 feeds: { ...snapshot.feeds, top: [7, 1, 2, 3, 4, 5] },
68 items: new Map(
69 [1, 2, 3, 4, 5, 6, 7].map((id) => [
70 id,
71 { id, title: `Story ${id}`, score: 1 },
72 ]),
73 ),
74 };
75 assert.equal(await publisher.tick(token, burst), 0);
76 // Keep fixture deadlines in the future while database round trips run;
77 // individual releases below are controlled without wall-clock races.
78 await pool.query("UPDATE hn_ingest_pending SET due_at=due_at+120000");
79 const queued = (
80 await pool.query(
81 "SELECT key,due_at FROM hn_ingest_pending ORDER BY key",
82 )
83 ).rows;
84 assert.equal(queued.length, 8);
85 assert.equal(
86 new Set(queued.map((job) => job.due_at)).size,
87 8,
88 "Separate operations have separate deadlines",
89 );
90 assert.equal(await publisher.tick(token, { ...burst, revision: 3 }), 0);
91 assert.deepEqual(
92 (
93 await pool.query(
94 "SELECT key,due_at FROM hn_ingest_pending ORDER BY key",
95 )
96 ).rows,
97 queued,
98 "Unchanged source values do not restart the delay",
99 );
100 const newest: SourceSnapshot = {
101 ...burst,
102 revision: 4,
103 items: new Map(burst.items),
104 };
105 newest.items.set(1, { ...newest.items.get(1)!, score: 2 });
106 newest.items.set(2, { ...newest.items.get(2)!, score: 0 });
107 await publisher.tick(token, newest);
108 assert.equal(
109 (
110 await pool.query(
111 "SELECT due_at FROM hn_ingest_pending WHERE key='item:1'",
112 )
113 ).rows[0].due_at,
114 queued.find((job) => job.key === "item:1").due_at,
115 "Latest value retains its first deadline",
116 );
117 assert.equal(
118 (
119 await pool.query(
120 "SELECT key FROM hn_ingest_pending WHERE key='item:2'",
121 )
122 ).rowCount,
123 0,
124 "A reverted change is cancelled",
125 );
126 await pool.query(
127 "UPDATE hn_ingest_pending SET due_at=0 WHERE key='feed:top'",
128 );
129 publisher.reset();
130 await publisher.tick(token);
131 const feed = (
132 await pool.query(
133 "SELECT item_id,rank FROM hn_feed_entries WHERE feed='top' ORDER BY rank",
134 )
135 ).rows;
136 assert.deepEqual(
137 feed.map((row) => row.item_id),
138 newest.feeds.top,
139 );
140 assert.deepEqual(
141 feed.map((row) => row.rank),
142 [1, 2, 3, 4, 5, 6],
143 );
144 assert.equal(
145 (await pool.query("SELECT title FROM hn_items WHERE id=7")).rows[0]
146 .title,
147 "Story 7",
148 );
149 assert.equal(
150 (await pool.query("SELECT score FROM hn_items WHERE id=1")).rows[0]
151 .score,
152 0,
153 "Feed reorders do not bypass unrelated score delays",
154 );
155 await publisher.tick(token, newest);
156​
157 // Transfer ownership with pending future work. The successor sees exactly
158 // the same deadlines and the old writer cannot stage or apply anything.
159 await pool.query(
160 "UPDATE ingest_leases SET active_session_end=clock_timestamp()",
161 );
162 const second = new Leases(
163 pool,
164 "second",
165 Date.now() + 120000,
166 90000,
167 60000,
168 );
169 assert.equal((await second.acquire()).role, "standby");
170 await second.renew("standby", token, true);
171 assert.equal(await first.handoff(token), "second");
172 const nextToken = (await second.promoteIfNeeded())!.fencing;
173 keeper = { lease: second, token: nextToken };
174 const successor = new SmoothingPublisher(pool, second, 28000);
175 const before = (
176 await pool.query(
177 "SELECT key,due_at FROM hn_ingest_pending ORDER BY key",
178 )
179 ).rows;
180 assert.equal(await successor.tick(nextToken, newest), 0);
181 assert.deepEqual(
182 (
183 await pool.query(
184 "SELECT key,due_at FROM hn_ingest_pending ORDER BY key",
185 )
186 ).rows,
187 before,
188 );
189 await assert.rejects(publisher.tick(token, newest), LostLease);
190 await pool.query("UPDATE hn_ingest_pending SET due_at=0");
191 successor.reset();
192 await successor.tick(nextToken);
193 assert.deepEqual(
194 (await pool.query("SELECT score FROM hn_items ORDER BY id")).rows.map(
195 (row) => row.score,
196 ),
197 [2, 0, 1, 1, 1, 1, 1],
198 );
199​
200 await pool.query("INSERT INTO hn_threads(story_id) VALUES(1)");
201 const thread: ThreadSnapshot = {
202 story: { ...newest.items.get(1)!, descendants: 2 },
203 receivedAt: Date.now(),
204 truncated: false,
205 rows: [
206 {
207 item: { id: 11, text: "Parent" },
208 parentId: 1,
209 path: "000001",
210 depth: 0,
211 },
212 {
213 item: { id: 12, text: "Reply" },
214 parentId: 11,
215 path: "000001.000001",
216 depth: 1,
217 },
218 ],
219 };
220 await successor.tick(nextToken, {
221 ...newest,
222 threads: [thread],
223 revision: 5,
224 });
225 assert.equal(
226 (await pool.query("SELECT count(*) FROM hn_comments")).rows[0].count,
227 "2",
228 "A new thread fills immediately",
229 );
230 const changed: ThreadSnapshot = {
231 ...thread,
232 story: { ...thread.story, descendants: 3 },
233 rows: [
234 { ...thread.rows[0], item: { id: 11, text: "Edited parent" } },
235 { ...thread.rows[1], item: { id: 12, text: "Edited reply" } },
236 {
237 item: { id: 13, text: "New reply" },
238 parentId: 11,
239 path: "000001.000002",
240 depth: 1,
241 },
242 ],
243 };
244 assert.equal(
245 await successor.tick(nextToken, {
246 ...newest,
247 threads: [changed],
248 revision: 6,
249 }),
250 0,
251 );
252 await pool.query("UPDATE hn_ingest_pending SET due_at=due_at+120000");
253 await pool.query(
254 "UPDATE hn_ingest_pending SET due_at=0 WHERE key='comment:1:11'",
255 );
256 successor.reset();
257 await successor.tick(nextToken);
258 assert.equal(
259 (await pool.query("SELECT text FROM hn_comments WHERE item_id=11"))
260 .rows[0].text,
261 "Edited parent",
262 );
263 const again = {
264 ...changed,
265 rows: changed.rows.map((row) =>
266 row.item.id === 13
267 ? { ...row, item: { ...row.item, text: "Edited new reply" } }
268 : row,
269 ),
270 };
271 await successor.tick(nextToken, {
272 ...newest,
273 threads: [again],
274 revision: 7,
275 });
276 const dependencies = (
277 await pool.query(
278 "SELECT key,due_at FROM hn_ingest_pending WHERE key IN ('thread:1','comment:1:13')",
279 )
280 ).rows;
281 assert.equal(dependencies.length, 2);
282 assert.ok(
283 Number(dependencies.find((job) => job.key === "comment:1:13").due_at) >=
284 Number(dependencies.find((job) => job.key === "thread:1").due_at),
285 );
286 await pool.query(
287 "UPDATE hn_ingest_pending SET due_at=0 WHERE key='thread:1'",
288 );
289 successor.reset();
290 await successor.tick(nextToken);
291 assert.equal(
292 (await pool.query("SELECT text FROM hn_comments WHERE item_id=11"))
293 .rows[0].text,
294 "Edited parent",
295 "Later tree writes preserve already published comment edits",
296 );
297 assert.equal(
298 (await pool.query("SELECT count(*) FROM hn_comments")).rows[0].count,
299 "3",
300 );
301​
302 // Remove a reply while its edit is pending; content jobs never insert it.
303 const removed = {
304 ...again,
305 story: { ...again.story, descendants: 2 },
306 rows: again.rows.slice(0, 2),
307 };
308 await successor.tick(nextToken, {
309 ...newest,
310 threads: [removed],
311 revision: 8,
312 });
313 await pool.query(
314 "UPDATE hn_ingest_pending SET due_at=0 WHERE key='thread:1'",
315 );
316 successor.reset();
317 await successor.tick(nextToken);
318 assert.equal(
319 (await pool.query("SELECT item_id FROM hn_comments WHERE item_id=13"))
320 .rowCount,
321 0,
322 );
323 const immediate = new SmoothingPublisher(pool, second, 0);
324 await immediate.tick(nextToken, {
325 ...newest,
326 threads: [removed],
327 revision: 9,
328 });
329 assert.equal(
330 (await pool.query("SELECT count(*) FROM hn_ingest_pending")).rows[0]
331 .count,
332 "0",
333 );
334 assert.equal(
335 (await pool.query("SELECT item_id FROM hn_comments WHERE item_id=13"))
336 .rowCount,
337 0,
338 );
339 assert.equal(
340 (await pool.query("SELECT text FROM hn_comments WHERE item_id=12"))
341 .rows[0].text,
342 "Edited reply",
343 );
344 const final = { ...newest, revision: 10, items: new Map(newest.items) };
345 final.items.set(2, { ...final.items.get(2)!, score: 5 });
346 await immediate.tick(nextToken, final);
347 assert.equal(
348 (await pool.query("SELECT score FROM hn_items WHERE id=2")).rows[0]
349 .score,
350 5,
351 );
352​
353 const events = (await pool.query("SELECT count(*) FROM hn_events"))
354 .rows[0].count;
355 await assert.rejects(
356 successor.tick(nextToken, {
357 ...final,
358 threads: [
359 { ...removed, rows: [{ ...removed.rows[0], parentId: 99 }] },
360 ],
361 }),
362 /Invalid thread/,
363 );
364 assert.equal(
365 (await pool.query("SELECT count(*) FROM hn_events")).rows[0].count,
366 events,
367 );
368 assert.equal(
369 (await pool.query("SELECT count(*) FROM hn_ingest_pending")).rows[0]
370 .count,
371 "0",
372 );
373 } finally {
374 clearInterval(heartbeat);
375 await renewing;
376 await pool.end();
377 await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
378 await admin.end();
379 }
380 },
381);