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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
|
/**
* @vitest-environment jsdom
*/
import "fake-indexeddb/auto";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CardState, db, Rating } from "../db/index";
import {
localCardRepository,
localDeckRepository,
localReviewLogRepository,
} from "../db/repositories";
import { SyncQueue, SyncStatus } from "./queue";
describe("SyncQueue", () => {
let syncQueue: SyncQueue;
beforeEach(async () => {
await db.decks.clear();
await db.cards.clear();
await db.reviewLogs.clear();
localStorage.clear();
syncQueue = new SyncQueue();
});
afterEach(async () => {
await db.decks.clear();
await db.cards.clear();
await db.reviewLogs.clear();
localStorage.clear();
});
describe("initial state", () => {
it("should have idle status by default", async () => {
const state = await syncQueue.getState();
expect(state.status).toBe(SyncStatus.Idle);
});
it("should have zero pending count initially", async () => {
const state = await syncQueue.getState();
expect(state.pendingCount).toBe(0);
});
it("should have zero last sync version initially", () => {
expect(syncQueue.getLastSyncVersion()).toBe(0);
});
it("should have no last sync date initially", async () => {
const state = await syncQueue.getState();
expect(state.lastSyncAt).toBeNull();
});
it("should have no error initially", async () => {
const state = await syncQueue.getState();
expect(state.lastError).toBeNull();
});
});
describe("getPendingChanges", () => {
it("should return empty arrays when no pending changes", async () => {
const changes = await syncQueue.getPendingChanges();
expect(changes.decks).toHaveLength(0);
expect(changes.cards).toHaveLength(0);
expect(changes.reviewLogs).toHaveLength(0);
});
it("should return unsynced decks", async () => {
await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
const changes = await syncQueue.getPendingChanges();
expect(changes.decks).toHaveLength(1);
expect(changes.decks[0]?.name).toBe("Test Deck");
});
it("should return unsynced cards", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
await localCardRepository.create({
deckId: deck.id,
front: "Question",
back: "Answer",
});
const changes = await syncQueue.getPendingChanges();
expect(changes.cards).toHaveLength(1);
expect(changes.cards[0]?.front).toBe("Question");
});
it("should return unsynced review logs", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
const card = await localCardRepository.create({
deckId: deck.id,
front: "Question",
back: "Answer",
});
await localReviewLogRepository.create({
cardId: card.id,
userId: "user-1",
rating: Rating.Good,
state: CardState.New,
scheduledDays: 1,
elapsedDays: 0,
reviewedAt: new Date(),
durationMs: 5000,
});
const changes = await syncQueue.getPendingChanges();
expect(changes.reviewLogs).toHaveLength(1);
});
it("should not return synced items", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
await localDeckRepository.markSynced(deck.id, 1);
const changes = await syncQueue.getPendingChanges();
expect(changes.decks).toHaveLength(0);
});
});
describe("getPendingCount", () => {
it("should return total count of pending items", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
await localCardRepository.create({
deckId: deck.id,
front: "Q1",
back: "A1",
});
await localCardRepository.create({
deckId: deck.id,
front: "Q2",
back: "A2",
});
const count = await syncQueue.getPendingCount();
// 1 deck + 2 cards = 3
expect(count).toBe(3);
});
});
describe("hasPendingChanges", () => {
it("should return false when no pending changes", async () => {
const hasPending = await syncQueue.hasPendingChanges();
expect(hasPending).toBe(false);
});
it("should return true when there are pending changes", async () => {
await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
const hasPending = await syncQueue.hasPendingChanges();
expect(hasPending).toBe(true);
});
});
describe("startSync", () => {
it("should set status to syncing", async () => {
await syncQueue.startSync();
const state = await syncQueue.getState();
expect(state.status).toBe(SyncStatus.Syncing);
});
it("should clear previous error", async () => {
await syncQueue.failSync("Previous error");
await syncQueue.startSync();
const state = await syncQueue.getState();
expect(state.lastError).toBeNull();
});
it("should notify listeners", async () => {
const listener = vi.fn();
syncQueue.subscribe(listener);
await syncQueue.startSync();
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
status: SyncStatus.Syncing,
}),
);
});
});
describe("completeSync", () => {
it("should set status to idle", async () => {
await syncQueue.startSync();
await syncQueue.completeSync(10);
const state = await syncQueue.getState();
expect(state.status).toBe(SyncStatus.Idle);
});
it("should update last sync version", async () => {
await syncQueue.completeSync(10);
expect(syncQueue.getLastSyncVersion()).toBe(10);
});
it("should update last sync date", async () => {
const before = new Date();
await syncQueue.completeSync(10);
const state = await syncQueue.getState();
expect(state.lastSyncAt).not.toBeNull();
expect(state.lastSyncAt?.getTime()).toBeGreaterThanOrEqual(
before.getTime(),
);
});
it("should persist state to localStorage", async () => {
await syncQueue.completeSync(10);
const stored = JSON.parse(
localStorage.getItem("kioku_sync_state") ?? "{}",
);
expect(stored.lastSyncVersion).toBe(10);
expect(stored.lastSyncAt).toBeDefined();
});
it("should notify listeners", async () => {
const listener = vi.fn();
syncQueue.subscribe(listener);
await syncQueue.completeSync(10);
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
status: SyncStatus.Idle,
lastSyncVersion: 10,
}),
);
});
});
describe("failSync", () => {
it("should set status to error", async () => {
await syncQueue.failSync("Network error");
const state = await syncQueue.getState();
expect(state.status).toBe(SyncStatus.Error);
});
it("should set error message", async () => {
await syncQueue.failSync("Network error");
const state = await syncQueue.getState();
expect(state.lastError).toBe("Network error");
});
it("should notify listeners", async () => {
const listener = vi.fn();
syncQueue.subscribe(listener);
await syncQueue.failSync("Network error");
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
status: SyncStatus.Error,
lastError: "Network error",
}),
);
});
});
describe("markSynced", () => {
it("should mark decks as synced", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
await syncQueue.markSynced({
decks: [{ id: deck.id, syncVersion: 5 }],
cards: [],
reviewLogs: [],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
const found = await localDeckRepository.findById(deck.id);
expect(found?._synced).toBe(true);
expect(found?.syncVersion).toBe(5);
});
it("should mark cards as synced", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
const card = await localCardRepository.create({
deckId: deck.id,
front: "Q",
back: "A",
});
await syncQueue.markSynced({
decks: [],
cards: [{ id: card.id, syncVersion: 3 }],
reviewLogs: [],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
const found = await localCardRepository.findById(card.id);
expect(found?._synced).toBe(true);
expect(found?.syncVersion).toBe(3);
});
it("should mark review logs as synced", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
const card = await localCardRepository.create({
deckId: deck.id,
front: "Q",
back: "A",
});
const reviewLog = await localReviewLogRepository.create({
cardId: card.id,
userId: "user-1",
rating: Rating.Good,
state: CardState.New,
scheduledDays: 1,
elapsedDays: 0,
reviewedAt: new Date(),
durationMs: 5000,
});
await syncQueue.markSynced({
decks: [],
cards: [],
reviewLogs: [{ id: reviewLog.id, syncVersion: 2 }],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
const found = await localReviewLogRepository.findById(reviewLog.id);
expect(found?._synced).toBe(true);
expect(found?.syncVersion).toBe(2);
});
it("should notify listeners", async () => {
const listener = vi.fn();
syncQueue.subscribe(listener);
await syncQueue.markSynced({
decks: [],
cards: [],
reviewLogs: [],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
expect(listener).toHaveBeenCalled();
});
});
describe("applyPulledChanges", () => {
it("should upsert decks from server", async () => {
const serverDeck = {
id: "server-deck-1",
userId: "user-1",
name: "Server Deck",
description: null,
newCardsPerDay: 15,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
syncVersion: 5,
_synced: false,
};
await syncQueue.applyPulledChanges({
decks: [serverDeck],
cards: [],
reviewLogs: [],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
const found = await localDeckRepository.findById("server-deck-1");
expect(found?.name).toBe("Server Deck");
expect(found?._synced).toBe(true);
});
it("should upsert cards from server", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
await localDeckRepository.markSynced(deck.id, 1);
const serverCard = {
id: "server-card-1",
deckId: deck.id,
noteId: null,
isReversed: null,
front: "Server Question",
back: "Server Answer",
state: CardState.New,
due: new Date(),
stability: 0,
difficulty: 0,
elapsedDays: 0,
scheduledDays: 0,
reps: 0,
lapses: 0,
lastReview: null,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
syncVersion: 3,
_synced: false,
} as const;
await syncQueue.applyPulledChanges({
decks: [],
cards: [serverCard],
reviewLogs: [],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
const found = await localCardRepository.findById("server-card-1");
expect(found?.front).toBe("Server Question");
expect(found?._synced).toBe(true);
});
it("should upsert review logs from server", async () => {
const deck = await localDeckRepository.create({
userId: "user-1",
name: "Test Deck",
description: null,
newCardsPerDay: 20,
});
const card = await localCardRepository.create({
deckId: deck.id,
front: "Q",
back: "A",
});
const serverLog = {
id: "server-log-1",
cardId: card.id,
userId: "user-1",
rating: Rating.Good,
state: CardState.New,
scheduledDays: 1,
elapsedDays: 0,
reviewedAt: new Date(),
durationMs: 5000,
syncVersion: 2,
_synced: false,
} as const;
await syncQueue.applyPulledChanges({
decks: [],
cards: [],
reviewLogs: [serverLog],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
const found = await localReviewLogRepository.findById("server-log-1");
expect(found?.rating).toBe(Rating.Good);
expect(found?._synced).toBe(true);
});
it("should notify listeners", async () => {
const listener = vi.fn();
syncQueue.subscribe(listener);
await syncQueue.applyPulledChanges({
decks: [],
cards: [],
reviewLogs: [],
noteTypes: [],
noteFieldTypes: [],
notes: [],
noteFieldValues: [],
});
expect(listener).toHaveBeenCalled();
});
});
describe("reset", () => {
it("should reset all state", async () => {
await syncQueue.completeSync(10);
await syncQueue.reset();
const state = await syncQueue.getState();
expect(state.status).toBe(SyncStatus.Idle);
expect(state.lastSyncVersion).toBe(0);
expect(state.lastSyncAt).toBeNull();
expect(state.lastError).toBeNull();
});
it("should clear localStorage", async () => {
await syncQueue.completeSync(10);
await syncQueue.reset();
expect(localStorage.getItem("kioku_sync_state")).toBeNull();
});
it("should notify listeners", async () => {
const listener = vi.fn();
syncQueue.subscribe(listener);
await syncQueue.reset();
expect(listener).toHaveBeenCalled();
});
});
describe("subscribe", () => {
it("should return unsubscribe function", async () => {
const listener = vi.fn();
const unsubscribe = syncQueue.subscribe(listener);
await syncQueue.startSync();
expect(listener).toHaveBeenCalledTimes(1);
unsubscribe();
await syncQueue.completeSync(10);
expect(listener).toHaveBeenCalledTimes(1);
});
it("should support multiple listeners", async () => {
const listener1 = vi.fn();
const listener2 = vi.fn();
syncQueue.subscribe(listener1);
syncQueue.subscribe(listener2);
await syncQueue.startSync();
expect(listener1).toHaveBeenCalled();
expect(listener2).toHaveBeenCalled();
});
});
describe("state persistence", () => {
it("should restore state from localStorage on construction", async () => {
// Simulate previous sync state
localStorage.setItem(
"kioku_sync_state",
JSON.stringify({
lastSyncVersion: 15,
lastSyncAt: "2024-01-15T10:00:00.000Z",
}),
);
const newQueue = new SyncQueue();
expect(newQueue.getLastSyncVersion()).toBe(15);
const state = await newQueue.getState();
expect(state.lastSyncAt).toEqual(new Date("2024-01-15T10:00:00.000Z"));
});
it("should handle invalid localStorage data", async () => {
localStorage.setItem("kioku_sync_state", "invalid json");
const newQueue = new SyncQueue();
expect(newQueue.getLastSyncVersion()).toBe(0);
});
});
});
|