Open History to see the last commit
1import { createCollection } from "@tanstack/react-db";
2
3import { api } from "@/api/client";
4import { subscribeToLiveNotes } from "@/api/fake-realtime";
5
6import { inOrder, saveEach } from "./write-queue";
7import type { Note } from "./schema";
8
9/**
10 * SIMULATION, for the Neon Realtime deep dive. This is not
11 * `@neon/realtime-tanstack`: that package needs TanStack DB 0.9, and this app
12 * runs 1.0. It's a stand-in built from TanStack DB's own sync primitives, over
13 * a simulated stream from the fake API (`api/fake-realtime.ts`), that follows
14 * the same flow: the stream's rows are the collection's synced data, and a
15 * write waits for its transaction id to come through the stream.
16 *
17 * The Notes app doesn't use this collection.
18 */
19
20// #region sync-run
21interface TxidWaiter {
22 txid: bigint;
23 resolve: (seen: true) => void;
24 reject: (error: unknown) => void;
25 timer?: ReturnType<typeof setTimeout>;
26}
27
28/**
29 * One run of the collection's sync, from subscribing to cleanup: the
30 * transactions it has seen, and the writes that started during it. The
31 * stream delivers transactions in commit order, so "seen" is a single
32 * high-water mark: the last transaction id it delivered. Cleanup ends the
33 * run, and every write still in progress in it fails.
34 */
35export function createSyncRun() {
36 const controller = new AbortController();
37 const { signal } = controller;
38 let seenUpTo = -1n;
39 const waiters = new Set<TxidWaiter>();
40
41 function settle(waiter: TxidWaiter) {
42 clearTimeout(waiter.timer);
43 waiters.delete(waiter);
44 }
45
46 return {
47 /** Aborts requests made during the run when it ends. */
48 signal,
49
50 /** The stream has delivered everything up to and including `txid`. */
51 seen(txid: string) {
52 if (BigInt(txid) > seenUpTo) seenUpTo = BigInt(txid);
53 for (const waiter of waiters) {
54 if (waiter.txid > seenUpTo) continue;
55 settle(waiter);
56 waiter.resolve(true);
57 }
58 },
59
60 /** Resolves once `txid` has been delivered, even if it already was. */
61 wait(txid: string, timeout?: number): Promise<true> {
62 if (signal.aborted) return Promise.reject(signal.reason);
63 if (BigInt(txid) <= seenUpTo) return Promise.resolve(true);
64 return new Promise((resolve, reject) => {
65 const waiter: TxidWaiter = { txid: BigInt(txid), resolve, reject };
66 if (timeout !== undefined) {
67 waiter.timer = setTimeout(() => {
68 settle(waiter);
69 reject(new Error(`Timed out waiting for transaction ${txid}.`));
70 }, timeout);
71 }
72 waiters.add(waiter);
73 });
74 },
75
76 /**
77 * Starts `request` if the run is still going, and settles like it,
78 * unless the run ends first: then it fails.
79 */
80 during<T>(request: () => Promise<T>): Promise<T> {
81 if (signal.aborted) return Promise.reject(signal.reason);
82 return new Promise<T>((resolve, reject) => {
83 const onAbort = () => reject(signal.reason);
84 signal.addEventListener("abort", onAbort, { once: true });
85 request()
86 .then(resolve, reject)
87 .finally(() => signal.removeEventListener("abort", onAbort));
88 });
89 },
90
91 /** Ends the run: requests are aborted, and every write still waiting fails. */
92 close(reason: Error) {
93 controller.abort(reason);
94 for (const waiter of waiters) {
95 settle(waiter);
96 waiter.reject(reason);
97 }
98 },
99
100 get waiting(): number {
101 return waiters.size;
102 },
103 };
104}
105
106type SyncRun = ReturnType<typeof createSyncRun>;
107
108/** The current sync run; there's none before sync starts or after cleanup. */
109let activeRun: SyncRun | undefined;
110
111/**
112 * Like the package's `collection.utils.awaitTxId(txid, timeout?)`: resolves
113 * once the stream has delivered `txid`, also when it arrived before the
114 * API's answer did. Rejects on timeout and when the collection is cleaned up.
115 */
116function awaitTxId(txid: string, timeout?: number): Promise<true> {
117 if (!activeRun) return Promise.reject(new Error("The collection isn't syncing."));
118 return activeRun.wait(txid, timeout);
119}
120// #endregion sync-run
121
122// #region realtime-notes-collection
123export const realtimeNotesCollection = createCollection<
124 Note,
125 string,
126 { awaitTxId: typeof awaitTxId }
127>({
128 id: "notes-realtime-simulation",
129 getKey: (note) => note.id,
130 utils: { awaitTxId },
131 sync: {
132 // Each message carries whole rows.
133 rowUpdateMode: "full",
134 sync: ({ begin, write, commit, markReady }) => {
135 const run = createSyncRun();
136 activeRun = run;
137 const keys = new Set<string>();
138
139 const unsubscribe = subscribeToLiveNotes((message) => {
140 if (message.type === "rows") {
141 // The query's complete result: replaces whatever was there.
142 begin({ snapshot: true });
143 keys.clear();
144 for (const row of message.rows) {
145 keys.add(row.id);
146 write({ type: "insert", value: row });
147 }
148 void commit();
149 markReady();
150 } else {
151 // One committed database transaction: apply it as one sync transaction.
152 begin();
153 for (const change of message.changes) {
154 if (change.type === "delete") {
155 keys.delete(change.key);
156 write({ type: "delete", key: change.key });
157 } else {
158 write({ type: keys.has(change.row.id) ? "update" : "insert", value: change.row });
159 keys.add(change.row.id);
160 }
161 }
162 // Accepted now; it shows up together with the end of the optimistic
163 // state it confirms. So a write waiting for this txid can finish.
164 void commit();
165 }
166 run.seen(message.txid);
167 });
168
169 return () => {
170 unsubscribe();
171 run.close(new Error("The collection was cleaned up."));
172 if (activeRun === run) activeRun = undefined;
173 };
174 },
175 },
176 onUpdate: async ({ transaction }) => {
177 // A write belongs to the sync run it starts in, and fails if that run ends.
178 const run = activeRun;
179 if (!run) throw new Error("The collection isn't syncing.");
180 await saveEach(transaction.mutations, ({ key, changes }) =>
181 // One save at a time per note, so an older change can't land last.
182 inOrder(`/api/live/notes/${key}`, async () => {
183 // The API saves the change and answers with its transaction id…
184 const { txid } = await run.during(() =>
185 api.patch<{ txid: string }>(`/api/live/notes/${key}`, changes, { signal: run.signal }),
186 );
187 // …and the optimistic change stays on screen until the stream delivers it.
188 await run.wait(txid);
189 }),
190 );
191 },
192});
193// #endregion realtime-notes-collection