Open History to see the last commit
1import { test } from "node:test";
2import assert from "node:assert/strict";
3import { randomUUID } from "node:crypto";
4import { setTimeout as delay } from "node:timers/promises";
5import { Pool } from "pg";
6import { migrate } from "../ingest/migrate";
7import { loadThread } from "../ingest/thread-load";
8import { updateThreadView, watchedThreads } from "../ingest/thread-watch";
9import { publishThread } from "../ingest/thread-store";
10import type { ThreadSnapshot } from "../ingest/comment-tree";
11
12test(
13 "cold page seeds, concurrent requests, partial publications and ownership races",
14 { skip: !process.env.RUN_DB_TESTS },
15 async () => {
16 const schema = `hn_loading_test_${Date.now()}`;
17 const admin = new Pool({
18 connectionString: process.env.DATABASE_URL_UNPOOLED,
19 });
20 await admin.query(`CREATE SCHEMA ${schema}`);
21 const pool = new Pool({
22 connectionString: process.env.DATABASE_URL_UNPOOLED,
23 options: `-c search_path=${schema}`,
24 max: 4,
25 });
26 try {
27 await migrate(pool);
28 await pool.query(
29 "INSERT INTO hn_items(id,type,title,created,committed_at) SELECT id,'story','Test story',0,'initial' FROM generate_series(1,5) id",
30 );
31 let reads = 0;
32 const reader = async (path: string) => {
33 reads++;
34 await delay(80);
35 const id = Number(path.slice(5));
36 return id === 1
37 ? { id, type: "story", kids: [11] }
38 : { id, type: "comment", text: "Seed", kids: [12] };
39 };
40 await Promise.all([
41 loadThread(pool, 1, reader),
42 loadThread(pool, 1, reader),
43 loadThread(pool, 1, reader),
44 ]);
45 assert.equal(
46 reads,
47 2,
48 "one root and one initial comment, shared across requests",
49 );
50 assert.equal(
51 (await pool.query("SELECT count(*) FROM hn_comments WHERE story_id=1"))
52 .rows[0].count,
53 "1",
54 );
55 await loadThread(pool, 1, reader);
56 assert.equal(reads, 2, "cached load does not fetch HN");
57 assert.deepEqual(
58 await watchedThreads(pool),
59 [],
60 "prefetch/SSR loading does not create ongoing watches",
61 );
62 const complete: ThreadSnapshot = {
63 story: { id: 1 },
64 receivedAt: Date.now(),
65 truncated: false,
66 rows: [
67 {
68 item: { id: 11, text: "Newer value" },
69 parentId: 1,
70 path: "000001",
71 depth: 0,
72 },
73 {
74 item: { id: 12, text: "Reply" },
75 parentId: 11,
76 path: "000001.000001",
77 depth: 1,
78 },
79 ],
80 };
81 const publish = async (snapshot: ThreadSnapshot) => {
82 const client = await pool.connect();
83 try {
84 await client.query("BEGIN");
85 const count = await publishThread(
86 client,
87 snapshot,
88 new Date().toISOString(),
89 );
90 await client.query("COMMIT");
91 return count;
92 } catch (error) {
93 await client.query("ROLLBACK");
94 throw error;
95 } finally {
96 client.release();
97 }
98 };
99 await publish(complete);
100 assert.equal(
101 await publish({
102 ...complete,
103 complete: false,
104 rows: [{ ...complete.rows[0], item: { id: 11, text: "Stale seed" } }],
105 }),
106 0,
107 );
108 assert.equal(
109 (
110 await pool.query(
111 "SELECT text FROM hn_comments WHERE story_id=1 ORDER BY path",
112 )
113 ).rows[0].text,
114 "Newer value",
115 );
116 assert.equal(
117 (await pool.query("SELECT count(*) FROM hn_comments WHERE story_id=1"))
118 .rows[0].count,
119 "2",
120 );
121 assert.equal(
122 await publish({ ...complete, rows: [complete.rows[0]] }),
123 1,
124 "authoritative snapshots remove missing descendants",
125 );
126
127 let fetched!: () => void;
128 let finish!: () => void;
129 const started = new Promise<void>((resolve) => {
130 fetched = resolve;
131 });
132 const gate = new Promise<void>((resolve) => {
133 finish = resolve;
134 });
135 const loading = loadThread(pool, 2, async () => {
136 fetched();
137 await gate;
138 return { id: 2, type: "story", kids: [] };
139 });
140 await started;
141 await publish({
142 story: { id: 2 },
143 rows: [
144 {
145 item: { id: 21, text: "Worker wins" },
146 parentId: 2,
147 path: "000001",
148 depth: 0,
149 },
150 ],
151 receivedAt: Date.now(),
152 truncated: false,
153 });
154 finish();
155 await loading;
156 assert.equal(
157 (await pool.query("SELECT text FROM hn_comments WHERE story_id=2"))
158 .rows[0].text,
159 "Worker wins",
160 );
161
162 const replacement = randomUUID();
163 await loadThread(pool, 3, async () => {
164 await pool.query(
165 "UPDATE hn_threads SET initial_load_owner=$2 WHERE story_id=$1",
166 [3, replacement],
167 );
168 return { id: 3, type: "story", kids: [] };
169 });
170 const replaced = (
171 await pool.query(
172 "SELECT initial_load_owner,loaded_at FROM hn_threads WHERE story_id=3",
173 )
174 ).rows[0];
175 assert.equal(replaced.initial_load_owner, replacement);
176 assert.equal(
177 replaced.loaded_at,
178 null,
179 "an expired/replaced owner cannot seed or release another owner's claim",
180 );
181 await pool.query(
182 "UPDATE hn_threads SET initial_load_until=clock_timestamp()-interval '1 second' WHERE story_id=3",
183 );
184 await loadThread(pool, 3, async () => ({ id: 3, type: "story" }));
185 assert.ok(
186 (await pool.query("SELECT loaded_at FROM hn_threads WHERE story_id=3"))
187 .rows[0].loaded_at,
188 );
189 await assert.rejects(
190 loadThread(pool, 4, async () => {
191 throw new Error("HN offline");
192 }),
193 /offline/,
194 );
195 assert.equal(
196 (
197 await pool.query(
198 "SELECT initial_load_owner FROM hn_threads WHERE story_id=4",
199 )
200 ).rows[0].initial_load_owner,
201 null,
202 );
203 await loadThread(pool, 999, async () => {
204 throw new Error("Unknown story should not fetch");
205 });
206 } finally {
207 await pool.end();
208 await admin.query(`DROP SCHEMA ${schema} CASCADE`);
209 await admin.end();
210 }
211 },
212);
213
214test(
215 "more than three open threads, independent viewers, expiry and reordered release",
216 { skip: !process.env.RUN_DB_TESTS },
217 async () => {
218 const schema = `hn_views_test_${Date.now()}`;
219 const admin = new Pool({
220 connectionString: process.env.DATABASE_URL_UNPOOLED,
221 });
222 await admin.query(`CREATE SCHEMA ${schema}`);
223 const pool = new Pool({
224 connectionString: process.env.DATABASE_URL_UNPOOLED,
225 options: `-c search_path=${schema}`,
226 max: 4,
227 });
228 try {
229 await migrate(pool);
230 await pool.query(
231 "INSERT INTO hn_items(id,type,title,created,committed_at) SELECT id,'story','Test',0,'initial' FROM generate_series(1,5) id",
232 );
233 const viewers = Array.from({ length: 5 }, () => randomUUID());
234 const health = await Promise.all(
235 viewers.map((viewer, i) => updateThreadView(pool, i + 1, viewer)),
236 );
237 assert.ok(health.every((value) => value?.state === "starting"));
238 assert.deepEqual(await watchedThreads(pool), [1, 2, 3, 4, 5]);
239 const another = randomUUID();
240 await updateThreadView(pool, 1, another);
241 await updateThreadView(pool, 1, viewers[0], true);
242 assert.deepEqual(
243 await watchedThreads(pool),
244 [1, 2, 3, 4, 5],
245 "another viewer keeps the same story watched",
246 );
247 await updateThreadView(pool, 1, another, true);
248 await updateThreadView(pool, 1, viewers[0]);
249 assert.deepEqual(
250 await watchedThreads(pool),
251 [2, 3, 4, 5],
252 "late renewal cannot resurrect a released watch",
253 );
254 const arrivedLate = randomUUID();
255 await updateThreadView(pool, 1, arrivedLate, true);
256 await updateThreadView(pool, 1, arrivedLate);
257 assert.deepEqual(await watchedThreads(pool), [2, 3, 4, 5]);
258 await pool.query(
259 "UPDATE hn_thread_views SET requested_at=clock_timestamp()-interval '31 seconds' WHERE story_id=2",
260 );
261 assert.deepEqual(await watchedThreads(pool), [3, 4, 5]);
262 await updateThreadView(pool, 2);
263 assert.deepEqual(
264 await watchedThreads(pool),
265 [2, 3, 4, 5],
266 "old clients still renew a short legacy lease",
267 );
268 assert.equal(await updateThreadView(pool, 999, randomUUID()), null);
269 } finally {
270 await pool.end();
271 await admin.query(`DROP SCHEMA ${schema} CASCADE`);
272 await admin.end();
273 }
274 },
275);