Open History to see the last commit
1import type { Pool, PoolClient } from "pg";
2import { isDeepStrictEqual } from "node:util";
3import type { Feed } from "../lib/types";
4import type { SourceSnapshot } from "./source";
5import type { ThreadSnapshot } from "./comment-tree";
6import { Leases } from "./lease";
7import {
8 itemRecord,
9 writeItems,
10 writeFeed,
11 recordCommit,
12 type ItemRecord,
13} from "./store";
14import {
15 commentRecords,
16 publishThread,
17 publishComment,
18 validateThread,
19 type CommentRecord,
20} from "./thread-store";
21
22export type Change =
23 | { kind: "item"; record: ItemRecord }
24 | { kind: "feed"; feed: Feed; ids: number[]; items: ItemRecord[] }
25 | { kind: "thread"; thread: ThreadSnapshot }
26 | { kind: "comment"; record: CommentRecord; afterStructure?: boolean };
27export interface PendingChange {
28 key: string;
29 due_at: number;
30 received_at: number;
31 revision: number;
32 payload: Change;
33}
34
35const content = (row: CommentRecord) => [
36 row.author,
37 row.created,
38 row.text,
39 row.deleted,
40 row.dead,
41];
42const structure = (rows: CommentRecord[], truncated: boolean) => ({
43 rows: rows.map((row) => [row.item_id, row.parent_id, row.path, row.depth]),
44 truncated,
45});
46const sameItem = (a: ItemRecord | undefined, b: ItemRecord) =>
47 a &&
48 Object.keys(b).every(
49 (key) =>
50 key === "committed_at" ||
51 a[key as keyof ItemRecord] === b[key as keyof ItemRecord],
52 );
53
54// Existing deadlines survive revisions and handoffs. Overlapping updates to a
55// row replace its pending value rather than postponing it indefinitely.
56export function spreadChanges(
57 changes: PendingChange[],
58 now: number,
59 windowMs: number,
60) {
61 const fresh = changes
62 .filter((change) => change.due_at < 0)
63 .sort((a, b) => a.key.localeCompare(b.key));
64 fresh.forEach((change, index) => {
65 change.due_at = Math.round(
66 now + (windowMs * (index + 1)) / (fresh.length + 1),
67 );
68 });
69 const structures = new Map(
70 changes
71 .filter((change) => change.payload.kind === "thread")
72 .map((change) => [change.key, change.due_at]),
73 );
74 for (const change of changes)
75 if (change.payload.kind === "comment" && change.payload.afterStructure) {
76 const due = structures.get(`thread:${change.payload.record.story_id}`);
77 if (due !== undefined) change.due_at = Math.max(change.due_at, due);
78 }
79 return changes;
80}
81
82export class SmoothingPublisher {
83 private nextDueAt = 0;
84 constructor(
85 private pool: Pool,
86 private leases: Leases,
87 readonly windowMs: number,
88 ) {
89 if (!Number.isInteger(windowMs) || windowMs < 0 || windowMs > 60000)
90 throw new Error("Invalid ingestion smoothing window (0–60000 ms)");
91 }
92 reset() {
93 this.nextDueAt = 0;
94 }
95
96 async tick(fencing: string, snapshot?: SourceSnapshot) {
97 if (!snapshot && Date.now() < this.nextDueAt) return 0;
98 const client = await this.pool.connect();
99 try {
100 await client.query("BEGIN");
101 await this.leases.assert(client, fencing);
102 const clockReadAt = Date.now();
103 const now = Number(
104 (
105 await client.query(
106 "SELECT (extract(epoch FROM clock_timestamp())*1000)::bigint AS now",
107 )
108 ).rows[0].now,
109 );
110 const committedAt = new Date(now).toISOString();
111 const counts = { changedItems: 0, changedEntries: 0, changedComments: 0 };
112 const received: number[] = [];
113 if (snapshot)
114 await this.stage(client, snapshot, now, committedAt, counts, received);
115 const due: PendingChange[] = (
116 await client.query(
117 `SELECT * FROM hn_ingest_pending WHERE due_at<=$1 OR $2=0 ORDER BY
118 CASE payload->>'kind' WHEN 'item' THEN 0 WHEN 'feed' THEN 1 WHEN 'thread' THEN 2 ELSE 3 END,
119 due_at,key`,
120 [now, this.windowMs],
121 )
122 ).rows;
123 for (const job of due) {
124 const change = job.payload;
125 if (change.kind === "item")
126 counts.changedItems += (
127 await writeItems(client, [
128 { ...change.record, committed_at: committedAt },
129 ])
130 ).length;
131 else if (change.kind === "feed") {
132 // New feed entries need complete records; existing items retain their
133 // independently scheduled score/count updates.
134 counts.changedItems += (
135 await writeItems(
136 client,
137 change.items.map((record) => ({
138 ...record,
139 committed_at: committedAt,
140 })),
141 true,
142 )
143 ).length;
144 counts.changedEntries += await writeFeed(
145 client,
146 change.feed,
147 change.ids,
148 );
149 } else if (change.kind === "thread")
150 counts.changedComments += await publishThread(
151 client,
152 change.thread,
153 committedAt,
154 true,
155 );
156 else
157 counts.changedComments += await publishComment(
158 client,
159 change.record,
160 committedAt,
161 );
162 received.push(Number(job.received_at));
163 }
164 await client.query(
165 "DELETE FROM hn_ingest_pending WHERE key=ANY($1::text[])",
166 [due.map((job) => job.key)],
167 );
168 await this.leases.assert(client, fencing);
169 const changed = await recordCommit(
170 client,
171 this.leases,
172 counts,
173 received,
174 snapshot?.revision ?? Number(due.at(-1)?.revision ?? 0),
175 committedAt,
176 this.windowMs,
177 );
178 const next = (
179 await client.query("SELECT min(due_at) AS due FROM hn_ingest_pending")
180 ).rows[0].due;
181 await client.query("COMMIT");
182 this.nextDueAt =
183 next === null ? Infinity : clockReadAt + Math.max(0, Number(next) - now);
184 return changed;
185 } catch (error) {
186 await client.query("ROLLBACK");
187 throw error;
188 } finally {
189 client.release();
190 }
191 }
192
193 private async stage(
194 client: PoolClient,
195 snapshot: SourceSnapshot,
196 now: number,
197 committedAt: string,
198 counts: {
199 changedItems: number;
200 changedEntries: number;
201 changedComments: number;
202 },
203 received: number[],
204 ) {
205 const feedIds = new Set([...snapshot.feeds.top, ...snapshot.feeds.new]);
206 if ([...feedIds].some((id) => !snapshot.items.has(id)))
207 throw new Error("Feed snapshot is incomplete");
208 for (const thread of snapshot.threads ?? []) validateThread(thread);
209 const sourceItems = new Map(
210 [...feedIds].map((id) => [id, snapshot.items.get(id)!]),
211 );
212 for (const thread of snapshot.threads ?? [])
213 sourceItems.set(thread.story.id, thread.story);
214 const records = new Map(
215 [...sourceItems].map(([id, item]) => [id, itemRecord(item, "")]),
216 );
217 const existingItems: Map<number, ItemRecord> = new Map(
218 (
219 await client.query(
220 "SELECT * FROM hn_items WHERE id=ANY($1::integer[])",
221 [[...records.keys()]],
222 )
223 ).rows.map((row) => [row.id, row]),
224 );
225 const feeds = (
226 await client.query(
227 "SELECT feed,item_id FROM hn_feed_entries ORDER BY feed,rank",
228 )
229 ).rows;
230 const pending: Map<string, PendingChange> = new Map(
231 (await client.query("SELECT * FROM hn_ingest_pending")).rows.map(
232 (row) => [
233 row.key,
234 {
235 ...row,
236 due_at: Number(row.due_at),
237 received_at: Number(row.received_at),
238 },
239 ],
240 ),
241 );
242 const changes = new Map<string, PendingChange>();
243 const cancelled = new Set<string>();
244 const schedule = (
245 key: string,
246 payload: Change,
247 matchesCurrent: boolean,
248 matchesPending: boolean,
249 receipt: number,
250 ) => {
251 const old = pending.get(key);
252 if (matchesCurrent) {
253 if (old) cancelled.add(key);
254 return;
255 }
256 if (old && matchesPending) return;
257 changes.set(key, {
258 key,
259 payload,
260 due_at: old?.due_at ?? -1,
261 received_at: (old?.received_at ?? receipt) || now,
262 revision: snapshot.revision,
263 });
264 };
265
266 // A fresh branch and a discussion's first reconciliation are baselines,
267 // not bursts of live changes: fill them without an artificial wait.
268 const bootstrap = feeds.length === 0;
269 if (bootstrap) {
270 counts.changedItems += (
271 await writeItems(
272 client,
273 [...records.values()].map((row) => ({
274 ...row,
275 committed_at: committedAt,
276 })),
277 )
278 ).length;
279 for (const feed of ["top", "new"] as const)
280 counts.changedEntries += await writeFeed(
281 client,
282 feed,
283 snapshot.feeds[feed],
284 );
285 received.push(snapshot.receivedAt || now);
286 }
287 const storyIds = (snapshot.threads ?? []).map((thread) => thread.story.id);
288 const threads = new Map(
289 (
290 await client.query(
291 "SELECT story_id,ingest_initialized,truncated FROM hn_threads WHERE story_id=ANY($1::integer[]) FOR UPDATE",
292 [storyIds],
293 )
294 ).rows.map((row) => [row.story_id, row]),
295 );
296 const comments: CommentRecord[] = (
297 await client.query(
298 "SELECT * FROM hn_comments WHERE story_id=ANY($1::integer[]) ORDER BY path,item_id",
299 [storyIds],
300 )
301 ).rows;
302 for (const thread of snapshot.threads ?? []) {
303 const state = threads.get(thread.story.id);
304 if (!state) throw new Error("Thread is not registered");
305 if (!state.ingest_initialized) {
306 const record = {
307 ...records.get(thread.story.id)!,
308 committed_at: committedAt,
309 };
310 counts.changedItems += (await writeItems(client, [record])).length;
311 existingItems.set(record.id, record);
312 cancelled.add(`item:${record.id}`);
313 counts.changedComments += await publishThread(
314 client,
315 thread,
316 committedAt,
317 );
318 received.push(thread.receivedAt || now);
319 continue;
320 }
321 // A warming successor must not overwrite a complete queued tree with a
322 // temporary partial snapshot. It will reconcile before changing it.
323 if (thread.complete === false) continue;
324 const key = `thread:${thread.story.id}`;
325 const current = comments.filter(
326 (row) => row.story_id === thread.story.id,
327 );
328 const next = commentRecords(thread, "");
329 const old = pending.get(key)?.payload;
330 const oldRows =
331 old?.kind === "thread" ? commentRecords(old.thread, "") : [];
332 const target = structure(next, thread.truncated);
333 schedule(
334 key,
335 { kind: "thread", thread },
336 isDeepStrictEqual(target, structure(current, state.truncated)),
337 old?.kind === "thread" &&
338 isDeepStrictEqual(target, structure(oldRows, old.thread.truncated)),
339 thread.receivedAt,
340 );
341 for (const row of next) {
342 const currentRow = current.find(
343 (value) => value.item_id === row.item_id,
344 );
345 const planned = oldRows.find((value) => value.item_id === row.item_id);
346 // New row contents are inserted with the structural update. If they
347 // change again before insertion, schedule the edit after that update.
348 if (!currentRow && !planned) continue;
349 const commentKey = `comment:${row.story_id}:${row.item_id}`;
350 const oldComment = pending.get(commentKey)?.payload;
351 schedule(
352 commentKey,
353 { kind: "comment", record: row, afterStructure: !currentRow },
354 isDeepStrictEqual(content(currentRow ?? planned!), content(row)),
355 oldComment?.kind === "comment" &&
356 isDeepStrictEqual(content(oldComment.record), content(row)),
357 thread.receivedAt,
358 );
359 }
360 }
361 if (!bootstrap) {
362 for (const [id, record] of records) {
363 const key = `item:${id}`;
364 const old = pending.get(key)?.payload;
365 schedule(
366 key,
367 { kind: "item", record },
368 Boolean(sameItem(existingItems.get(id), record)),
369 Boolean(old?.kind === "item" && sameItem(old.record, record)),
370 (snapshot.threads ?? []).find((thread) => thread.story.id === id)
371 ?.receivedAt ??
372 snapshot.itemReceipts?.get(id) ??
373 snapshot.receivedAt,
374 );
375 }
376 for (const feed of ["top", "new"] as const) {
377 const key = `feed:${feed}`;
378 const ids = snapshot.feeds[feed];
379 const old = pending.get(key)?.payload;
380 schedule(
381 key,
382 { kind: "feed", feed, ids, items: ids.map((id) => records.get(id)!) },
383 isDeepStrictEqual(
384 ids,
385 feeds.filter((row) => row.feed === feed).map((row) => row.item_id),
386 ),
387 old?.kind === "feed" && isDeepStrictEqual(ids, old.ids),
388 snapshot.feedReceipts?.[feed] || snapshot.receivedAt,
389 );
390 }
391 }
392 await client.query(
393 "DELETE FROM hn_ingest_pending WHERE key=ANY($1::text[])",
394 [[...cancelled]],
395 );
396 // Include existing structure deadlines when assigning dependent edits.
397 const scheduled = spreadChanges(
398 [
399 ...changes.values(),
400 ...[...pending.values()].filter(
401 (job) =>
402 job.payload.kind === "thread" &&
403 !changes.has(job.key) &&
404 !cancelled.has(job.key),
405 ),
406 ],
407 now,
408 this.windowMs,
409 );
410 await client.query(
411 `INSERT INTO hn_ingest_pending(key,due_at,received_at,revision,payload)
412 SELECT * FROM jsonb_to_recordset($1::jsonb)
413 AS x(key text,due_at bigint,received_at bigint,revision bigint,payload jsonb)
414 ON CONFLICT(key) DO UPDATE SET due_at=EXCLUDED.due_at,received_at=EXCLUDED.received_at,
415 revision=EXCLUDED.revision,payload=EXCLUDED.payload`,
416 [JSON.stringify(scheduled.filter((job) => changes.has(job.key)))],
417 );
418 }
419}