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

leader-failover.test.ts

406 lines10.9 KB

1import { describe, expect, it } from 'vitest'
2import { FakeStorageAdapter, createTestOfflineEnvironment } from './harness'
3​
4const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0))
5​
6const waitUntil = async (
7 predicate: () => boolean | Promise<boolean>,
8 timeoutMs = 5000,
9 intervalMs = 20,
10) => {
11 const deadline = Date.now() + timeoutMs
12 while (Date.now() < deadline) {
13 if (await predicate()) {
14 return
15 }
16 await new Promise((resolve) => setTimeout(resolve, intervalMs))
17 }
18 throw new Error(`Timed out waiting for condition`)
20​
21describe(`leader failover`, () => {
22 it(`transfers pending transactions from old leader to new leader`, async () => {
23 const sharedStorage = new FakeStorageAdapter()
24​
25 // Create executor A as leader
26 const envA = createTestOfflineEnvironment({
27 storage: sharedStorage,
28 mutationFn: () => {
29 throw new Error(`offline`)
30 },
31 })
32​
33 await envA.waitForLeader()
34 expect(envA.executor.isOfflineEnabled).toBe(true)
35​
36 // Create a transaction that will fail and persist to outbox
37 const txA = envA.executor.createOfflineTransaction({
38 mutationFnName: envA.mutationFnName,
39 autoCommit: false,
40 })
41​
42 txA.mutate(() => {
43 envA.collection.insert({
44 id: `failover-item`,
45 value: `transfer-me`,
46 completed: false,
47 updatedAt: new Date(),
48 })
49 })
50​
51 // Start commit - it will fail and persist to outbox
52 txA.commit()
53​
54 // Wait for transaction to be in outbox
55 await waitUntil(async () => {
56 const outbox = await envA.executor.peekOutbox()
57 return outbox.length === 1
58 })
59​
60 // Verify A has the transaction in outbox
61 const outboxA = await envA.executor.peekOutbox()
62 expect(outboxA).toHaveLength(1)
63 expect(outboxA[0]!.id).toBe(txA.id)
64​
65 // Now create executor B with same storage, starts as non-leader
66 const envB = createTestOfflineEnvironment({
67 storage: sharedStorage,
68 mutationFn: (params) => {
69 const mutations = params.transaction.mutations
70 envB.applyMutations(mutations)
71 return { ok: true, mutations }
72 },
73 config: {
74 leaderElection: undefined, // Will use its own leader
75 },
76 })
77​
78 // Initially B is non-leader
79 envB.leader.setLeader(false)
80 await flushMicrotasks()
81 expect(envB.executor.isOfflineEnabled).toBe(false)
82​
83 // Switch leadership: A loses, B gains
84 envA.leader.setLeader(false)
85 envB.leader.setLeader(true)
86​
87 await flushMicrotasks()
88​
89 // Verify leadership states
90 expect(envA.executor.isOfflineEnabled).toBe(false)
91 expect(envB.executor.isOfflineEnabled).toBe(true)
92​
93 // Wait for B to execute the transaction
94 await waitUntil(() => envB.mutationCalls.length >= 1)
95​
96 // Verify B executed the transaction
97 expect(envB.mutationCalls).toHaveLength(1)
98 expect(envB.serverState.get(`failover-item`)?.value).toBe(`transfer-me`)
99​
100 // Verify outbox is now empty (transaction completed)
101 await waitUntil(async () => {
102 const outbox = await envB.executor.peekOutbox()
103 return outbox.length === 0
104 })
105​
106 envA.executor.dispose()
107 envB.executor.dispose()
108 })
109​
110 it(`non-leader remains passive until it becomes leader`, async () => {
111 const sharedStorage = new FakeStorageAdapter()
112​
113 // Create executor A as leader with a failing mutation
114 const envA = createTestOfflineEnvironment({
115 storage: sharedStorage,
116 mutationFn: () => {
117 throw new Error(`offline`)
118 },
119 })
120​
121 await envA.waitForLeader()
122​
123 // Create executor B as non-leader with working mutation
124 const envB = createTestOfflineEnvironment({
125 storage: sharedStorage,
126 mutationFn: (params) => {
127 const mutations = params.transaction.mutations
128 envB.applyMutations(mutations)
129 return { ok: true, mutations }
130 },
131 })
132​
133 envB.leader.setLeader(false)
134 await flushMicrotasks()
135​
136 // A creates a transaction that goes to outbox
137 const txA = envA.executor.createOfflineTransaction({
138 mutationFnName: envA.mutationFnName,
139 autoCommit: false,
140 })
141​
142 txA.mutate(() => {
143 envA.collection.insert({
144 id: `passive-test`,
145 value: `waiting`,
146 completed: false,
147 updatedAt: new Date(),
148 })
149 })
150​
151 txA.commit()
152​
153 await waitUntil(async () => {
154 const outbox = await envA.executor.peekOutbox()
155 return outbox.length === 1
156 })
157​
158 // B should not execute while non-leader
159 await flushMicrotasks()
160 await new Promise((resolve) => setTimeout(resolve, 100))
161 expect(envB.mutationCalls).toHaveLength(0)
162​
163 // Now make B the leader
164 envA.leader.setLeader(false)
165 envB.leader.setLeader(true)
166 await flushMicrotasks()
167​
168 // B should now execute the transaction
169 await waitUntil(() => envB.mutationCalls.length >= 1)
170 expect(envB.mutationCalls).toHaveLength(1)
171 expect(envB.serverState.get(`passive-test`)?.value).toBe(`waiting`)
172​
173 envA.executor.dispose()
174 envB.executor.dispose()
175 })
176​
177 it(`transaction survives multiple leadership transitions`, async () => {
178 const sharedStorage = new FakeStorageAdapter()
179​
180 // Create executor A (will fail)
181 const envA = createTestOfflineEnvironment({
182 storage: sharedStorage,
183 mutationFn: () => {
184 throw new Error(`A fails`)
185 },
186 })
187​
188 await envA.waitForLeader()
189​
190 // Create transaction from A
191 const txA = envA.executor.createOfflineTransaction({
192 mutationFnName: envA.mutationFnName,
193 autoCommit: false,
194 })
195​
196 txA.mutate(() => {
197 envA.collection.insert({
198 id: `survivor`,
199 value: `resilient`,
200 completed: false,
201 updatedAt: new Date(),
202 })
203 })
204​
205 txA.commit()
206​
207 await waitUntil(async () => {
208 const outbox = await envA.executor.peekOutbox()
209 return outbox.length === 1
210 })
211​
212 // Create executor B (will also fail)
213 const envB = createTestOfflineEnvironment({
214 storage: sharedStorage,
215 mutationFn: () => {
216 throw new Error(`B fails`)
217 },
218 })
219​
220 envB.leader.setLeader(false)
221​
222 // Create executor C (will succeed)
223 const envC = createTestOfflineEnvironment({
224 storage: sharedStorage,
225 mutationFn: (params) => {
226 const mutations = params.transaction.mutations
227 envC.applyMutations(mutations)
228 return { ok: true, mutations }
229 },
230 })
231​
232 envC.leader.setLeader(false)
233​
234 // Transfer to B
235 envA.leader.setLeader(false)
236 envB.leader.setLeader(true)
237 await flushMicrotasks()
238​
239 // Wait for B to attempt and fail
240 await waitUntil(() => envB.mutationCalls.length >= 1)
241 expect(envB.mutationCalls).toHaveLength(1)
242​
243 // Transaction should still be in outbox
244 const outboxB = await envB.executor.peekOutbox()
245 expect(outboxB).toHaveLength(1)
246​
247 // Transfer to C
248 envB.leader.setLeader(false)
249 envC.leader.setLeader(true)
250 await flushMicrotasks()
251​
252 // Wait for C to execute successfully
253 await waitUntil(() => envC.mutationCalls.length >= 1)
254 expect(envC.mutationCalls).toHaveLength(1)
255 expect(envC.serverState.get(`survivor`)?.value).toBe(`resilient`)
256​
257 // Outbox should now be empty
258 await waitUntil(async () => {
259 const outbox = await envC.executor.peekOutbox()
260 return outbox.length === 0
261 })
262​
263 envA.executor.dispose()
264 envB.executor.dispose()
265 envC.executor.dispose()
266 })
267​
268 it(`new transactions from non-leader go online-only`, async () => {
269 const sharedStorage = new FakeStorageAdapter()
270​
271 const envA = createTestOfflineEnvironment({
272 storage: sharedStorage,
273 })
274​
275 await envA.waitForLeader()
276​
277 const envB = createTestOfflineEnvironment({
278 storage: sharedStorage,
279 })
280​
281 envB.leader.setLeader(false)
282 await flushMicrotasks()
283​
284 // Create transaction from non-leader B
285 const txB = envB.executor.createOfflineTransaction({
286 mutationFnName: envB.mutationFnName,
287 autoCommit: false,
288 })
289​
290 txB.mutate(() => {
291 envB.collection.insert({
292 id: `online-only`,
293 value: `no-outbox`,
294 completed: false,
295 updatedAt: new Date(),
296 })
297 })
298​
299 await txB.commit()
300​
301 // Should have executed immediately without outbox
302 expect(envB.mutationCalls).toHaveLength(1)
303​
304 // Should NOT be in outbox
305 const outbox = await envB.executor.peekOutbox()
306 expect(outbox).toHaveLength(0)
307​
308 // Now create transaction from leader A
309 const txA = envA.executor.createOfflineTransaction({
310 mutationFnName: envA.mutationFnName,
311 autoCommit: false,
312 })
313​
314 txA.mutate(() => {
315 envA.collection.insert({
316 id: `outbox-item`,
317 value: `in-outbox`,
318 completed: false,
319 updatedAt: new Date(),
320 })
321 })
322​
323 await txA.commit()
324​
325 // A's transaction should have gone through outbox
326 expect(envA.mutationCalls.length).toBeGreaterThanOrEqual(1)
327​
328 envA.executor.dispose()
329 envB.executor.dispose()
330 })
331​
332 it(`calls onLeadershipChange callback on both gain and loss`, async () => {
333 const sharedStorage = new FakeStorageAdapter()
334 const callbackCalls: Array<{ executor: string; isLeader: boolean }> = []
335​
336 const envA = createTestOfflineEnvironment({
337 storage: sharedStorage,
338 config: {
339 onLeadershipChange: (isLeader) => {
340 callbackCalls.push({ executor: `A`, isLeader })
341 },
342 },
343 })
344​
345 await envA.waitForLeader()
346​
347 // A should have been called with true
348 expect(callbackCalls).toContainEqual({ executor: `A`, isLeader: true })
349​
350 const envB = createTestOfflineEnvironment({
351 storage: sharedStorage,
352 config: {
353 onLeadershipChange: (isLeader) => {
354 callbackCalls.push({ executor: `B`, isLeader })
355 },
356 },
357 })
358​
359 envB.leader.setLeader(false)
360 await flushMicrotasks()
361​
362 // B should have been called with false
363 expect(callbackCalls).toContainEqual({ executor: `B`, isLeader: false })
364​
365 const beforeLength = callbackCalls.length
366​
367 // Transfer leadership
368 envA.leader.setLeader(false)
369 await flushMicrotasks()
370 envB.leader.setLeader(true)
371 await flushMicrotasks()
372​
373 // Both should have been called
374 const newCalls = callbackCalls.slice(beforeLength)
375 expect(newCalls).toContainEqual({ executor: `A`, isLeader: false })
376 expect(newCalls).toContainEqual({ executor: `B`, isLeader: true })
377​
378 envA.executor.dispose()
379 envB.executor.dispose()
380 })
381​
382 it(`calls onLeadershipChange exactly once during initialization`, async () => {
383 const callbackCalls: Array<boolean> = []
384​
385 const env = createTestOfflineEnvironment({
386 config: {
387 onLeadershipChange: (isLeader) => {
388 callbackCalls.push(isLeader)
389 },
390 },
391 })
392​
393 await env.waitForLeader()
394​
395 // Should be called exactly once with true during initialization
396 expect(callbackCalls).toEqual([true])
397​
398 // Wait a bit to ensure no duplicate calls
399 await new Promise((resolve) => setTimeout(resolve, 50))
400​
401 // Still should only have one call
402 expect(callbackCalls).toEqual([true])
403​
404 env.executor.dispose()
405 })
406})