Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

offline-refresh.e2e.test.ts

319 lines9.6 KB

1/**
2 * Integration test: offline transactions + query collection refresh
3 *
4 * Verifies that a query-backed collection does not revert to stale server
5 * state when coming back online with pending offline transactions.
6 */
7​
8import { describe, expect, it, vi } from 'vitest'
9import { BTreeIndex, createCollection } from '@tanstack/db'
10import { QueryClient } from '@tanstack/query-core'
11import { startOfflineExecutor } from '@tanstack/offline-transactions'
12import { queryCollectionOptions } from '../src/query'
13import type { Collection } from '@tanstack/db'
14import type {
15 LeaderElection,
16 OfflineConfig,
17 OnlineDetector,
18 StorageAdapter,
19} from '@tanstack/offline-transactions'
20​
21// --- Browser API mocks needed by @tanstack/offline-transactions ---
22// jsdom doesn't provide navigator.locks, which the WebLocksLeader uses.
23// We pass custom implementations (FakeLeaderElection, ManualOnlineDetector,
24// FakeStorageAdapter) so these mocks just prevent initialization errors.
25​
26if (!(globalThis.navigator as any)?.locks) {
27 Object.defineProperty(globalThis.navigator, `locks`, {
28 value: { request: vi.fn().mockResolvedValue(false) },
29 configurable: true,
30 })
32​
33// --- Test helpers ---
34​
35const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0))
36​
37class ManualOnlineDetector implements OnlineDetector {
38 private listeners = new Set<() => void>()
39 private online: boolean
40​
41 constructor(initialOnline: boolean) {
42 this.online = initialOnline
43 }
44​
45 subscribe(callback: () => void): () => void {
46 this.listeners.add(callback)
47 return () => {
48 this.listeners.delete(callback)
49 }
50 }
51​
52 notifyOnline(): void {
53 for (const listener of this.listeners) {
54 listener()
55 }
56 }
57​
58 isOnline(): boolean {
59 return this.online
60 }
61​
62 setOnline(isOnline: boolean): void {
63 this.online = isOnline
64 if (isOnline) {
65 this.notifyOnline()
66 }
67 }
68​
69 dispose(): void {
70 this.listeners.clear()
71 }
73​
74class FakeStorageAdapter implements StorageAdapter {
75 private store = new Map<string, string>()
76​
77 get(key: string): Promise<string | null> {
78 return Promise.resolve(this.store.has(key) ? this.store.get(key)! : null)
79 }
80​
81 set(key: string, value: string): Promise<void> {
82 this.store.set(key, value)
83 return Promise.resolve()
84 }
85​
86 delete(key: string): Promise<void> {
87 this.store.delete(key)
88 return Promise.resolve()
89 }
90​
91 keys(): Promise<Array<string>> {
92 return Promise.resolve(Array.from(this.store.keys()))
93 }
94​
95 clear(): Promise<void> {
96 this.store.clear()
97 return Promise.resolve()
98 }
100​
101class FakeLeaderElection implements LeaderElection {
102 private listeners = new Set<(isLeader: boolean) => void>()
103 private leader = true
104​
105 requestLeadership(): Promise<boolean> {
106 this.notify(this.leader)
107 return Promise.resolve(this.leader)
108 }
109​
110 releaseLeadership(): void {
111 this.leader = false
112 this.notify(false)
113 }
114​
115 isLeader(): boolean {
116 return this.leader
117 }
118​
119 onLeadershipChange(callback: (isLeader: boolean) => void): () => void {
120 this.listeners.add(callback)
121 return () => {
122 this.listeners.delete(callback)
123 }
124 }
125​
126 private notify(isLeader: boolean): void {
127 for (const listener of this.listeners) {
128 listener(isLeader)
129 }
130 }
132​
133// --- Test item type ---
134​
135interface TestItem {
136 id: string
137 value: string
139​
140type OfflineMutationParams = Parameters<OfflineConfig[`mutationFns`][string]>[0]
141​
142// --- Tests ---
143​
144describe(`offline transactions + query collection refresh`, () => {
145 it(`should not revert optimistic state when query refetches before pending offline transactions complete`, async () => {
146 // This test verifies that when a user goes offline, queues a mutation,
147 // and comes back online, the collection does not temporarily lose the
148 // optimistic insert. In a query-backed collection, data flows through
149 // query refetches (queryFn), not directly from the mutation function.
150 // When refetchOnReconnect fires before the offline transaction reaches
151 // the server, the refetch returns stale data. The optimistic state
152 // should remain visible until the transaction completes and a fresh
153 // refetch confirms the data.
154​
155 const onlineDetector = new ManualOnlineDetector(false) // Start offline
156 const storage = new FakeStorageAdapter()
157​
158 // --- Mock server state ---
159 const serverItems: Array<TestItem> = [
160 { id: `item-1`, value: `server-data` },
161 ]
162​
163 // Control when the mutation fn resolves
164 let resolveMutation: (() => void) | null = null
165​
166 const queryClient = new QueryClient({
167 defaultOptions: {
168 queries: {
169 staleTime: 0,
170 retry: false,
171 },
172 },
173 })
174​
175 // queryFn reads from serverItems (simulating a real API GET endpoint)
176 const queryFn = vi.fn().mockImplementation(() => {
177 return Promise.resolve([...serverItems])
178 })
179​
180 // Create the query-backed collection
181 const collection = createCollection(
182 queryCollectionOptions({
183 id: `offline-refresh-test`,
184 queryClient,
185 queryKey: [`offline-refresh-test`],
186 queryFn,
187 getKey: (item: TestItem) => item.id,
188 startSync: true,
189 autoIndex: `eager`,
190 defaultIndexType: BTreeIndex,
191 }),
192 )
193​
194 // Wait for initial query to populate the collection
195 await vi.waitFor(() => {
196 expect(queryFn).toHaveBeenCalledTimes(1)
197 expect(collection.size).toBe(1)
198 })
199 expect(collection.get(`item-1`)?.value).toBe(`server-data`)
200​
201 // --- Set up offline executor ---
202 const mutationFnName = `syncData`
203 const offlineConfig: OfflineConfig = {
204 collections: { [`offline-refresh-test`]: collection as any },
205 mutationFns: {
206 [mutationFnName]: async (params: OfflineMutationParams) => {
207 // Block until the test explicitly resolves (simulating slow API POST)
208 await new Promise<void>((resolve) => {
209 resolveMutation = resolve
210 })
211​
212 // Update server state (simulating the server processing the mutation)
213 for (const mutation of params.transaction.mutations) {
214 if (mutation.type === `insert`) {
215 serverItems.push(mutation.modified as unknown as TestItem)
216 }
217 }
218​
219 return { ok: true }
220 },
221 },
222 storage,
223 leaderElection: new FakeLeaderElection(),
224 onlineDetector,
225 }
226​
227 const executor = startOfflineExecutor(offlineConfig)
228 await executor.waitForInit()
229​
230 // --- Go offline and create an offline mutation ---
231 const offlineTx = executor.createOfflineTransaction({
232 mutationFnName,
233 autoCommit: false,
234 })
235​
236 offlineTx.mutate(() => {
237 ;(collection as Collection<TestItem, string, any>).insert({
238 id: `item-2`,
239 value: `offline-insert`,
240 })
241 })
242​
243 // Commit while offline: persists to outbox, mutation fn NOT called yet
244 const commitPromise = offlineTx.commit()
245 await flushMicrotasks()
246​
247 // Verify: item-2 is visible through optimistic state
248 expect(collection.get(`item-2`)?.value).toBe(`offline-insert`)
249 expect(collection.get(`item-1`)?.value).toBe(`server-data`)
250​
251 // --- Come online ---
252 // This triggers both:
253 // 1. The offline executor replaying pending transactions (mutationFn called)
254 // 2. TanStack Query potentially refetching (refetchOnReconnect default)
255 onlineDetector.setOnline(true)
256 await vi.waitFor(() => {
257 expect(resolveMutation).not.toBeNull()
258 })
259​
260 const deferBarrier = collection.deferDataRefresh
261 expect(deferBarrier).not.toBeNull()
262 if (!deferBarrier) throw new Error(`Expected an active refresh barrier`)
263 let signalDeferredResult!: () => void
264 const deferredResultScheduled = new Promise<void>((resolve) => {
265 signalDeferredResult = resolve
266 })
267 const originalThen = deferBarrier.then.bind(deferBarrier)
268 deferBarrier.then = ((...args) => {
269 signalDeferredResult()
270 return originalThen(...args)
271 }) as typeof deferBarrier.then
272​
273 // Trigger a query refetch that returns stale server state.
274 // The server doesn't have item-2 yet (the mutation is still in progress).
275 // This simulates what refetchOnReconnect would do.
276 let refetchSettled = false
277 const refetchPromise = collection.utils.refetch().then((result) => {
278 refetchSettled = true
279 return result
280 })
281 await deferredResultScheduled
282 deferBarrier.then = originalThen
283​
284 // The query returned stale data (only item-1), but item-2 should still be
285 // visible because the offline transaction is still pending
286 // and the optimistic state should cover the gap. Its public promise must
287 // remain pending until the barrier-triggered refresh applies fresh data.
288 expect(refetchSettled).toBe(false)
289 expect(collection.get(`item-2`)?.value).toBe(`offline-insert`)
290​
291 // --- Complete the mutation (server processes it) ---
292 expect(resolveMutation).not.toBeNull()
293 resolveMutation!()
294​
295 // Wait for the transaction to fully complete
296 await commitPromise
297 await refetchPromise
298​
299 // After the transaction completes, item-2 should remain visible.
300 //
301 // Without the fix: the stale refetch overwrote syncedData with only
302 // item-1, the optimistic state was cleaned up, and item-2 is gone
303 // permanently (no fresh refetch is triggered).
304 //
305 // With the fix: the stale refetch was skipped (barrier), and a fresh
306 // refetch is triggered once the barrier resolves. The fresh refetch
307 // includes item-2 because the server now has it. We use waitFor to
308 // allow the barrier-triggered refetch to complete.
309 await vi.waitFor(
310 () => {
311 expect(collection.get(`item-2`)?.value).toBe(`offline-insert`)
312 },
313 { timeout: 1000 },
314 )
315​
316 executor.dispose()
317 queryClient.clear()
318 })
319})