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

leader-failover.test.ts

508 lines14.4 KB

1import { describe, expect, it } from 'vitest'
2import { FakeStorageAdapter, createTestOfflineEnvironment } from './harness'
3import type { TestItem } from './harness'
4import type { PendingMutation } from '@tanstack/db'
5import type { LeaderElection } from '../src/types'
6​
7const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0))
8​
9const waitUntil = async (
10 predicate: () => boolean | Promise<boolean>,
11 timeoutMs = 5000,
12 intervalMs = 20,
13) => {
14 const deadline = Date.now() + timeoutMs
15 while (Date.now() < deadline) {
16 if (await predicate()) {
17 return
18 }
19 await new Promise((resolve) => setTimeout(resolve, intervalMs))
20 }
21 throw new Error(`Timed out waiting for condition`)
23​
24describe(`leader failover`, () => {
25 it(`transfers pending transactions from old leader to new leader`, async () => {
26 const sharedStorage = new FakeStorageAdapter()
27​
28 // Create executor A as leader
29 const envA = createTestOfflineEnvironment({
30 storage: sharedStorage,
31 mutationFn: () => {
32 throw new Error(`offline`)
33 },
34 })
35​
36 await envA.waitForLeader()
37 expect(envA.executor.isOfflineEnabled).toBe(true)
38​
39 // Create a transaction that will fail and persist to outbox
40 const txA = envA.executor.createOfflineTransaction({
41 mutationFnName: envA.mutationFnName,
42 autoCommit: false,
43 })
44​
45 txA.mutate(() => {
46 envA.collection.insert({
47 id: `failover-item`,
48 value: `transfer-me`,
49 completed: false,
50 updatedAt: new Date(),
51 })
52 })
53​
54 // Start commit - it will fail and persist to outbox
55 txA.commit()
56​
57 // Wait for transaction to be in outbox
58 await waitUntil(async () => {
59 const outbox = await envA.executor.peekOutbox()
60 return outbox.length === 1
61 })
62​
63 // Verify A has the transaction in outbox
64 const outboxA = await envA.executor.peekOutbox()
65 expect(outboxA).toHaveLength(1)
66 expect(outboxA[0].id).toBe(txA.id)
67​
68 // Now create executor B with same storage, starts as non-leader
69 const envB = createTestOfflineEnvironment({
70 storage: sharedStorage,
71 mutationFn: (params) => {
72 const mutations = params.transaction.mutations as Array<
73 PendingMutation<TestItem>
74 >
75 envB.applyMutations(mutations)
76 return { ok: true, mutations }
77 },
78 config: {
79 leaderElection: undefined, // Will use its own leader
80 },
81 })
82​
83 // Initially B is non-leader
84 envB.leader.setLeader(false)
85 await flushMicrotasks()
86 expect(envB.executor.isOfflineEnabled).toBe(false)
87​
88 // Switch leadership: A loses, B gains
89 envA.leader.setLeader(false)
90 envB.leader.setLeader(true)
91​
92 await flushMicrotasks()
93​
94 // Verify leadership states
95 expect(envA.executor.isOfflineEnabled).toBe(false)
96 expect(envB.executor.isOfflineEnabled).toBe(true)
97​
98 // Wait for B to execute the transaction
99 await waitUntil(() => envB.mutationCalls.length >= 1)
100​
101 // Verify B executed the transaction
102 expect(envB.mutationCalls).toHaveLength(1)
103 expect(envB.serverState.get(`failover-item`)?.value).toBe(`transfer-me`)
104​
105 // Verify outbox is now empty (transaction completed)
106 await waitUntil(async () => {
107 const outbox = await envB.executor.peekOutbox()
108 return outbox.length === 0
109 })
110​
111 envA.executor.dispose()
112 envB.executor.dispose()
113 })
114​
115 it(`non-leader remains passive until it becomes leader`, async () => {
116 const sharedStorage = new FakeStorageAdapter()
117​
118 // Create executor A as leader with a failing mutation
119 const envA = createTestOfflineEnvironment({
120 storage: sharedStorage,
121 mutationFn: () => {
122 throw new Error(`offline`)
123 },
124 })
125​
126 await envA.waitForLeader()
127​
128 // Create executor B as non-leader with working mutation
129 const envB = createTestOfflineEnvironment({
130 storage: sharedStorage,
131 mutationFn: (params) => {
132 const mutations = params.transaction.mutations as Array<
133 PendingMutation<TestItem>
134 >
135 envB.applyMutations(mutations)
136 return { ok: true, mutations }
137 },
138 })
139​
140 envB.leader.setLeader(false)
141 await flushMicrotasks()
142​
143 // A creates a transaction that goes to outbox
144 const txA = envA.executor.createOfflineTransaction({
145 mutationFnName: envA.mutationFnName,
146 autoCommit: false,
147 })
148​
149 txA.mutate(() => {
150 envA.collection.insert({
151 id: `passive-test`,
152 value: `waiting`,
153 completed: false,
154 updatedAt: new Date(),
155 })
156 })
157​
158 txA.commit()
159​
160 await waitUntil(async () => {
161 const outbox = await envA.executor.peekOutbox()
162 return outbox.length === 1
163 })
164​
165 // B should not execute while non-leader
166 await flushMicrotasks()
167 await new Promise((resolve) => setTimeout(resolve, 100))
168 expect(envB.mutationCalls).toHaveLength(0)
169​
170 // Now make B the leader
171 envA.leader.setLeader(false)
172 envB.leader.setLeader(true)
173 await flushMicrotasks()
174​
175 // B should now execute the transaction
176 await waitUntil(() => envB.mutationCalls.length >= 1)
177 expect(envB.mutationCalls).toHaveLength(1)
178 expect(envB.serverState.get(`passive-test`)?.value).toBe(`waiting`)
179​
180 envA.executor.dispose()
181 envB.executor.dispose()
182 })
183​
184 it(`transaction survives multiple leadership transitions`, async () => {
185 const sharedStorage = new FakeStorageAdapter()
186​
187 // Create executor A (will fail)
188 const envA = createTestOfflineEnvironment({
189 storage: sharedStorage,
190 mutationFn: () => {
191 throw new Error(`A fails`)
192 },
193 })
194​
195 await envA.waitForLeader()
196​
197 // Create transaction from A
198 const txA = envA.executor.createOfflineTransaction({
199 mutationFnName: envA.mutationFnName,
200 autoCommit: false,
201 })
202​
203 txA.mutate(() => {
204 envA.collection.insert({
205 id: `survivor`,
206 value: `resilient`,
207 completed: false,
208 updatedAt: new Date(),
209 })
210 })
211​
212 txA.commit()
213​
214 await waitUntil(async () => {
215 const outbox = await envA.executor.peekOutbox()
216 return outbox.length === 1
217 })
218​
219 // Create executor B (will also fail)
220 const envB = createTestOfflineEnvironment({
221 storage: sharedStorage,
222 mutationFn: () => {
223 throw new Error(`B fails`)
224 },
225 })
226​
227 envB.leader.setLeader(false)
228​
229 // Create executor C (will succeed)
230 const envC = createTestOfflineEnvironment({
231 storage: sharedStorage,
232 mutationFn: (params) => {
233 const mutations = params.transaction.mutations as Array<
234 PendingMutation<TestItem>
235 >
236 envC.applyMutations(mutations)
237 return { ok: true, mutations }
238 },
239 })
240​
241 envC.leader.setLeader(false)
242​
243 // Transfer to B
244 envA.leader.setLeader(false)
245 envB.leader.setLeader(true)
246 await flushMicrotasks()
247​
248 // Wait for B to attempt and fail
249 await waitUntil(() => envB.mutationCalls.length >= 1)
250 expect(envB.mutationCalls).toHaveLength(1)
251​
252 // Transaction should still be in outbox
253 const outboxB = await envB.executor.peekOutbox()
254 expect(outboxB).toHaveLength(1)
255​
256 // Transfer to C
257 envB.leader.setLeader(false)
258 envC.leader.setLeader(true)
259 await flushMicrotasks()
260​
261 // Wait for C to execute successfully
262 await waitUntil(() => envC.mutationCalls.length >= 1)
263 expect(envC.mutationCalls).toHaveLength(1)
264 expect(envC.serverState.get(`survivor`)?.value).toBe(`resilient`)
265​
266 // Outbox should now be empty
267 await waitUntil(async () => {
268 const outbox = await envC.executor.peekOutbox()
269 return outbox.length === 0
270 })
271​
272 envA.executor.dispose()
273 envB.executor.dispose()
274 envC.executor.dispose()
275 })
276​
277 it(`new transactions from non-leader go online-only`, async () => {
278 const sharedStorage = new FakeStorageAdapter()
279​
280 const envA = createTestOfflineEnvironment({
281 storage: sharedStorage,
282 })
283​
284 await envA.waitForLeader()
285​
286 const envB = createTestOfflineEnvironment({
287 storage: sharedStorage,
288 })
289​
290 envB.leader.setLeader(false)
291 await flushMicrotasks()
292​
293 // Create transaction from non-leader B
294 const txB = envB.executor.createOfflineTransaction({
295 mutationFnName: envB.mutationFnName,
296 autoCommit: false,
297 })
298​
299 txB.mutate(() => {
300 envB.collection.insert({
301 id: `online-only`,
302 value: `no-outbox`,
303 completed: false,
304 updatedAt: new Date(),
305 })
306 })
307​
308 await txB.commit()
309​
310 // Should have executed immediately without outbox
311 expect(envB.mutationCalls).toHaveLength(1)
312​
313 // Should NOT be in outbox
314 const outbox = await envB.executor.peekOutbox()
315 expect(outbox).toHaveLength(0)
316​
317 // Now create transaction from leader A
318 const txA = envA.executor.createOfflineTransaction({
319 mutationFnName: envA.mutationFnName,
320 autoCommit: false,
321 })
322​
323 txA.mutate(() => {
324 envA.collection.insert({
325 id: `outbox-item`,
326 value: `in-outbox`,
327 completed: false,
328 updatedAt: new Date(),
329 })
330 })
331​
332 await txA.commit()
333​
334 // A's transaction should have gone through outbox
335 expect(envA.mutationCalls.length).toBeGreaterThanOrEqual(1)
336​
337 envA.executor.dispose()
338 envB.executor.dispose()
339 })
340​
341 it(`calls onLeadershipChange callback on both gain and loss`, async () => {
342 const sharedStorage = new FakeStorageAdapter()
343 const callbackCalls: Array<{ executor: string; isLeader: boolean }> = []
344​
345 const envA = createTestOfflineEnvironment({
346 storage: sharedStorage,
347 config: {
348 onLeadershipChange: (isLeader) => {
349 callbackCalls.push({ executor: `A`, isLeader })
350 },
351 },
352 })
353​
354 await envA.waitForLeader()
355​
356 // A should have been called with true
357 expect(callbackCalls).toContainEqual({ executor: `A`, isLeader: true })
358​
359 const envB = createTestOfflineEnvironment({
360 storage: sharedStorage,
361 config: {
362 onLeadershipChange: (isLeader) => {
363 callbackCalls.push({ executor: `B`, isLeader })
364 },
365 },
366 })
367​
368 envB.leader.setLeader(false)
369 await flushMicrotasks()
370​
371 // B should have been called with false
372 expect(callbackCalls).toContainEqual({ executor: `B`, isLeader: false })
373​
374 const beforeLength = callbackCalls.length
375​
376 // Transfer leadership
377 envA.leader.setLeader(false)
378 await flushMicrotasks()
379 envB.leader.setLeader(true)
380 await flushMicrotasks()
381​
382 // Both should have been called
383 const newCalls = callbackCalls.slice(beforeLength)
384 expect(newCalls).toContainEqual({ executor: `A`, isLeader: false })
385 expect(newCalls).toContainEqual({ executor: `B`, isLeader: true })
386​
387 envA.executor.dispose()
388 envB.executor.dispose()
389 })
390​
391 it(`calls onLeadershipChange exactly once during initialization`, async () => {
392 const callbackCalls: Array<boolean> = []
393​
394 const env = createTestOfflineEnvironment({
395 config: {
396 onLeadershipChange: (isLeader) => {
397 callbackCalls.push(isLeader)
398 },
399 },
400 })
401​
402 await env.waitForLeader()
403​
404 // Should be called exactly once with true during initialization
405 expect(callbackCalls).toEqual([true])
406​
407 // Wait a bit to ensure no duplicate calls
408 await new Promise((resolve) => setTimeout(resolve, 50))
409​
410 // Still should only have one call
411 expect(callbackCalls).toEqual([true])
412​
413 env.executor.dispose()
414 })
415​
416 it(`does not double-replay transactions when leadership callback fires after requestLeadership returns`, async () => {
417 // This test simulates the race condition in WebLocksLeader where:
418 // 1. requestLeadership() returns true immediately when lock is available
419 // 2. But notifyLeadershipChange(true) is called asynchronously when lock is actually acquired
420 // 3. This used to cause loadAndReplayTransactions() to be called twice
421 //
422 // The fix is to set isLeaderState = true synchronously in requestLeadership()
423 // so the async notifyLeadershipChange(true) doesn't trigger listeners again
424​
425 const sharedStorage = new FakeStorageAdapter()
426​
427 // Create a leader election that simulates the race condition:
428 // requestLeadership() returns true immediately but the callback fires later
429 class AsyncLeaderElection implements LeaderElection {
430 private listeners = new Set<(isLeader: boolean) => void>()
431 private leader = false
432​
433 requestLeadership(): Promise<boolean> {
434 // Simulate: lock is available, will return true immediately
435 // but the actual lock acquisition (and callback) happens async
436 setTimeout(() => {
437 // This simulates the fire-and-forget navigator.locks.request() completing
438 this.leader = true
439 for (const listener of this.listeners) {
440 listener(true)
441 }
442 }, 10)
443​
444 return Promise.resolve(true) // Returns immediately before callback fires
445 }
446​
447 releaseLeadership(): void {
448 this.leader = false
449 for (const listener of this.listeners) {
450 listener(false)
451 }
452 }
453​
454 isLeader(): boolean {
455 return this.leader
456 }
457​
458 onLeadershipChange(callback: (isLeader: boolean) => void): () => void {
459 this.listeners.add(callback)
460 return () => {
461 this.listeners.delete(callback)
462 }
463 }
464 }
465​
466 // Pre-populate storage with a pending transaction
467 const transactionId = `test-tx-${Date.now()}`
468 const transaction = {
469 id: transactionId,
470 mutationFnName: `syncData`,
471 idempotencyKey: `test-idempotency-key`,
472 payload: {},
473 createdAt: Date.now(),
474 }
475 await sharedStorage.set(
476 `offline-executor:transaction:${transactionId}`,
477 JSON.stringify(transaction),
478 )
479​
480 let replayCount = 0
481 const env = createTestOfflineEnvironment({
482 storage: sharedStorage,
483 mutationFn: (params) => {
484 replayCount++
485 const mutations = params.transaction.mutations as Array<
486 PendingMutation<TestItem>
487 >
488 env.applyMutations(mutations)
489 return Promise.resolve({ ok: true, mutations })
490 },
491 config: {
492 leaderElection: new AsyncLeaderElection(),
493 },
494 })
495​
496 // Wait for potential double-replay to occur
497 // If the bug exists, the callback would fire ~10ms after initialization
498 // and cause a second replay
499 await new Promise((resolve) => setTimeout(resolve, 100))
500​
501 // The mutation should only be called once, not twice
502 // Note: In this specific test, the pre-populated transaction might not
503 // match the expected schema, so we check the replay count didn't double
504 expect(replayCount).toBeLessThanOrEqual(1)
505​
506 env.executor.dispose()
507 })
508})