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

session.ts

249 lines8.7 KB

1import { randomUUID } from "node:crypto";
2import { setTimeout as delay } from "node:timers/promises";
3import type { Pool } from "pg";
4import { HnSource } from "./source";
5import { Leases, LostLease } from "./lease";
6import { SmoothingPublisher } from "./smoothing";
7import { watchedThreads } from "./thread-watch";
8export interface SessionOptions {
9 budgetMs?: number;
10 tenureMs?: number;
11 overlapMs?: number;
12 smoothingMs?: number;
13 owner?: string;
14 signal?: AbortSignal;
16export async function runSession(pool: Pool, options: SessionOptions = {}) {
17 const arrived = Date.now();
18 const budgetMs = options.budgetMs ?? 240000;
19 const tenureMs = options.tenureMs ?? 120000;
20 const overlapMs = options.overlapMs ?? 90000;
21 const smoothingMs = options.smoothingMs ?? 28000;
22 if (!Number.isInteger(smoothingMs) || smoothingMs < 0 || smoothingMs > 60000)
23 throw new Error("Invalid ingestion smoothing window (0–60000 ms)");
24 if (
25 ![budgetMs, tenureMs, overlapMs].every(Number.isFinite) ||
26 budgetMs < 60000 ||
27 budgetMs > 840000 ||
28 tenureMs < 30000 ||
29 tenureMs > budgetMs - 15000 ||
30 overlapMs < 10000 ||
31 overlapMs >= tenureMs
32 )
33 throw new Error("Invalid ingestion time budgets");
34 const owner = options.owner ?? randomUUID();
35 const controller = new AbortController();
36 const signal = options.signal
37 ? AbortSignal.any([controller.signal, options.signal])
38 : controller.signal;
39 const deadline = arrived + budgetMs;
40 const leases = new Leases(pool, owner, deadline, tenureMs, overlapMs);
41 const publisher = new SmoothingPublisher(pool, leases, smoothingMs);
42 const acquired = await leases.acquire();
43 if (acquired.role === "skip") return { role: "skip", owner };
44 let role = acquired.role;
45 let fencing = acquired.fencing;
46 let end = Math.min(arrived + tenureMs, deadline - 10000);
47 let stopped = false;
48 let transferred = false;
49 let publishedRevision = -1;
50 let renewing: Promise<void> | undefined;
51 let reconciliation: Promise<void> | undefined;
52 let watchRefresh: Promise<void> | undefined;
53 let watchesCheckedAt = 0;
54 let viewsPrunedAt = 0;
55 let standbyMarkedReady = false;
56 let waitingForHandoff = false;
57 const event = async (kind: string, details: Record<string, unknown> = {}) => {
58 await pool.query(
59 "INSERT INTO ingest_events(owner,kind,details) VALUES($1,$2,$3::jsonb)",
60 [owner, kind, JSON.stringify(details)],
61 );
62 console.log(
63 JSON.stringify({ owner, kind, at: new Date().toISOString(), ...details }),
64 );
65 };
66 const source = new HnSource(owner, signal);
67 const promote = async () => {
68 const promoted = await leases.promoteIfNeeded();
69 if (!promoted) return false;
70 role = "active";
71 fencing = promoted.fencing;
72 end = promoted.end;
73 publishedRevision = -1;
74 publisher.reset();
75 await event("promoted", {
76 deadline: new Date(deadline).toISOString(),
77 end: new Date(end).toISOString(),
78 });
79 await pool.query(
80 `UPDATE ingest_status SET handoff_ms=EXTRACT(epoch FROM (clock_timestamp()-handoff_at))*1000 WHERE id=1 AND handoff_at>clock_timestamp()-interval '30 seconds'`,
81 );
82 return true;
83 };
84 const renew = async () => {
85 try {
86 let valid = await leases.renew(role, fencing, source.prepared);
87 // Transfer can occur between the standby poll and its renewal.
88 if (!valid && role === "standby" && (await promote()))
89 valid = await leases.renew("active", fencing, source.prepared);
90 if (!valid) {
91 stopped = true;
92 controller.abort(new LostLease());
93 return;
94 }
95 if (role === "active") {
96 await pool.query(
97 `UPDATE ingest_status SET state=$1, checked_at=CASE WHEN $1='healthy' THEN clock_timestamp() ELSE checked_at END,
98 reconciled_at=$2, owner=$3 WHERE id=1 AND EXISTS(SELECT 1 FROM ingest_leases WHERE id=1 AND active_owner=$3 AND fencing=$4 AND active_until>clock_timestamp())`,
99 [
100 source.ready
101 ? "healthy"
102 : source.connected
103 ? "starting"
104 : "reconnecting",
105 source.snapshot.reconciledAt
106 ? new Date(source.snapshot.reconciledAt)
107 : null,
108 owner,
109 fencing,
110 ],
111 );
112 for (const thread of source.threads.values())
113 await pool.query(
114 `UPDATE hn_threads SET state=$2,checked_at=CASE WHEN $2='healthy' THEN clock_timestamp() ELSE checked_at END
115 WHERE story_id=$1 AND EXISTS(SELECT 1 FROM ingest_leases WHERE id=1 AND active_owner=$3 AND fencing=$4 AND active_until>clock_timestamp())`,
116 [
117 thread.id,
118 source.connected && thread.ready
119 ? "healthy"
120 : !source.connected
121 ? "reconnecting"
122 : thread.failed
123 ? "degraded"
124 : "starting",
125 owner,
126 fencing,
127 ],
128 );
129 }
130 } catch {
131 stopped = true;
132 controller.abort(new LostLease());
133 }
134 };
135 const heartbeat = setInterval(() => {
136 if (!renewing)
137 renewing = renew().finally(() => {
138 renewing = undefined;
139 });
140 }, 5000);
141 const timeout = setTimeout(() => {
142 stopped = true;
143 controller.abort();
144 }, budgetMs - 5000);
145 const shutdown = () => {
146 stopped = true;
147 controller.abort();
148 };
149 process.once("SIGINT", shutdown);
150 process.once("SIGTERM", shutdown);
151 const refreshWatches = async () => {
152 source.watchThreads(await watchedThreads(pool));
153 if (Date.now() - viewsPrunedAt > 60000) {
154 await pool.query(
155 "DELETE FROM hn_thread_views WHERE requested_at<clock_timestamp()-interval '5 minutes'",
156 );
157 viewsPrunedAt = Date.now();
158 }
159 };
160 try {
161 await event("started", {
162 role,
163 budgetMs,
164 tenureMs,
165 overlapMs,
166 smoothingMs,
167 });
168 await source.reconcile();
169 await refreshWatches();
170 await renew();
171 while (!stopped && !signal.aborted && Date.now() < deadline - 5000) {
172 if (Date.now() - watchesCheckedAt >= 1000 && !watchRefresh) {
173 watchesCheckedAt = Date.now();
174 watchRefresh = refreshWatches()
175 .catch(async () => {
176 await event("thread_watch_failed");
177 })
178 .finally(() => {
179 watchRefresh = undefined;
180 });
181 }
182 if (source.needsReconcile && !reconciliation) {
183 reconciliation = source
184 .reconcile()
185 .catch(async () => {
186 source.failed = true;
187 await event("source_failed");
188 })
189 .finally(() => {
190 reconciliation = undefined;
191 });
192 }
193 if (role === "standby") {
194 if (!source.prepared) standbyMarkedReady = false;
195 if (source.prepared) {
196 if (!standbyMarkedReady) {
197 await leases.renew("standby", fencing, true);
198 standbyMarkedReady = true;
199 }
200 await promote();
201 }
202 } else {
203 const snapshot =
204 source.ready && source.snapshot.revision !== publishedRevision
205 ? source.copy()
206 : undefined;
207 await publisher.tick(fencing, snapshot);
208 if (snapshot) publishedRevision = snapshot.revision;
209 if (Date.now() >= end) {
210 const next = await leases.handoff(fencing);
211 if (next) {
212 transferred = true;
213 await event("handoff", { to: next });
214 break;
215 }
216 // Scheduled delivery can arrive late. Continue publishing within the
217 // original request budget while waiting for a prepared successor.
218 if (!waitingForHandoff) {
219 waitingForHandoff = true;
220 await event("handoff_waiting");
221 }
222 }
223 }
224 await delay(250, undefined, { signal }).catch(() => {});
225 }
226 if (waitingForHandoff && !transferred) await event("handoff_unavailable");
227 return { role, owner, transferred, durationMs: Date.now() - arrived };
228 } catch (error) {
229 await event(error instanceof LostLease ? "lost_lease" : "session_failed");
230 throw error;
231 } finally {
232 clearInterval(heartbeat);
233 clearTimeout(timeout);
234 controller.abort();
235 process.removeListener("SIGINT", shutdown);
236 process.removeListener("SIGTERM", shutdown);
237 await source.close();
238 await reconciliation?.catch(() => {});
239 await renewing?.catch(() => {});
240 await watchRefresh?.catch(() => {});
241 await leases.release();
242 await pool.query(
243 `UPDATE ingest_status SET state='degraded', failure_at=clock_timestamp(), failure='Session ended without handoff'
244 WHERE id=1 AND owner=$1 AND NOT EXISTS(SELECT 1 FROM ingest_leases WHERE id=1 AND active_until>clock_timestamp())`,
245 [owner],
246 );
247 await event("finished", { transferred, durationMs: Date.now() - arrived });
248 }