Open History to see the last commit
1import { randomUUID } from "node:crypto";
2import { setTimeout as delay } from "node:timers/promises";
3import type { Pool } from "pg";
4import { readHn, mapLimit, type HnItem } from "./hn-api";
5import {
6 orderedComments,
7 selectComments,
8 type ThreadSnapshot,
9} from "./comment-tree";
10import { publishThread } from "./thread-store";
11
12type Reader = (path: string, signal?: AbortSignal) => Promise<HnItem | null>;
13export async function firstComments(
14 id: number,
15 read: Reader = readHn,
16): Promise<ThreadSnapshot> {
17 // Load a small parallel batch; first render needn't wait for the whole tree.
18 const signal = AbortSignal.timeout(4500);
19 const root = await read(`item/${id}`, signal);
20 if (!root || !["story", "job", "poll"].includes(root.type ?? ""))
21 throw new Error("HN story is unavailable");
22 const ids = selectComments(root, new Map()).ids.slice(0, 20);
23 const pairs = await mapLimit(
24 ids,
25 20,
26 async (childId) =>
27 [
28 childId,
29 (await read(`item/${childId}`, signal)) ?? {
30 id: childId,
31 deleted: true,
32 },
33 ] as const,
34 );
35 const items = new Map(pairs);
36 const selected = selectComments(root, items);
37 return {
38 story: root,
39 rows: orderedComments(root, items),
40 truncated: selected.truncated,
41 receivedAt: Date.now(),
42 complete: selected.ids.every((childId) => items.has(childId)),
43 };
44}
45
46// A DB claim deduplicates cold loads across web instances. Never hold a pool
47// connection over HN requests. A newer worker publication wins the seed race.
48export async function loadThread(pool: Pool, id: number, read?: Reader) {
49 const owner = randomUUID();
50 const deadline = Date.now() + 5500;
51 while (true) {
52 const claim = await pool.query(
53 `INSERT INTO hn_threads(story_id,requested_at,initial_load_owner,initial_load_until)
54 SELECT id,'-infinity',$2,clock_timestamp()+interval '8 seconds' FROM hn_items
55 WHERE id=$1 AND type IN ('story','job','poll')
56 ON CONFLICT(story_id) DO UPDATE SET initial_load_owner=$2,initial_load_until=clock_timestamp()+interval '8 seconds'
57 WHERE hn_threads.loaded_at IS NULL AND (hn_threads.initial_load_until IS NULL OR hn_threads.initial_load_until<clock_timestamp())
58 RETURNING story_id`,
59 [id, owner],
60 );
61 if (claim.rowCount) break;
62 const current = (
63 await pool.query("SELECT loaded_at FROM hn_threads WHERE story_id=$1", [
64 id,
65 ])
66 ).rows[0];
67 if (!current || current.loaded_at || Date.now() >= deadline) return;
68 await delay(150);
69 }
70 try {
71 const snapshot = await firstComments(id, read);
72 const client = await pool.connect();
73 try {
74 await client.query("BEGIN");
75 const current = await client.query(
76 `SELECT 1 FROM hn_threads WHERE story_id=$1 AND initial_load_owner=$2
77 AND initial_load_until>clock_timestamp() AND loaded_at IS NULL FOR UPDATE`,
78 [id, owner],
79 );
80 if (current.rowCount)
81 await publishThread(client, snapshot, new Date().toISOString());
82 await client.query("COMMIT");
83 } catch (error) {
84 await client.query("ROLLBACK");
85 throw error;
86 } finally {
87 client.release();
88 }
89 } finally {
90 await pool.query(
91 "UPDATE hn_threads SET initial_load_owner=NULL,initial_load_until=NULL WHERE story_id=$1 AND initial_load_owner=$2",
92 [id, owner],
93 );
94 }
95}