forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollection-lifecycle.test.ts
More file actions
485 lines (388 loc) · 13.7 KB
/
collection-lifecycle.test.ts
File metadata and controls
485 lines (388 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createCollection } from "../src/collection.js"
// Mock setTimeout and clearTimeout for testing GC behavior
const originalSetTimeout = global.setTimeout
const originalClearTimeout = global.clearTimeout
describe(`Collection Lifecycle Management`, () => {
let mockSetTimeout: ReturnType<typeof vi.fn>
let mockClearTimeout: ReturnType<typeof vi.fn>
let timeoutCallbacks: Map<number, () => void>
let timeoutId = 1
beforeEach(() => {
timeoutCallbacks = new Map()
timeoutId = 1
mockSetTimeout = vi.fn((callback: () => void, _delay: number) => {
const id = timeoutId++
timeoutCallbacks.set(id, callback)
return id
})
mockClearTimeout = vi.fn((id: number) => {
timeoutCallbacks.delete(id)
})
global.setTimeout = mockSetTimeout as any
global.clearTimeout = mockClearTimeout as any
})
afterEach(() => {
global.setTimeout = originalSetTimeout
global.clearTimeout = originalClearTimeout
vi.clearAllMocks()
})
const triggerTimeout = (id: number) => {
const callback = timeoutCallbacks.get(id)
if (callback) {
callback()
timeoutCallbacks.delete(id)
}
}
describe(`Collection Status Tracking`, () => {
it(`should start with idle status and transition to ready after first commit when startSync is false`, () => {
let beginCallback: (() => void) | undefined
let commitCallback: (() => void) | undefined
const collection = createCollection<{ id: string; name: string }>({
id: `status-test`,
getKey: (item) => item.id,
sync: {
sync: ({ begin, commit, markReady }) => {
beginCallback = begin as () => void
commitCallback = () => {
commit()
markReady()
}
},
},
})
expect(collection.status).toBe(`idle`)
collection.preload()
if (beginCallback && commitCallback) {
beginCallback()
commitCallback()
}
expect(collection.status).toBe(`ready`)
})
it(`should start with loading status and transition to ready after first commit when startSync is true`, () => {
let beginCallback: (() => void) | undefined
let commitCallback: (() => void) | undefined
const collection = createCollection<{ id: string; name: string }>({
id: `status-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, commit, markReady }) => {
beginCallback = begin as () => void
commitCallback = () => {
commit()
markReady()
}
},
},
})
// Should start in loading state since sync starts immediately
expect(collection.status).toBe(`loading`)
// Trigger first commit (begin then commit)
if (beginCallback && commitCallback) {
beginCallback()
commitCallback()
}
expect(collection.status).toBe(`ready`)
})
it(`should transition to cleaned-up status after cleanup`, async () => {
const collection = createCollection<{ id: string; name: string }>({
id: `cleanup-status-test`,
getKey: (item) => item.id,
sync: {
sync: () => {},
},
})
await collection.cleanup()
expect(collection.status).toBe(`cleaned-up`)
})
it(`should transition when subscribing to changes`, () => {
let beginCallback: (() => void) | undefined
let commitCallback: (() => void) | undefined
const collection = createCollection<{ id: string; name: string }>({
id: `subscribe-test`,
getKey: (item) => item.id,
gcTime: 0,
sync: {
sync: ({ begin, commit, markReady }) => {
beginCallback = begin as () => void
commitCallback = () => {
commit()
markReady()
}
},
},
})
expect(collection.status).toBe(`idle`)
const unsubscribe = collection.subscribeChanges(() => {})
expect(collection.status).toBe(`loading`)
if (beginCallback && commitCallback) {
beginCallback()
commitCallback()
}
expect(collection.status).toBe(`ready`)
unsubscribe()
expect(collection.status).toBe(`ready`)
})
it(`should restart sync when accessing cleaned-up collection`, async () => {
let syncCallCount = 0
const collection = createCollection<{ id: string; name: string }>({
id: `restart-test`,
getKey: (item) => item.id,
startSync: false, // Test lazy loading behavior
sync: {
sync: ({ begin, commit, markReady }) => {
begin()
commit()
markReady()
syncCallCount++
},
},
})
expect(syncCallCount).toBe(0) // no sync yet
await collection.preload()
expect(syncCallCount).toBe(1) // sync called when subscribing
await collection.cleanup()
expect(collection.status).toBe(`cleaned-up`)
await collection.preload()
expect(syncCallCount).toBe(2)
expect(collection.status).toBe(`ready`) // Sync completes immediately in this test
})
})
describe(`Subscriber Management`, () => {
it(`should track active subscribers correctly`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `subscriber-test`,
getKey: (item) => item.id,
sync: {
sync: () => {},
},
})
// No subscribers initially
expect((collection as any).activeSubscribersCount).toBe(0)
// Subscribe to changes
const unsubscribe1 = collection.subscribeChanges(() => {})
expect((collection as any).activeSubscribersCount).toBe(1)
const unsubscribe2 = collection.subscribeChanges(() => {})
expect((collection as any).activeSubscribersCount).toBe(2)
// Unsubscribe
unsubscribe1()
expect((collection as any).activeSubscribersCount).toBe(1)
unsubscribe2()
expect((collection as any).activeSubscribersCount).toBe(0)
})
it(`should track key-specific subscribers`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `key-subscriber-test`,
getKey: (item) => item.id,
sync: {
sync: () => {},
},
})
const unsubscribe1 = collection.subscribeChangesKey(`key1`, () => {})
const unsubscribe2 = collection.subscribeChangesKey(`key2`, () => {})
const unsubscribe3 = collection.subscribeChangesKey(`key1`, () => {})
expect((collection as any).activeSubscribersCount).toBe(3)
unsubscribe1()
expect((collection as any).activeSubscribersCount).toBe(2)
unsubscribe2()
unsubscribe3()
expect((collection as any).activeSubscribersCount).toBe(0)
})
it(`should handle rapid subscribe/unsubscribe correctly`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `rapid-sub-test`,
getKey: (item) => item.id,
gcTime: 1000, // Short GC time for testing
sync: {
sync: () => {},
},
})
// Subscribe and immediately unsubscribe multiple times
for (let i = 0; i < 5; i++) {
const unsubscribe = collection.subscribeChanges(() => {})
expect((collection as any).activeSubscribersCount).toBe(1)
unsubscribe()
expect((collection as any).activeSubscribersCount).toBe(0)
// Should start GC timer each time
expect(mockSetTimeout).toHaveBeenCalledWith(expect.any(Function), 1000)
}
expect(mockSetTimeout).toHaveBeenCalledTimes(5)
})
})
describe(`Garbage Collection`, () => {
it(`should start GC timer when last subscriber is removed`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `gc-timer-test`,
getKey: (item) => item.id,
gcTime: 5000, // 5 seconds
sync: {
sync: () => {},
},
})
const unsubscribe = collection.subscribeChanges(() => {})
// Should not have GC timer while there are subscribers
expect(mockSetTimeout).not.toHaveBeenCalled()
unsubscribe()
// Should start GC timer when last subscriber is removed
expect(mockSetTimeout).toHaveBeenCalledWith(expect.any(Function), 5000)
})
it(`should cancel GC timer when new subscriber is added`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `gc-cancel-test`,
getKey: (item) => item.id,
gcTime: 5000,
sync: {
sync: () => {},
},
})
const unsubscribe1 = collection.subscribeChanges(() => {})
unsubscribe1()
expect(mockSetTimeout).toHaveBeenCalledTimes(1)
const timerId = mockSetTimeout.mock.results[0]?.value
// Add new subscriber should cancel GC timer
const unsubscribe2 = collection.subscribeChanges(() => {})
expect(mockClearTimeout).toHaveBeenCalledWith(timerId)
unsubscribe2()
})
it(`should cleanup collection when GC timer fires`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `gc-cleanup-test`,
getKey: (item) => item.id,
gcTime: 1000,
sync: {
sync: () => {},
},
})
const unsubscribe = collection.subscribeChanges(() => {})
unsubscribe()
expect(collection.status).toBe(`loading`) // or "ready"
// Trigger GC timeout
const timerId = mockSetTimeout.mock.results[0]?.value
if (timerId) {
triggerTimeout(timerId)
}
expect(collection.status).toBe(`cleaned-up`)
})
it(`should use default GC time when not specified`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `default-gc-test`,
getKey: (item) => item.id,
sync: {
sync: () => {},
},
})
const unsubscribe = collection.subscribeChanges(() => {})
unsubscribe()
// Should use default 5 minutes (300000ms)
expect(mockSetTimeout).toHaveBeenCalledWith(expect.any(Function), 300000)
})
it(`should disable GC when gcTime is 0`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `disabled-gc-test`,
getKey: (item) => item.id,
gcTime: 0, // Disabled GC
sync: {
sync: () => {},
},
})
const unsubscribe = collection.subscribeChanges(() => {})
unsubscribe()
// Should not start any timer when GC is disabled
expect(mockSetTimeout).not.toHaveBeenCalled()
expect(collection.status).not.toBe(`cleaned-up`)
})
})
describe(`Manual Preload and Cleanup`, () => {
it(`should resolve preload immediately if already ready`, async () => {
let beginCallback: (() => void) | undefined
let commitCallback: (() => void) | undefined
const collection = createCollection<{ id: string; name: string }>({
id: `preload-ready-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, commit, markReady }) => {
beginCallback = begin as () => void
commitCallback = () => {
commit()
markReady()
}
},
},
})
// Make collection ready
if (beginCallback && commitCallback) {
beginCallback()
commitCallback()
}
// Preload should resolve immediately
const startTime = Date.now()
await collection.preload()
const endTime = Date.now()
expect(endTime - startTime).toBeLessThan(50) // Should be nearly instant
})
it(`should share preload promise for concurrent calls`, () => {
const collection = createCollection<{ id: string; name: string }>({
id: `concurrent-preload-test`,
getKey: (item) => item.id,
sync: {
sync: () => {},
},
})
const promise1 = collection.preload()
const promise2 = collection.preload()
expect(promise1).toBe(promise2) // Should be the same promise
})
it(`should cleanup collection manually`, async () => {
let cleanupCalled = false
const collection = createCollection<{ id: string; name: string }>({
id: `manual-cleanup-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: () => {
return () => {
cleanupCalled = true
}
},
},
})
expect(collection.status).toBe(`loading`)
await collection.cleanup()
expect(collection.status).toBe(`cleaned-up`)
expect(cleanupCalled).toBe(true)
})
})
describe(`Lifecycle Events`, () => {
it(`should call onFirstReady callbacks`, () => {
let markReadyCallback: (() => void) | undefined
const callbacks: Array<() => void> = []
const collection = createCollection<{ id: string; name: string }>({
id: `first-ready-test`,
getKey: (item) => item.id,
sync: {
sync: ({ markReady }) => {
markReadyCallback = markReady as () => void
},
},
})
const unsubscribe = collection.subscribeChanges(() => {})
// Register callbacks
collection.onFirstReady(() => callbacks.push(() => `callback1`))
collection.onFirstReady(() => callbacks.push(() => `callback2`))
expect(callbacks).toHaveLength(0)
// Trigger first ready
if (markReadyCallback) {
markReadyCallback()
}
expect(callbacks).toHaveLength(2)
// Subsequent markReady calls should not trigger callbacks
if (markReadyCallback) {
markReadyCallback()
}
expect(callbacks).toHaveLength(2)
unsubscribe()
})
})
})