Open History to see the last commit
1import { onValue, ref, type Database } from "@firebase/database";
2import {
3 selectComments,
4 orderedComments,
5 type ThreadSnapshot,
6} from "./comment-tree";
7export {
8 selectComments,
9 orderedComments,
10 type ThreadSnapshot,
11 type ThreadRow,
12} from "./comment-tree";
13import { readHn, mapLimit, type HnItem } from "./hn-api";
14
15const normalize = (id: number, item: HnItem | null): HnItem =>
16 item ? { ...item, id } : { id, deleted: true };
17
18export class HnThread {
19 private root?: HnItem;
20 private items = new Map<number, HnItem>();
21 private versions = new Map<number, number>();
22 private rootVersion = 0;
23 private revision = 0;
24 private listeners = new Map<number, () => void>();
25 private unsubscribe: () => void;
26 private closed = false;
27 private controller = new AbortController();
28 private signal: AbortSignal;
29 private reconciliation?: Promise<void>;
30 private reconciledAt = 0;
31 private receivedAt = 0;
32 private attemptedAt = 0;
33 failed = false;
34 constructor(
35 private db: Database,
36 readonly id: number,
37 signal: AbortSignal,
38 private changed: () => void,
39 ) {
40 this.signal = AbortSignal.any([signal, this.controller.signal]);
41 this.unsubscribe = onValue(
42 ref(db, `v0/item/${id}`),
43 (value) => {
44 if (this.closed) return;
45 this.root = normalize(id, value.val());
46 this.rootVersion = ++this.revision;
47 this.receivedAt = Date.now();
48 this.sync();
49 this.changed();
50 },
51 () => {
52 this.failed = true;
53 this.changed();
54 },
55 );
56 void this.reconcile().catch(() => {
57 this.failed = true;
58 this.changed();
59 });
60 }
61 get ready() {
62 return Boolean(
63 this.root &&
64 !this.failed &&
65 this.reconciledAt &&
66 selectComments(this.root, this.items).ids.every((id) =>
67 this.items.has(id),
68 ),
69 );
70 }
71 invalidate() {
72 this.reconciledAt = 0;
73 }
74 get needsReconcile() {
75 return (
76 !this.reconciliation &&
77 (Date.now() - this.reconciledAt >= 60000 || this.failed) &&
78 Date.now() - this.attemptedAt >= 5000
79 );
80 }
81 private sync() {
82 if (!this.root || this.closed) return;
83 const selected = new Set(selectComments(this.root, this.items).ids);
84 for (const [id, unsubscribe] of this.listeners)
85 if (!selected.has(id)) {
86 unsubscribe();
87 this.listeners.delete(id);
88 this.items.delete(id);
89 }
90 for (const id of selected)
91 if (!this.listeners.has(id)) {
92 this.listeners.set(id, () => {});
93 this.listeners.set(
94 id,
95 onValue(
96 ref(this.db, `v0/item/${id}`),
97 (value) => {
98 if (this.closed || !this.listeners.has(id)) return;
99 this.items.set(id, normalize(id, value.val()));
100 this.versions.set(id, ++this.revision);
101 this.receivedAt = Date.now();
102 this.sync();
103 this.changed();
104 },
105 () => {
106 this.failed = true;
107 this.changed();
108 },
109 ),
110 );
111 }
112 }
113 copy(): ThreadSnapshot | null {
114 if (!this.root || this.failed) return null;
115 return {
116 story: { ...this.root },
117 rows: orderedComments(this.root, this.items),
118 truncated: selectComments(this.root, this.items).truncated,
119 receivedAt: this.receivedAt,
120 complete: this.ready,
121 };
122 }
123 async reconcile() {
124 if (this.reconciliation) return this.reconciliation;
125 this.reconciliation = this.refresh().finally(() => {
126 this.reconciliation = undefined;
127 });
128 return this.reconciliation;
129 }
130 private async refresh() {
131 this.attemptedAt = Date.now();
132 const version = this.revision;
133 const root = normalize(
134 this.id,
135 await readHn<HnItem | null>(`item/${this.id}`, this.signal),
136 );
137 const refreshed = new Map<number, HnItem>();
138 let pending = selectComments(root, refreshed).ids;
139 while (pending.length) {
140 const pairs = await mapLimit(
141 pending,
142 20,
143 async (id) =>
144 [
145 id,
146 normalize(
147 id,
148 await readHn<HnItem | null>(`item/${id}`, this.signal),
149 ),
150 ] as const,
151 );
152 pairs.forEach(([id, item]) => refreshed.set(id, item));
153 pending = selectComments(root, refreshed).ids.filter(
154 (id) => !refreshed.has(id),
155 );
156 }
157 if (this.closed) return;
158 if (this.rootVersion <= version) this.root = root;
159 for (const [id, item] of refreshed)
160 if ((this.versions.get(id) ?? 0) <= version) this.items.set(id, item);
161 this.reconciledAt = Date.now();
162 this.receivedAt = Date.now();
163 this.failed = false;
164 this.sync();
165 this.changed();
166 }
167 async close() {
168 this.closed = true;
169 this.controller.abort();
170 this.unsubscribe();
171 this.listeners.forEach((unsubscribe) => unsubscribe());
172 await this.reconciliation?.catch(() => {});
173 }
174}