Open History to see the last commit
1import { initializeApp, deleteApp, type FirebaseApp } from "@firebase/app";
2import {
3 getDatabase,
4 onValue,
5 ref,
6 goOffline,
7 type Database,
8} from "@firebase/database";
9import { FEED_SIZE, type Feed } from "../lib/types";
10import { HnThread, type ThreadSnapshot } from "./threads";
11import { readHn, mapLimit, type HnItem } from "./hn-api";
12export { readHn, mapLimit, type HnItem } from "./hn-api";
13export interface SourceSnapshot {
14 feeds: Record<Feed, number[]>;
15 items: Map<number, HnItem>;
16 revision: number;
17 receivedAt: number;
18 reconciledAt: number;
19 itemReceipts?: Map<number, number>;
20 feedReceipts?: Record<Feed, number>;
21 threads?: ThreadSnapshot[];
22}
23const normalizeItem = (id: number, item: HnItem | null): HnItem =>
24 item ? { ...item, id } : { id, deleted: true };
25
26export class HnSource {
27 private app: FirebaseApp;
28 private db: Database;
29 private listeners = new Map<number, () => void>();
30 private initialized = new Set<number>();
31 private unsubscribers: (() => void)[] = [];
32 private closed = false;
33 private reconnectEpoch = 0;
34 private reconciledEpoch = -1;
35 private reconciliation?: Promise<void>;
36 private itemVersions = new Map<number, number>();
37 private feedVersions: Record<Feed, number> = { top: 0, new: 0 };
38 readonly threads = new Map<number, HnThread>();
39 private closingThreads: Promise<void>[] = [];
40 connected = false;
41 failed = false;
42 snapshot: SourceSnapshot = {
43 feeds: { top: [], new: [] },
44 items: new Map(),
45 revision: 0,
46 receivedAt: 0,
47 reconciledAt: 0,
48 itemReceipts: new Map(),
49 feedReceipts: { top: 0, new: 0 },
50 };
51 constructor(
52 owner: string,
53 private signal: AbortSignal,
54 ) {
55 this.app = initializeApp(
56 { databaseURL: "https://hacker-news.firebaseio.com" },
57 owner,
58 );
59 this.db = getDatabase(this.app);
60 const fail = () => {
61 this.failed = true;
62 this.connected = false;
63 };
64 this.unsubscribers.push(
65 onValue(
66 ref(this.db, ".info/connected"),
67 (value) => {
68 const wasConnected = this.connected;
69 this.connected = value.val() === true;
70 if (this.connected && !wasConnected) {
71 this.reconnectEpoch++;
72 this.failed = false;
73 this.threads.forEach((thread) => thread.invalidate());
74 }
75 },
76 fail,
77 ),
78 );
79 for (const feed of ["top", "new"] as const) {
80 this.unsubscribers.push(
81 onValue(
82 ref(this.db, `v0/${feed}stories`),
83 (value) => {
84 if (!Array.isArray(value.val())) {
85 fail();
86 return;
87 }
88 this.snapshot.feeds[feed] = value.val().slice(0, FEED_SIZE);
89 this.markChanged();
90 this.feedVersions[feed] = this.snapshot.revision;
91 this.snapshot.feedReceipts![feed] = Date.now();
92 this.syncListeners();
93 },
94 fail,
95 ),
96 );
97 }
98 }
99 private markChanged() {
100 this.snapshot.revision++;
101 this.snapshot.receivedAt = Date.now();
102 }
103 private syncListeners() {
104 const tracked = new Set([
105 ...this.snapshot.feeds.top,
106 ...this.snapshot.feeds.new,
107 ]);
108 for (const [id, unsubscribe] of this.listeners) {
109 if (!tracked.has(id)) {
110 unsubscribe();
111 this.listeners.delete(id);
112 this.initialized.delete(id);
113 this.snapshot.items.delete(id);
114 }
115 }
116 for (const id of tracked) {
117 if (this.listeners.has(id)) continue;
118 this.listeners.set(
119 id,
120 onValue(
121 ref(this.db, `v0/item/${id}`),
122 (value) => {
123 this.snapshot.items.set(id, normalizeItem(id, value.val()));
124 this.initialized.add(id);
125 this.markChanged();
126 this.itemVersions.set(id, this.snapshot.revision);
127 this.snapshot.itemReceipts!.set(id, Date.now());
128 },
129 () => {
130 this.failed = true;
131 },
132 ),
133 );
134 }
135 }
136 get ready() {
137 const ids = [...this.snapshot.feeds.top, ...this.snapshot.feeds.new];
138 return (
139 this.connected &&
140 !this.failed &&
141 ids.length > 0 &&
142 this.snapshot.reconciledAt > 0 &&
143 ids.every((id) => this.initialized.has(id))
144 );
145 }
146 get needsReconcile() {
147 return (
148 this.reconciledEpoch !== this.reconnectEpoch ||
149 Date.now() - this.snapshot.reconciledAt >= 60000
150 );
151 }
152 get prepared() {
153 // Cold discussions must not delay handoff of the shared feed. Partial
154 // thread snapshots only insert missing rows until reconciliation completes.
155 return this.ready;
156 }
157 watchThreads(ids: number[]) {
158 if (this.closed) return;
159 const wanted = new Set(ids);
160 for (const [id, thread] of this.threads)
161 if (!wanted.has(id)) {
162 this.closingThreads.push(thread.close());
163 this.threads.delete(id);
164 }
165 for (const id of wanted)
166 if (!this.threads.has(id))
167 this.threads.set(
168 id,
169 new HnThread(this.db, id, this.signal, () => this.markChanged()),
170 );
171 for (const thread of this.threads.values())
172 if (thread.needsReconcile)
173 void thread.reconcile().catch(() => {
174 thread.failed = true;
175 });
176 }
177 async reconcile() {
178 if (this.reconciliation) return this.reconciliation;
179 this.reconciliation = this.refresh().finally(() => {
180 this.reconciliation = undefined;
181 });
182 return this.reconciliation;
183 }
184 private async refresh() {
185 const revision = this.snapshot.revision;
186 const epoch = this.reconnectEpoch;
187 const [top, fresh] = await Promise.all([
188 readHn<number[]>("topstories", this.signal),
189 readHn<number[]>("newstories", this.signal),
190 ]);
191 const feeds = {
192 top: top.slice(0, FEED_SIZE),
193 new: fresh.slice(0, FEED_SIZE),
194 };
195 const ids = [...new Set([...feeds.top, ...feeds.new])];
196 const pairs = await mapLimit(
197 ids,
198 20,
199 async (id) =>
200 [
201 id,
202 normalizeItem(
203 id,
204 await readHn<HnItem | null>(`item/${id}`, this.signal),
205 ),
206 ] as const,
207 );
208 if (this.closed) return;
209 // Preserve newer subscriptions independently for each node. Activity on one
210 // item must not prevent authoritative recovery of a different missed item.
211 for (const feed of ["top", "new"] as const) {
212 if (this.feedVersions[feed] <= revision) {
213 if (
214 JSON.stringify(this.snapshot.feeds[feed]) !==
215 JSON.stringify(feeds[feed])
216 ) {
217 this.snapshot.feeds[feed] = feeds[feed];
218 this.snapshot.feedReceipts![feed] = Date.now();
219 this.markChanged();
220 }
221 }
222 }
223 for (const [id, item] of pairs) {
224 if (
225 (this.itemVersions.get(id) ?? 0) <= revision &&
226 JSON.stringify(this.snapshot.items.get(id)) !== JSON.stringify(item)
227 ) {
228 this.snapshot.items.set(id, item);
229 this.snapshot.itemReceipts!.set(id, Date.now());
230 this.markChanged();
231 }
232 }
233 this.snapshot.reconciledAt = Date.now();
234 this.reconciledEpoch = epoch;
235 this.failed = false;
236 this.syncListeners();
237 await Promise.all(
238 [...this.threads.values()].map((thread) =>
239 thread.reconcile().catch(() => {
240 thread.failed = true;
241 }),
242 ),
243 );
244 }
245 copy(): SourceSnapshot {
246 return {
247 ...this.snapshot,
248 feeds: {
249 top: [...this.snapshot.feeds.top],
250 new: [...this.snapshot.feeds.new],
251 },
252 items: new Map(this.snapshot.items),
253 itemReceipts: new Map(this.snapshot.itemReceipts),
254 feedReceipts: { ...this.snapshot.feedReceipts! },
255 threads: [...this.threads.values()]
256 .map((thread) => thread.copy())
257 .filter((thread): thread is ThreadSnapshot => thread !== null),
258 };
259 }
260 async close() {
261 this.closed = true;
262 this.unsubscribers.forEach((stop) => stop());
263 this.listeners.forEach((stop) => stop());
264 await Promise.all([
265 ...this.closingThreads,
266 ...[...this.threads.values()].map((thread) => thread.close()),
267 ]);
268 goOffline(this.db);
269 await deleteApp(this.app);
270 }
271}