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

thread-watch.ts

83 lines2.7 KB

1import type { Pool } from "pg";
2import { WATCH_SECONDS, type ThreadHealth } from "../lib/comments";
3​
4export async function updateThreadView(
5 pool: Pool,
6 id: number,
7 viewer?: string,
8 released = false,
9): Promise<ThreadHealth | null> {
10 const client = await pool.connect();
11 try {
12 await client.query("BEGIN");
13 const known = await client.query(
14 "SELECT id FROM hn_items WHERE id=$1 AND type IN ('story','job','poll')",
15 [id],
16 );
17 if (!known.rowCount) {
18 await client.query("ROLLBACK");
19 return null;
20 }
21 await client.query(
22 "INSERT INTO hn_threads(story_id,requested_at) VALUES($1,'-infinity') ON CONFLICT DO NOTHING",
23 [id],
24 );
25 if (viewer) {
26 // A release wins even when an earlier renewal arrives afterwards.
27 await client.query(
28 `INSERT INTO hn_thread_views(viewer_id,story_id,released) VALUES($1,$2,$3)
29 ON CONFLICT(viewer_id,story_id) DO UPDATE SET requested_at=clock_timestamp(),
30 released=hn_thread_views.released OR EXCLUDED.released`,
31 [viewer, id, released],
32 );
33 } else {
34 // Old deployed tabs only send an ID. Keep a short lease until reload.
35 await client.query(
36 "UPDATE hn_threads SET requested_at=clock_timestamp() WHERE story_id=$1",
37 [id],
38 );
39 }
40 const { rows } = await client.query(
41 `SELECT state,checked_at,committed_at,truncated,
42 EXISTS(SELECT 1 FROM ingest_leases WHERE id=1 AND active_until>clock_timestamp()) AS owned
43 FROM hn_threads WHERE story_id=$1`,
44 [id],
45 );
46 await client.query("COMMIT");
47 const row = rows[0];
48 const checkedAt = row.checked_at
49 ? new Date(row.checked_at).toISOString()
50 : null;
51 const fresh =
52 checkedAt && Date.now() - Date.parse(checkedAt) < 30000 && row.owned;
53 return {
54 state: fresh
55 ? row.state
56 : row.state === "starting"
57 ? "starting"
58 : "degraded",
59 checkedAt,
60 committedAt: row.committed_at
61 ? new Date(row.committed_at).toISOString()
62 : null,
63 truncated: row.truncated,
64 };
65 } catch (error) {
66 await client.query("ROLLBACK");
67 throw error;
68 } finally {
69 client.release();
70 }
72​
73export async function watchedThreads(pool: Pool): Promise<number[]> {
74 const { rows } = await pool.query(
75 `SELECT story_id FROM hn_threads t
76 WHERE requested_at>clock_timestamp()-$1::integer*interval '1 second'
77 OR EXISTS(SELECT 1 FROM hn_thread_views v WHERE v.story_id=t.story_id AND NOT v.released
78 AND v.requested_at>clock_timestamp()-$1::integer*interval '1 second')
79 ORDER BY story_id`,
80 [WATCH_SECONDS],
81 );
82 return rows.map((row) => row.story_id);