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

KeyScheduler.test.ts

362 lines9.0 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { KeyScheduler } from '../src/executor/KeyScheduler'
3import type { OfflineTransaction } from '../src/types'
4​
5function createTransaction({
6 id,
7 createdAt,
8 nextAttemptAt,
9 retryCount = 0,
10}: {
11 id: string
12 createdAt: Date
13 nextAttemptAt: number
14 retryCount?: number
15}): OfflineTransaction {
16 return {
17 id,
18 mutationFnName: `syncData`,
19 mutations: [],
20 keys: [],
21 idempotencyKey: `idempotency-${id}`,
22 createdAt,
23 retryCount,
24 nextAttemptAt,
25 metadata: {},
26 version: 1,
27 }
29​
30describe(`KeyScheduler`, () => {
31 afterEach(() => {
32 vi.useRealTimers()
33 })
34​
35 it(`reconciles bulk updates with work proportional to the pending records`, () => {
36 const scheduler = new KeyScheduler()
37 const count = 64
38 let pendingIdReads = 0
39 for (let index = 0; index < count; index++) {
40 const transaction = createTransaction({
41 id: `tx-${index}`,
42 createdAt: new Date(index),
43 nextAttemptAt: 0,
44 })
45 Object.defineProperty(transaction, `id`, {
46 get: () => {
47 pendingIdReads++
48 return `tx-${index}`
49 },
50 })
51 scheduler.schedule(transaction)
52 }
53 pendingIdReads = 0
54​
55 let updateIdReads = 0
56 const updates = Array.from({ length: count }, (_, index) => {
57 const transaction = createTransaction({
58 id: `tx-${index}`,
59 createdAt: new Date(count - index),
60 nextAttemptAt: index + 1,
61 })
62 Object.defineProperty(transaction, `id`, {
63 get: () => {
64 updateIdReads++
65 return `tx-${index}`
66 },
67 })
68 return transaction
69 })
70​
71 scheduler.updateTransactions(updates)
72​
73 expect(pendingIdReads + updateIdReads).toBeLessThanOrEqual(count * 4)
74 expect(
75 scheduler
76 .getAllPendingTransactions()
77 .map(({ nextAttemptAt }) => nextAttemptAt),
78 ).toEqual(Array.from({ length: count }, (_, index) => count - index))
79 })
80​
81 it(`keeps the last update for a pending ID and ignores unknown IDs`, () => {
82 const scheduler = new KeyScheduler()
83 const first = createTransaction({
84 id: `first`,
85 createdAt: new Date(0),
86 nextAttemptAt: 0,
87 })
88 const second = createTransaction({
89 id: `second`,
90 createdAt: new Date(1),
91 nextAttemptAt: 0,
92 })
93 scheduler.schedule(first)
94 scheduler.schedule(second)
95​
96 const lastFirst = { ...first, createdAt: new Date(2), nextAttemptAt: 2 }
97 scheduler.updateTransactions([
98 { ...first, createdAt: new Date(-1), nextAttemptAt: 1 },
99 { ...first, id: `unknown` },
100 lastFirst,
101 ])
102​
103 expect(scheduler.getAllPendingTransactions()).toEqual([second, lastFirst])
104 })
105​
106 it(`does not execute a later ready transaction while an earlier retry is pending`, () => {
107 vi.useFakeTimers()
108​
109 const now = new Date(`2026-01-01T00:00:00.000Z`)
110 vi.setSystemTime(now)
111​
112 const scheduler = new KeyScheduler()
113 const first = createTransaction({
114 id: `first`,
115 createdAt: new Date(now.getTime()),
116 nextAttemptAt: now.getTime(),
117 })
118 const second = createTransaction({
119 id: `second`,
120 createdAt: new Date(now.getTime() + 1),
121 nextAttemptAt: now.getTime(),
122 })
123​
124 scheduler.schedule(first)
125 scheduler.schedule(second)
126​
127 const firstTx = scheduler.getNext()
128 expect(firstTx?.id).toBe(`first`)
129​
130 scheduler.markStarted(first)
131 scheduler.markFailed(first)
132 scheduler.updateTransaction({
133 ...first,
134 retryCount: 1,
135 nextAttemptAt: now.getTime() + 5000,
136 lastError: {
137 name: `Error`,
138 message: `network timeout`,
139 },
140 })
141​
142 const secondTx = scheduler.getNext()
143 expect(secondTx).toBeUndefined()
144 })
145​
146 it(`executes the first transaction once its retry delay has elapsed`, () => {
147 vi.useFakeTimers()
148​
149 const now = new Date(`2026-01-01T00:00:00.000Z`)
150 vi.setSystemTime(now)
151​
152 const scheduler = new KeyScheduler()
153 const first = createTransaction({
154 id: `first`,
155 createdAt: new Date(now.getTime()),
156 nextAttemptAt: now.getTime() + 5000,
157 retryCount: 1,
158 })
159 const second = createTransaction({
160 id: `second`,
161 createdAt: new Date(now.getTime() + 1),
162 nextAttemptAt: now.getTime(),
163 })
164​
165 scheduler.schedule(first)
166 scheduler.schedule(second)
167​
168 expect(scheduler.getNext()).toBeUndefined()
169​
170 vi.advanceTimersByTime(5000)
171​
172 const result = scheduler.getNext()
173 expect(result?.id).toBe(`first`)
174 })
175​
176 it(`processes the second transaction after the first completes`, () => {
177 vi.useFakeTimers()
178​
179 const now = new Date(`2026-01-01T00:00:00.000Z`)
180 vi.setSystemTime(now)
181​
182 const scheduler = new KeyScheduler()
183 const first = createTransaction({
184 id: `first`,
185 createdAt: new Date(now.getTime()),
186 nextAttemptAt: now.getTime(),
187 })
188 const second = createTransaction({
189 id: `second`,
190 createdAt: new Date(now.getTime() + 1),
191 nextAttemptAt: now.getTime(),
192 })
193​
194 scheduler.schedule(first)
195 scheduler.schedule(second)
196​
197 const tx1 = scheduler.getNext()
198 expect(tx1?.id).toBe(`first`)
199​
200 scheduler.markStarted(first)
201 scheduler.markCompleted(first)
202​
203 const tx2 = scheduler.getNext()
204 expect(tx2?.id).toBe(`second`)
205 })
206​
207 it(`returns nothing while a transaction is running`, () => {
208 vi.useFakeTimers()
209​
210 const now = new Date(`2026-01-01T00:00:00.000Z`)
211 vi.setSystemTime(now)
212​
213 const scheduler = new KeyScheduler()
214 const tx = createTransaction({
215 id: `tx1`,
216 createdAt: new Date(now.getTime()),
217 nextAttemptAt: now.getTime(),
218 })
219​
220 scheduler.schedule(tx)
221 scheduler.markStarted(tx)
222​
223 expect(scheduler.getNext()).toBeUndefined()
224 })
225​
226 it(`processes second transaction after first retries and succeeds`, () => {
227 vi.useFakeTimers()
228​
229 const now = new Date(`2026-01-01T00:00:00.000Z`)
230 vi.setSystemTime(now)
231​
232 const scheduler = new KeyScheduler()
233 const first = createTransaction({
234 id: `first`,
235 createdAt: new Date(now.getTime()),
236 nextAttemptAt: now.getTime(),
237 })
238 const second = createTransaction({
239 id: `second`,
240 createdAt: new Date(now.getTime() + 1),
241 nextAttemptAt: now.getTime(),
242 })
243​
244 scheduler.schedule(first)
245 scheduler.schedule(second)
246​
247 scheduler.markStarted(first)
248 scheduler.markFailed(first)
249 scheduler.updateTransaction({
250 ...first,
251 retryCount: 1,
252 nextAttemptAt: now.getTime() + 5000,
253 })
254​
255 expect(scheduler.getNext()).toBeUndefined()
256​
257 vi.advanceTimersByTime(5000)
258​
259 const retryTx = scheduler.getNext()
260 expect(retryTx?.id).toBe(`first`)
261​
262 scheduler.markStarted(retryTx!)
263 scheduler.markCompleted(retryTx!)
264​
265 const finalTx = scheduler.getNext()
266 expect(finalTx?.id).toBe(`second`)
267 })
268​
269 it(`maintains FIFO order regardless of scheduling order`, () => {
270 vi.useFakeTimers()
271​
272 const now = new Date(`2026-01-01T00:00:00.000Z`)
273 vi.setSystemTime(now)
274​
275 const scheduler = new KeyScheduler()
276 const older = createTransaction({
277 id: `older`,
278 createdAt: new Date(now.getTime()),
279 nextAttemptAt: now.getTime(),
280 })
281 const newer = createTransaction({
282 id: `newer`,
283 createdAt: new Date(now.getTime() + 1),
284 nextAttemptAt: now.getTime(),
285 })
286​
287 scheduler.schedule(newer)
288 scheduler.schedule(older)
289​
290 const next = scheduler.getNext()
291 expect(next?.id).toBe(`older`)
292 })
293​
294 it(`preserves FIFO order after updateTransaction`, () => {
295 vi.useFakeTimers()
296​
297 const now = new Date(`2026-01-01T00:00:00.000Z`)
298 vi.setSystemTime(now)
299​
300 const scheduler = new KeyScheduler()
301 const first = createTransaction({
302 id: `first`,
303 createdAt: new Date(now.getTime()),
304 nextAttemptAt: now.getTime(),
305 })
306 const second = createTransaction({
307 id: `second`,
308 createdAt: new Date(now.getTime() + 1),
309 nextAttemptAt: now.getTime(),
310 })
311​
312 scheduler.schedule(first)
313 scheduler.schedule(second)
314​
315 scheduler.updateTransaction({
316 ...first,
317 retryCount: 1,
318 nextAttemptAt: now.getTime() + 5000,
319 })
320​
321 vi.advanceTimersByTime(5000)
322​
323 const next = scheduler.getNext()
324 expect(next?.id).toBe(`first`)
325 })
326​
327 it(`returns undefined when no transactions are scheduled`, () => {
328 const scheduler = new KeyScheduler()
329 expect(scheduler.getNext()).toBeUndefined()
330 })
331​
332 it(`processes transactions with identical createdAt in scheduling order`, () => {
333 vi.useFakeTimers()
334​
335 const now = new Date(`2026-01-01T00:00:00.000Z`)
336 vi.setSystemTime(now)
337​
338 const scheduler = new KeyScheduler()
339 const first = createTransaction({
340 id: `first`,
341 createdAt: new Date(now.getTime()),
342 nextAttemptAt: now.getTime(),
343 })
344 const second = createTransaction({
345 id: `second`,
346 createdAt: new Date(now.getTime()),
347 nextAttemptAt: now.getTime(),
348 })
349​
350 scheduler.schedule(first)
351 scheduler.schedule(second)
352​
353 const tx1 = scheduler.getNext()
354 expect(tx1?.id).toBe(`first`)
355​
356 scheduler.markStarted(first)
357 scheduler.markCompleted(first)
358​
359 const tx2 = scheduler.getNext()
360 expect(tx2?.id).toBe(`second`)
361 })
362})