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

navigation.test.ts

226 lines7.5 KB

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import { createHash } from "node:crypto";
4import type {
5 LiveQuerySnapshot,
6 RealtimeClient,
7 SealedLiveQuery,
8} from "@neon/realtime/client";
9import { LiveQueryCache } from "../lib/live-cache";
10import { liveRoute, NavigationIntent } from "../lib/live-route";
11​
12const query = (key: string): SealedLiveQuery<number> => ({
13 capability: `${Buffer.from(JSON.stringify({ alg: "dir", enc: "A256GCM", v: 1 })).toString("base64url")}..iv.ciphertext.tag`,
14 queryFingerprint: createHash("sha256").update(key).digest("hex"),
15 expiresAt: Date.now() + 60000,
16});
17function mockClient() {
18 const handles: {
19 emit: (snapshot: LiveQuerySnapshot<number>) => void;
20 closed: boolean;
21 renewals: SealedLiveQuery<number>[];
22 }[] = [];
23 const client = {
24 subscribe(_query: unknown, options: { initialData?: number[] }) {
25 let snapshot: LiveQuerySnapshot<number> = {
26 status: "stale",
27 error: undefined,
28 data: options.initialData,
29 };
30 const listeners = new Set<
31 (snapshot: LiveQuerySnapshot<number>) => void
32 >();
33 const handle = {
34 closed: false,
35 renewals: [] as SealedLiveQuery<number>[],
36 emit(next: LiveQuerySnapshot<number>) {
37 snapshot = next;
38 listeners.forEach((listener) => listener(snapshot));
39 },
40 };
41 handles.push(handle);
42 return {
43 getSnapshot: () => snapshot,
44 onChange(listener: (snapshot: LiveQuerySnapshot<number>) => void) {
45 listeners.add(listener);
46 return () => {
47 listeners.delete(listener);
48 };
49 },
50 renew: async (query: SealedLiveQuery<number>) => {
51 handle.renewals.push(query);
52 },
53 unsubscribe() {
54 handle.closed = true;
55 handle.emit({ ...snapshot, status: "closed", error: undefined });
56 listeners.clear();
57 },
58 };
59 },
60 close() {},
61 } as unknown as RealtimeClient;
62 return { client, handles };
64const live = (data: number[]): LiveQuerySnapshot<number> => ({
65 status: "live",
66 error: undefined,
67 data,
68});
69​
70test("route preparation waits for live reset and page mount reuses the handle and current rows", async () => {
71 const { client, handles } = mockClient();
72 const cache = new LiveQueryCache(client);
73 try {
74 const sealed = query("top");
75 const prepared = cache.get("feed:top:1", sealed, [1], async () => sealed);
76 let ready = false;
77 const pending = prepared.ready().then(() => {
78 ready = true;
79 });
80 await Promise.resolve();
81 assert.equal(
82 ready,
83 false,
84 "SSR fallback is not an authoritative live baseline",
85 );
86 assert.equal(prepared.getSnapshot().status, "connecting");
87 handles[0].emit(live([2]));
88 await pending;
89 const mounted = cache.get(
90 "feed:top:1",
91 { ...sealed, capability: "new capability" },
92 [0],
93 async () => sealed,
94 );
95 const unsubscribe = mounted.subscribe(() => {});
96 assert.equal(mounted, prepared);
97 assert.equal(handles.length, 1);
98 assert.deepEqual(mounted.getSnapshot().data, [2]);
99 handles[0].emit({ status: "stale", error: undefined, data: [2] });
100 assert.equal(
101 mounted.getSnapshot().status,
102 "stale",
103 "a real reconnect is visible after the baseline",
104 );
105 unsubscribe();
106 } finally {
107 cache.close();
108 }
109});
110​
111test("warm back navigation survives unmount, idle entries expire, active entries survive", async () => {
112 const { client, handles } = mockClient();
113 const cache = new LiveQueryCache(client, 35);
114 try {
115 const sealed = query("top");
116 const store = cache.get("top", sealed, [], async () => sealed);
117 const release = store.subscribe(() => {});
118 handles[0].emit(live([1]));
119 release();
120 assert.equal(cache.find("top"), store);
121 const releaseAgain = store.subscribe(() => {});
122 await new Promise((resolve) => setTimeout(resolve, 55));
123 assert.equal(handles[0].closed, false);
124 releaseAgain();
125 await new Promise((resolve) => setTimeout(resolve, 55));
126 assert.equal(handles[0].closed, true);
127 assert.equal(cache.find("top"), undefined);
128 } finally {
129 cache.close();
130 }
131});
132​
133test("idle cache is bounded without evicting an active page", () => {
134 const { client, handles } = mockClient();
135 const cache = new LiveQueryCache(client, 60000, 2);
136 try {
137 const q = query("active");
138 cache.get("active", q, [], async () => q).subscribe(() => {});
139 for (const key of ["one", "two", "three"]) {
140 const sealed = query(key);
141 cache.get(key, sealed, [], async () => sealed).start();
142 }
143 assert.equal(handles[0].closed, false);
144 assert.equal(handles[1].closed, true);
145 assert.equal(cache.find("one"), undefined);
146 assert.ok(cache.find("three"));
147 assert.throws(
148 () => cache.get("active", query("different"), [], async () => q),
149 /identity changed/,
150 );
151 } finally {
152 cache.close();
153 }
154});
155​
156test("failed or slow preparation settles so navigation can fall back to SSR", async () => {
157 const { client, handles } = mockClient();
158 const cache = new LiveQueryCache(client);
159 try {
160 const sealed = query("slow");
161 const slow = cache.get("slow", sealed, [], async () => sealed);
162 await assert.rejects(slow.ready(10), /timed out/);
163 const error = Object.assign(new Error("Offline"), {
164 code: "offline",
165 retryable: false,
166 });
167 const pending = slow.ready();
168 handles[0].emit({ status: "error", error, data: [] });
169 await assert.rejects(pending, /Offline/);
170 assert.equal(slow.getSnapshot().status, "error");
171 assert.equal(cache.find("slow"), undefined);
172 } finally {
173 cache.close();
174 }
175});
176​
177test("cached subscriptions renew capabilities and invalid renewal stays visibly failed", async () => {
178 const { client, handles } = mockClient();
179 const cache = new LiveQueryCache(client);
180 try {
181 const sealed = { ...query("renew"), expiresAt: Date.now() + 9990 };
182 const replacement = query("renew");
183 const store = cache.get("renew", sealed, [1], async () => replacement);
184 const release = store.subscribe(() => {});
185 handles[0].emit(live([2]));
186 await new Promise((resolve) => setTimeout(resolve, 20));
187 assert.deepEqual(handles[0].renewals, [replacement]);
188 assert.deepEqual(store.getSnapshot().data, [2]);
189 release();
190​
191 const invalid = { ...query("invalid"), expiresAt: Date.now() + 9990 };
192 const failed = cache.get("invalid", invalid, [1], async () =>
193 query("wrong identity"),
194 );
195 const pending = failed.ready();
196 await assert.rejects(pending, /Unable to renew/);
197 handles[1].emit(live([3]));
198 assert.equal(
199 failed.getSnapshot().status,
200 "error",
201 "a row update cannot hide a renewal failure",
202 );
203 assert.deepEqual(handles[1].renewals, []);
204 } finally {
205 cache.close();
206 }
207});
208​
209test("route identity ignores comment anchors and rapid navigation only commits the latest choice", () => {
210 assert.deepEqual(liveRoute("/?feed=new&page=2"), {
211 kind: "feed",
212 key: "feed:new:2",
213 api: "/api/feed/live?feed=new&page=2",
214 });
215 assert.equal(liveRoute("/item?id=123#comment-456")?.key, "thread:123");
216 assert.equal(liveRoute("https://news.ycombinator.com/item?id=123"), null);
217 assert.equal(liveRoute("//example.com"), null);
218 assert.throws(() => liveRoute("/item?id=-1"));
219 const intent = new NavigationIntent();
220 const first = intent.begin();
221 const second = intent.begin();
222 assert.equal(first(), false);
223 assert.equal(second(), true);
224 intent.cancel();
225 assert.equal(second(), false, "browser back cancels a pending click");
226});