Open History to see the last commit
1import type { PoolClient } from "pg";
2import { THREAD_LIMIT } from "../lib/comments";
3import type { ThreadSnapshot } from "./comment-tree";
4export function validateThread(thread: ThreadSnapshot) {
5 const ids = thread.rows.map((row) => row.item.id);
6 if (
7 ids.length > THREAD_LIMIT ||
8 new Set(ids).size !== ids.length ||
9 thread.rows.some(
10 (row) => row.parentId !== thread.story.id && !ids.includes(row.parentId),
11 )
12 )
13 throw new Error("Invalid thread snapshot");
14}
15
16export function commentRecords(thread: ThreadSnapshot, committedAt: string) {
17 return thread.rows.map((row) => ({
18 story_id: thread.story.id,
19 item_id: row.item.id,
20 parent_id: row.parentId,
21 path: row.path,
22 depth: row.depth,
23 author: row.item.by ?? null,
24 created: row.item.time ?? 0,
25 text: row.item.text ?? "",
26 deleted: Boolean(row.item.deleted),
27 dead: Boolean(row.item.dead),
28 committed_at: committedAt,
29 }));
30}
31export type CommentRecord = ReturnType<typeof commentRecords>[number];
32
33export async function publishComment(
34 client: PoolClient,
35 row: CommentRecord,
36 committedAt: string,
37) {
38 // Structure jobs insert parents and descendants together. Content jobs only
39 // update existing rows, so a delayed edit cannot resurrect a removed reply.
40 const result = await client.query(
41 `UPDATE hn_comments SET author=$3,created=$4,text=$5,deleted=$6,dead=$7,committed_at=$8
42 WHERE story_id=$1 AND item_id=$2 AND (author,created,text,deleted,dead)
43 IS DISTINCT FROM ($3::text,$4::integer,$5::text,$6::boolean,$7::boolean)`,
44 [
45 row.story_id,
46 row.item_id,
47 row.author,
48 row.created,
49 row.text,
50 row.deleted,
51 row.dead,
52 committedAt,
53 ],
54 );
55 if (result.rowCount)
56 await client.query(
57 "UPDATE hn_threads SET committed_at=clock_timestamp() WHERE story_id=$1",
58 [row.story_id],
59 );
60 return result.rowCount ?? 0;
61}
62
63export async function publishThread(
64 client: PoolClient,
65 thread: ThreadSnapshot,
66 committedAt: string,
67 structureOnly = false,
68) {
69 validateThread(thread);
70 const ids = thread.rows.map((row) => row.item.id);
71 // Serialize cold-page seeds with the worker. Incomplete trees only add rows.
72 const locked = await client.query(
73 "SELECT story_id FROM hn_threads WHERE story_id=$1 FOR UPDATE",
74 [thread.story.id],
75 );
76 if (!locked.rowCount) throw new Error("Thread is not registered");
77 const complete = thread.complete !== false;
78 const records = commentRecords(thread, committedAt);
79 const removed = complete
80 ? await client.query(
81 "DELETE FROM hn_comments WHERE story_id=$1 AND NOT(item_id=ANY($2::integer[]))",
82 [thread.story.id, ids],
83 )
84 : { rowCount: 0 };
85 const written = await client.query(
86 `INSERT INTO hn_comments SELECT * FROM jsonb_to_recordset($1::jsonb)
87 AS x(story_id integer,item_id integer,parent_id integer,path text,depth integer,author text,created integer,text text,deleted boolean,dead boolean,committed_at text)
88 ON CONFLICT(story_id,item_id) ${
89 !complete
90 ? "DO NOTHING"
91 : structureOnly
92 ? `DO UPDATE SET parent_id=EXCLUDED.parent_id,path=EXCLUDED.path,depth=EXCLUDED.depth,committed_at=EXCLUDED.committed_at
93 WHERE (hn_comments.parent_id,hn_comments.path,hn_comments.depth)
94 IS DISTINCT FROM (EXCLUDED.parent_id,EXCLUDED.path,EXCLUDED.depth)`
95 : `DO UPDATE SET parent_id=EXCLUDED.parent_id,path=EXCLUDED.path,depth=EXCLUDED.depth,
96 author=EXCLUDED.author,created=EXCLUDED.created,text=EXCLUDED.text,deleted=EXCLUDED.deleted,dead=EXCLUDED.dead,committed_at=EXCLUDED.committed_at
97 WHERE (hn_comments.parent_id,hn_comments.path,hn_comments.depth,hn_comments.author,hn_comments.created,hn_comments.text,hn_comments.deleted,hn_comments.dead)
98 IS DISTINCT FROM (EXCLUDED.parent_id,EXCLUDED.path,EXCLUDED.depth,EXCLUDED.author,EXCLUDED.created,EXCLUDED.text,EXCLUDED.deleted,EXCLUDED.dead)`
99 }`,
100 [JSON.stringify(records)],
101 );
102 const changed = (removed.rowCount ?? 0) + (written.rowCount ?? 0);
103 await client.query(
104 `UPDATE hn_threads SET state=$4,checked_at=CASE WHEN $4='healthy' THEN clock_timestamp() ELSE checked_at END,truncated=$2,
105 loaded_at=CASE WHEN $5 THEN COALESCE(loaded_at,clock_timestamp()) ELSE loaded_at END,
106 ingest_initialized=ingest_initialized OR $6,
107 committed_at=CASE WHEN $3>0 THEN clock_timestamp() ELSE committed_at END WHERE story_id=$1`,
108 [
109 thread.story.id,
110 thread.truncated,
111 changed,
112 complete ? "healthy" : "starting",
113 complete || ids.length > 0,
114 complete,
115 ],
116 );
117 return changed;
118}