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

live-cache.ts

210 lines6.1 KB

1import {
2 QueryRefreshController,
3 type LiveQueryError,
4 type LiveQuerySnapshot,
5 type MaterializedLiveQuerySubscription,
6 type RealtimeClient,
7 type SealedLiveQuery,
8} from "@neon/realtime/client";
9​
10export class LiveStore<Row> {
11 private subscription?: MaterializedLiveQuerySubscription<Row>;
12 private refresh?: QueryRefreshController<Row>;
13 private detach?: () => void;
14 private expiry?: ReturnType<typeof setTimeout>;
15 private listeners = new Set<() => void>();
16 private waiters = new Set<() => void>();
17 private snapshot: LiveQuerySnapshot<Row>;
18 private disposed = false;
19 private baseline = false;
20 private refreshError?: LiveQueryError;
21 lastUsed = Date.now();
22​
23 constructor(
24 private client: RealtimeClient,
25 readonly query: SealedLiveQuery<Row>,
26 initialData: readonly Row[] | undefined,
27 private refreshQuery: () => Promise<SealedLiveQuery<Row>>,
28 private idleMs: number,
29 private onIdle: () => void,
30 private onWarm: () => void,
31 ) {
32 this.snapshot = {
33 status: "connecting",
34 error: undefined,
35 data: initialData,
36 };
37 }
38​
39 get active() {
40 return this.listeners.size > 0;
41 }
42 get failed() {
43 return this.snapshot.status === "error" || this.disposed;
44 }
45 getSnapshot = () => this.snapshot;
46 subscribe = (listener: () => void) => {
47 this.listeners.add(listener);
48 this.start();
49 return () => {
50 this.listeners.delete(listener);
51 if (!this.active) this.keepWarm();
52 };
53 };
54​
55 start() {
56 if (this.disposed) throw new Error("Live query has been disposed");
57 this.lastUsed = Date.now();
58 clearTimeout(this.expiry);
59 if (!this.subscription) {
60 const subscription = this.client.subscribe(this.query, {
61 initialData: this.snapshot.data,
62 });
63 this.subscription = subscription;
64 this.publish(subscription.getSnapshot());
65 this.detach = subscription.onChange((snapshot) => this.publish(snapshot));
66 this.refresh = new QueryRefreshController({
67 query: this.query,
68 subscription,
69 refreshQuery: this.refreshQuery,
70 renewSubscription: (query) => subscription.renew(query),
71 onSubscriptionRenewed: () => {
72 this.refreshError = undefined;
73 this.publish(subscription.getSnapshot());
74 },
75 onRefreshExhausted: () => {
76 const error = Object.assign(
77 new Error("Unable to renew the live query"),
78 {
79 code: "QUERY_REFRESH_FAILED",
80 retryable: false,
81 },
82 ) satisfies LiveQueryError;
83 this.refreshError = error;
84 this.publish(subscription.getSnapshot());
85 },
86 });
87 this.refresh.start();
88 }
89 if (!this.active) this.keepWarm();
90 }
91​
92 // Initial rows are only a fallback. Navigation waits for the authoritative reset.
93 ready(timeout = 5000): Promise<void> {
94 this.start();
95 if (this.snapshot.status === "live") return Promise.resolve();
96 return new Promise((resolve, reject) => {
97 const check = () => {
98 const { status, error } = this.snapshot;
99 if (status !== "live" && status !== "error" && status !== "closed")
100 return;
101 clearTimeout(timer);
102 detach();
103 if (status === "live") resolve();
104 else reject(error ?? new Error("Live query closed"));
105 };
106 const detach = () => {
107 this.waiters.delete(check);
108 };
109 const timer = setTimeout(() => {
110 detach();
111 reject(new Error("Live query preparation timed out"));
112 }, timeout);
113 this.waiters.add(check);
114 check();
115 });
116 }
117​
118 dispose() {
119 this.disposed = true;
120 clearTimeout(this.expiry);
121 this.refresh?.stop();
122 this.detach?.();
123 this.subscription?.unsubscribe();
124 this.snapshot = { ...this.snapshot, status: "closed", error: undefined };
125 this.listeners.forEach((listener) => listener());
126 this.waiters.forEach((listener) => listener());
127 }
128​
129 private publish(snapshot: LiveQuerySnapshot<Row>) {
130 if (snapshot.status === "live") this.baseline = true;
131 this.snapshot =
132 snapshot.status === "stale" && !this.baseline
133 ? { ...snapshot, status: "connecting" }
134 : snapshot;
135 if (this.refreshError)
136 this.snapshot = {
137 ...this.snapshot,
138 status: "error",
139 error: this.refreshError,
140 };
141 this.listeners.forEach((listener) => listener());
142 this.waiters.forEach((listener) => listener());
143 }
144 private keepWarm() {
145 clearTimeout(this.expiry);
146 this.lastUsed = Date.now();
147 this.expiry = setTimeout(this.onIdle, this.idleMs);
148 this.onWarm();
149 }
151​
152// One cache per layout. Prepared and mounted queries consume the same SDK handle.
153export class LiveQueryCache {
154 private entries = new Map<string, LiveStore<unknown>>();
155 constructor(
156 private client: RealtimeClient,
157 private idleMs = 60000,
158 private maxIdle = 8,
159 ) {}
160​
161 find(key: string) {
162 const store = this.entries.get(key);
163 return store && !store.failed ? store : undefined;
164 }
165​
166 get<Row>(
167 key: string,
168 query: SealedLiveQuery<Row>,
169 initialData: readonly Row[] | undefined,
170 refreshQuery: () => Promise<SealedLiveQuery<Row>>,
171 ) {
172 const old = this.entries.get(key);
173 if (old && old.query.queryFingerprint !== query.queryFingerprint)
174 throw new Error("Live query cache identity changed");
175 if (old && !old.failed) return old as LiveStore<Row>;
176 old?.dispose();
177 const store = new LiveStore(
178 this.client,
179 query,
180 initialData,
181 refreshQuery,
182 this.idleMs,
183 () => {
184 if (!store.active) {
185 store.dispose();
186 this.entries.delete(key);
187 }
188 },
189 () => this.trim(key),
190 );
191 this.entries.set(key, store as LiveStore<unknown>);
192 this.trim(key);
193 return store;
194 }
195​
196 close() {
197 this.entries.forEach((store) => store.dispose());
198 this.entries.clear();
199 }
200 private trim(protectedKey: string) {
201 const idle = [...this.entries]
202 .filter(([key, store]) => key !== protectedKey && !store.active)
203 .sort((a, b) => a[1].lastUsed - b[1].lastUsed);
204 while (idle.length >= this.maxIdle) {
205 const [key, store] = idle.shift()!;
206 store.dispose();
207 this.entries.delete(key);
208 }
209 }