-
-
Notifications
You must be signed in to change notification settings - Fork 393
/
online.test.js
1134 lines (902 loc) · 38.9 KB
/
online.test.js
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { BaseItemCounts } from '../lib/BaseItemCounts.js'
import * as Factory from '../lib/factory.js'
import * as Utils from '../lib/Utils.js'
chai.use(chaiAsPromised)
const expect = chai.expect
describe('online syncing', function () {
this.timeout(Factory.TenSecondTimeout)
let application
let email
let password
let expectedItemCount
let context
let safeGuard
const syncOptions = {
checkIntegrity: true,
awaitAll: true,
}
beforeEach(async function () {
localStorage.clear()
expectedItemCount = BaseItemCounts.DefaultItemsWithAccount
context = await Factory.createAppContext()
await context.launch()
application = context.application
email = context.email
password = context.password
Factory.disableIntegrityAutoHeal(application)
await Factory.registerUserToApplication({
application: application,
email: email,
password: password,
})
safeGuard = application.dependencies.get(TYPES.SyncFrequencyGuard)
safeGuard.clear()
})
afterEach(async function () {
expect(application.sync.isOutOfSync()).to.equal(false)
const items = application.items.allTrackedItems()
expect(items.length).to.equal(expectedItemCount)
const rawPayloads = await application.storage.getAllRawPayloads()
expect(rawPayloads.length).to.equal(expectedItemCount)
await Factory.safeDeinit(application)
localStorage.clear()
safeGuard.clear()
application = undefined
context = undefined
safeGuard = undefined
})
function noteObjectsFromObjects(items) {
return items.filter((item) => item.content_type === ContentType.TYPES.Note)
}
it('should register and sync basic model online', async function () {
let note = await Factory.createSyncedNote(application)
expectedItemCount++
expect(application.items.getDirtyItems().length).to.equal(0)
note = application.items.findItem(note.uuid)
expect(note.dirty).to.not.be.ok
const rawPayloads = await application.storage.getAllRawPayloads()
const notePayloads = noteObjectsFromObjects(rawPayloads)
expect(notePayloads.length).to.equal(1)
for (const rawNote of notePayloads) {
expect(rawNote.dirty).to.not.be.ok
}
})
it('should login and retrieve synced item', async function () {
const note = await Factory.createSyncedNote(application)
expectedItemCount++
application = await Factory.signOutApplicationAndReturnNew(application)
await Factory.loginToApplication({
application: application,
email: email,
password: password,
})
const notes = application.items.getDisplayableNotes()
expect(notes.length).to.equal(1)
expect(notes[0].title).to.equal(note.title)
})
it('can complete multipage sync on sign in', async function () {
const count = 0
await Factory.createManyMappedNotes(application, count)
expectedItemCount += count
await application.sync.sync(syncOptions)
application = await context.signout()
expect(application.items.items.length).to.equal(BaseItemCounts.DefaultItems)
const promise = Factory.loginToApplication({
application: application,
email: email,
password: password,
})
/** Throw in some random syncs to cause trouble */
const syncCount = 30
for (let i = 0; i < syncCount; i++) {
application.sync.sync(syncOptions)
await Factory.sleep(0.01, undefined, true)
}
await promise
expect(promise).to.be.fulfilled
/** Allow any unwaited syncs in for loop to complete */
await Factory.sleep(0.5)
}).timeout(20000)
it('having offline data then signing in should not alternate uuid and merge with account', async function () {
application = await Factory.signOutApplicationAndReturnNew(application)
const note = await Factory.createMappedNote(application)
expectedItemCount++
await Factory.loginToApplication({
application: application,
email: email,
password: password,
mergeLocal: true,
})
const notes = application.items.getDisplayableNotes()
expect(notes.length).to.equal(1)
/** uuid should have been alternated */
expect(notes[0].uuid).to.equal(note.uuid)
})
it('resolve on next timing strategy', async function () {
const syncCount = 7
let successes = 0
let events = 0
application.sync.ut_beginLatencySimulator(250)
application.sync.addEventObserver((event, data) => {
if (event === SyncEvent.SyncCompletedWithAllItemsUploaded) {
events++
}
})
const promises = []
for (let i = 0; i < syncCount; i++) {
promises.push(
application.sync
.sync({
queueStrategy: SyncQueueStrategy.ResolveOnNext,
})
.then(() => {
successes++
}),
)
}
await Promise.all(promises)
expect(successes).to.equal(syncCount)
// Only a fully executed sync request creates a sync:completed event.
// We don't know how many will execute above.
expect(events).to.be.at.least(1)
application.sync.ut_endLatencySimulator()
// Since the syncs all happen after one another, extra syncs may be queued on that we are not awaiting.
await Factory.sleep(0.5)
})
it('force spawn new timing strategy', async function () {
const syncCount = 7
let successes = 0
let events = 0
application.sync.ut_beginLatencySimulator(250)
application.sync.addEventObserver((event, data) => {
if (event === SyncEvent.SyncCompletedWithAllItemsUploaded) {
events++
}
})
const promises = []
for (let i = 0; i < syncCount; i++) {
promises.push(
application.sync
.sync({
queueStrategy: SyncQueueStrategy.ForceSpawnNew,
})
.then(() => {
successes++
}),
)
}
await Promise.all(promises)
expect(successes).to.equal(syncCount)
expect(events).to.equal(syncCount)
application.sync.ut_endLatencySimulator()
})
it('retrieving new items should not mark them as dirty', async function () {
const originalNote = await Factory.createSyncedNote(application)
expectedItemCount++
application = await Factory.signOutApplicationAndReturnNew(application)
const promise = new Promise((resolve) => {
application.sync.addEventObserver(async (event) => {
if (event === SyncEvent.PaginatedSyncRequestCompleted) {
const note = application.items.findItem(originalNote.uuid)
if (note) {
expect(note.dirty).to.not.be.ok
resolve()
}
}
})
})
await application.signIn(email, password, undefined, undefined, undefined, true)
await promise
})
it('allows saving of data after sign out', async function () {
expect(application.items.getDisplayableItemsKeys().length).to.equal(1)
application = await Factory.signOutApplicationAndReturnNew(application)
expect(application.items.getDisplayableItemsKeys().length).to.equal(1)
const note = await Factory.createMappedNote(application)
expectedItemCount++
await application.mutator.setItemDirty(note)
await application.sync.sync(syncOptions)
const rawPayloads = await application.storage.getAllRawPayloads()
const notePayload = noteObjectsFromObjects(rawPayloads)
expect(notePayload.length).to.equal(1)
expect(application.items.getDisplayableNotes().length).to.equal(1)
// set item to be merged for when sign in occurs
await application.sync.markAllItemsAsNeedingSyncAndPersist()
expect(application.sync.isOutOfSync()).to.equal(false)
expect(application.items.getDirtyItems().length).to.equal(BaseItemCounts.DefaultItems + 1)
// Sign back in for next tests
await Factory.loginToApplication({
application: application,
email: email,
password: password,
})
expect(application.items.getDirtyItems().length).to.equal(0)
expect(application.items.getDisplayableItemsKeys().length).to.equal(1)
expect(application.sync.isOutOfSync()).to.equal(false)
expect(application.items.getDisplayableNotes().length).to.equal(1)
for (const item of application.items.getDisplayableNotes()) {
expect(item.content.title).to.be.ok
}
const updatedRawPayloads = await application.storage.getAllRawPayloads()
for (const payload of updatedRawPayloads) {
// if an item comes back from the server, it is saved to disk immediately without a dirty value.
expect(payload.dirty).to.not.be.ok
}
})
it('mapping should not mutate items with error decrypting state', async function () {
const note = await Factory.createMappedNote(application)
expectedItemCount++
const originalTitle = note.content.title
await application.mutator.setItemDirty(note)
await application.sync.sync(syncOptions)
const encrypted = CreateEncryptedServerSyncPushPayload(
await application.encryption.encryptSplitSingle({
usesItemsKeyWithKeyLookup: {
items: [note.payloadRepresentation()],
},
}),
)
const errorred = new EncryptedPayload({
...encrypted,
errorDecrypting: true,
})
const items = await application.mutator.emitItemsFromPayloads([errorred], PayloadEmitSource.LocalChanged)
const mappedItem = application.items.findAnyItem(errorred.uuid)
expect(typeof mappedItem.content).to.equal('string')
const decryptedPayload = await application.encryption.decryptSplitSingle({
usesItemsKeyWithKeyLookup: {
items: [errorred],
},
})
const mappedItems2 = await application.mutator.emitItemsFromPayloads(
[decryptedPayload],
PayloadEmitSource.LocalChanged,
)
const mappedItem2 = mappedItems2[0]
expect(typeof mappedItem2.content).to.equal('object')
expect(mappedItem2.content.title).to.equal(originalTitle)
})
it('signing into account with pre-existing items', async function () {
const note = await Factory.createMappedNote(application)
await Factory.markDirtyAndSyncItem(application, note)
expectedItemCount += 1
application = await Factory.signOutApplicationAndReturnNew(application)
await application.signIn(email, password, undefined, undefined, undefined, true)
expect(application.items.items.length).to.equal(expectedItemCount)
})
it('removes item from storage upon deletion', async function () {
let note = await Factory.createMappedNote(application)
expectedItemCount++
await application.mutator.setItemDirty(note)
await application.sync.sync(syncOptions)
note = application.items.findItem(note.uuid)
expect(note.dirty).to.equal(false)
expect(application.items.items.length).to.equal(expectedItemCount)
await application.mutator.setItemToBeDeleted(note)
note = application.items.findAnyItem(note.uuid)
expect(note.dirty).to.equal(true)
expectedItemCount--
await application.sync.sync(syncOptions)
note = application.items.findItem(note.uuid)
expect(note).to.not.be.ok
// We expect that this item is now gone for good, and no duplicate has been created.
expect(application.items.items.length).to.equal(expectedItemCount)
await Factory.sleep(0.5)
const rawPayloads = await application.storage.getAllRawPayloads()
expect(rawPayloads.length).to.equal(expectedItemCount)
})
it('retrieving item with no content should correctly map local state', async function () {
const note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
await application.sync.sync(syncOptions)
const syncToken = await application.sync.getLastSyncToken()
expectedItemCount++
expect(application.items.items.length).to.equal(expectedItemCount)
// client A
await application.mutator.setItemToBeDeleted(note)
await application.sync.sync(syncOptions)
// Subtract 1
expectedItemCount--
// client B
// Clearing sync tokens wont work as server wont return deleted items.
// Set saved sync token instead
await application.sync.setLastSyncToken(syncToken)
await application.sync.sync(syncOptions)
expect(application.items.items.length).to.equal(expectedItemCount)
})
it('changing an item while it is being synced should sync again', async function () {
const note = await Factory.createMappedNote(application)
expectedItemCount++
/** Begin syncing it with server but introduce latency so we can sneak in a delete */
application.sync.ut_beginLatencySimulator(500)
const sync = application.sync.sync()
/** Sleep so sync call can begin preparations but not fully begin */
await Factory.sleep(0.1)
await application.mutator.changeItem(note, (mutator) => {
mutator.title = 'latest title'
})
await sync
application.sync.ut_endLatencySimulator()
await application.sync.sync(syncOptions)
const latestNote = application.items.findItem(note.uuid)
expect(latestNote.title).to.equal('latest title')
})
it('deleting an item while it is being synced should keep deletion state', async function () {
const note = await Factory.createMappedNote(application)
expectedItemCount++
/** Begin syncing it with server but introduce latency so we can sneak in a delete */
application.sync.ut_beginLatencySimulator(500)
const sync = application.sync.sync()
/** Sleep so sync call can begin preparations but not fully begin */
await Factory.sleep(0.1)
await application.mutator.setItemToBeDeleted(note)
expectedItemCount--
await sync
application.sync.ut_endLatencySimulator()
await application.sync.sync(syncOptions)
/** We expect that item has been deleted */
const allItems = application.items.items
expect(allItems.length).to.equal(expectedItemCount)
})
it('should defer syncing if syncing is breaching the sync calls per minute threshold', async function () {
let syncCount = 0
while(!safeGuard.isSyncCallsThresholdReachedThisMinute()) {
await application.sync.sync({
onPresyncSave: () => {
syncCount++
}
})
}
expect(safeGuard.isSyncCallsThresholdReachedThisMinute()).to.equal(true)
expect(syncCount == 200).to.equal(true)
})
it('items that are never synced and deleted should not be uploaded to server', async function () {
const note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
await application.mutator.setItemToBeDeleted(note)
let success = true
let didCompleteRelevantSync = false
let beginCheckingResponse = false
application.sync.addEventObserver((eventName, data) => {
if (eventName === SyncEvent.DownloadFirstSyncCompleted) {
beginCheckingResponse = true
}
if (!beginCheckingResponse) {
return
}
if (!didCompleteRelevantSync && eventName === SyncEvent.PaginatedSyncRequestCompleted) {
didCompleteRelevantSync = true
const response = data
const matching = response.savedPayloads.find((p) => p.uuid === note.uuid)
if (matching) {
success = false
}
}
})
await application.sync.sync({ mode: SyncMode.DownloadFirst })
expect(didCompleteRelevantSync).to.equal(true)
expect(success).to.equal(true)
})
it('items that are deleted after download first sync complete should not be uploaded to server', async function () {
/** The singleton manager may delete items are download first. We dont want those uploaded to server. */
const note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
let success = true
let didCompleteRelevantSync = false
let beginCheckingResponse = false
application.sync.addEventObserver(async (eventName, data) => {
if (eventName === SyncEvent.DownloadFirstSyncCompleted) {
await application.mutator.setItemToBeDeleted(note)
beginCheckingResponse = true
}
if (!beginCheckingResponse) {
return
}
if (!didCompleteRelevantSync && eventName === SyncEvent.PaginatedSyncRequestCompleted) {
didCompleteRelevantSync = true
const response = data
const matching = response.savedPayloads.find((p) => p.uuid === note.uuid)
if (matching) {
success = false
}
}
})
await application.sync.sync({ mode: SyncMode.DownloadFirst })
expect(didCompleteRelevantSync).to.equal(true)
expect(success).to.equal(true)
})
it('marking an item dirty then saving to disk should retain that dirty state when restored', async function () {
const note = await Factory.createMappedNote(application)
expectedItemCount++
await application.sync.markAllItemsAsNeedingSyncAndPersist()
application.items.resetState()
application.payloads.resetState()
await application.sync.clearSyncPositionTokens()
expect(application.items.items.length).to.equal(0)
const rawPayloads = await application.storage.getAllRawPayloads()
const encryptedPayloads = rawPayloads.map((rawPayload) => {
return new EncryptedPayload(rawPayload)
})
const encryptionSplit = SplitPayloadsByEncryptionType(encryptedPayloads)
const keyedSplit = CreateDecryptionSplitWithKeyLookup(encryptionSplit)
const decryptionResults = await application.encryption.decryptSplit(keyedSplit)
await application.mutator.emitItemsFromPayloads(decryptionResults, PayloadEmitSource.LocalChanged)
expect(application.items.allTrackedItems().length).to.equal(expectedItemCount)
const foundNote = application.items.findAnyItem(note.uuid)
expect(foundNote.dirty).to.equal(true)
await application.sync.sync(syncOptions)
})
/** This test takes 30s+ on a Docker server environment and should be skipped for now */
it.skip('should handle uploading with sync pagination', async function () {
const largeItemCount = SyncUpDownLimit + 10
for (let i = 0; i < largeItemCount; i++) {
const note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
}
expectedItemCount += largeItemCount
await application.sync.sync(syncOptions)
const rawPayloads = await application.storage.getAllRawPayloads()
expect(rawPayloads.length).to.equal(expectedItemCount)
}).timeout(Factory.SixtySecondTimeout)
/** This test takes 30s+ on a Docker server environment and should be skipped for now */
it.skip('should handle downloading with sync pagination', async function () {
const largeItemCount = SyncUpDownLimit + 10
for (let i = 0; i < largeItemCount; i++) {
const note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
}
/** Upload */
application.sync.sync({ awaitAll: true, checkIntegrity: false })
await context.awaitNextSucessfulSync()
expectedItemCount += largeItemCount
/** Clear local data */
await application.payloads.resetState()
await application.items.resetState()
await application.sync.clearSyncPositionTokens()
await application.storage.clearAllPayloads()
expect(application.items.items.length).to.equal(0)
/** Download all data */
application.sync.sync(syncOptions)
await context.awaitNextSucessfulSync()
expect(application.items.items.length).to.equal(expectedItemCount)
const rawPayloads = await application.storage.getAllRawPayloads()
expect(rawPayloads.length).to.equal(expectedItemCount)
}).timeout(Factory.SixtySecondTimeout)
it('should sync all items including ones that are breaching transfer limit', async function () {
const response = await fetch('/mocha/assets/small_file.md')
const buffer = new Uint8Array(await response.arrayBuffer())
const numberOfNotesToExceedThe1MBTransferLimit = Math.ceil(100_000 / buffer.length) + 1
const testContext = await Factory.createAppContextWithFakeCrypto()
await testContext.launch()
await testContext.register()
const email = testContext.email
const password = testContext.password
for (let i = 0; i < numberOfNotesToExceedThe1MBTransferLimit; i++) {
await testContext.createSyncedNote(`note ${i}`, buffer.toString())
await testContext.sync()
}
await testContext.deinit()
const secondContext = await Factory.createAppContextWithFakeCrypto(Math.random(), email, password)
await secondContext.launch()
const firstSyncPromise = secondContext.awaitNextSyncEvent(SyncEvent.PaginatedSyncRequestCompleted)
await secondContext.signIn()
const firstSyncResult = await firstSyncPromise
expect(firstSyncResult.retrievedPayloads.length > 0).to.be.true
expect(firstSyncResult.retrievedPayloads.length < numberOfNotesToExceedThe1MBTransferLimit).to.be.true
expect(firstSyncResult.successResponseData.cursor_token).not.to.be.undefined
expect(secondContext.noteCount).to.equal(numberOfNotesToExceedThe1MBTransferLimit)
await secondContext.deinit()
}).timeout(Factory.SixtySecondTimeout)
it('syncing an item should storage it encrypted', async function () {
const note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
await application.sync.sync(syncOptions)
expectedItemCount++
const rawPayloads = await application.storage.getAllRawPayloads()
const notePayload = rawPayloads.find((p) => p.content_type === ContentType.TYPES.Note)
expect(typeof notePayload.content).to.equal('string')
})
it('syncing an item before data load should storage it encrypted', async function () {
const note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
expectedItemCount++
/** Simulate database not loaded */
await application.sync.clearSyncPositionTokens()
application.sync.ut_setDatabaseLoaded(false)
application.sync.sync(syncOptions)
await Factory.sleep(0.3)
const rawPayloads = await application.storage.getAllRawPayloads()
const notePayload = rawPayloads.find((p) => p.content_type === ContentType.TYPES.Note)
expect(typeof notePayload.content).to.equal('string')
})
it('saving an item after sync should persist it with content property', async function () {
const note = await Factory.createMappedNote(application)
const text = Factory.randomString(10000)
await application.changeAndSaveItem.execute(
note,
(mutator) => {
mutator.text = text
},
undefined,
undefined,
syncOptions,
)
expectedItemCount++
const rawPayloads = await application.storage.getAllRawPayloads()
const notePayload = rawPayloads.find((p) => p.content_type === ContentType.TYPES.Note)
expect(typeof notePayload.content).to.equal('string')
expect(notePayload.content.length).to.be.above(text.length)
})
it('syncing a new item before local data has loaded should still persist the item to disk', async function () {
application.sync.ut_setDatabaseLoaded(false)
/** You don't want to clear model manager state as we'll lose encrypting items key */
// await application.payloads.resetState();
await application.sync.clearSyncPositionTokens()
expect(application.items.getDirtyItems().length).to.equal(0)
let note = await Factory.createMappedNote(application)
note = await application.mutator.changeItem(note, (mutator) => {
mutator.text = `${Math.random()}`
})
/** This sync request should exit prematurely as we called ut_setDatabaseNotLoaded */
/** Do not await. Sleep instead. */
application.sync.sync(syncOptions)
await Factory.sleep(0.3)
expectedItemCount++
/** Item should still be dirty */
expect(note.dirty).to.equal(true)
expect(application.items.getDirtyItems().length).to.equal(1)
const rawPayloads = await application.storage.getAllRawPayloads()
expect(rawPayloads.length).to.equal(expectedItemCount)
const rawPayload = rawPayloads.find((p) => p.uuid === note.uuid)
expect(rawPayload.uuid).to.equal(note.uuid)
expect(rawPayload.dirty).equal(true)
expect(typeof rawPayload.content).to.equal('string')
/** Clear state data and upload item from storage to server */
await application.sync.clearSyncPositionTokens()
await application.payloads.resetState()
await application.items.resetState()
await application.sync.loadDatabasePayloads()
await application.sync.sync(syncOptions)
const newRawPayloads = await application.storage.getAllRawPayloads()
expect(newRawPayloads.length).to.equal(expectedItemCount)
const currentItem = application.items.findItem(note.uuid)
expect(currentItem.content.text).to.equal(note.content.text)
expect(currentItem.text).to.equal(note.text)
expect(currentItem.dirty).to.not.be.ok
})
it('load local items should respect sort priority', function () {
const contentTypes = ['A', 'B', 'C']
const itemCount = 6
const originalPayloads = []
for (let i = 0; i < itemCount; i++) {
const payload = Factory.createStorageItemPayload(contentTypes[Math.floor(i / 2)])
originalPayloads.push(payload)
}
const { contentTypePriorityPayloads } = GetSortedPayloadsByPriority(originalPayloads, {
contentTypePriority: ['C', 'A', 'B'],
})
expect(contentTypePriorityPayloads[0].content_type).to.equal('C')
expect(contentTypePriorityPayloads[2].content_type).to.equal('A')
expect(contentTypePriorityPayloads[4].content_type).to.equal('B')
})
it('should sign in and retrieve large number of items', async function () {
const largeItemCount = 50
await Factory.createManyMappedNotes(application, largeItemCount)
expectedItemCount += largeItemCount
await application.sync.sync(syncOptions)
application = await Factory.signOutApplicationAndReturnNew(application)
await application.signIn(email, password, undefined, undefined, undefined, true)
application.sync.ut_setDatabaseLoaded(false)
await application.sync.loadDatabasePayloads()
await application.sync.sync(syncOptions)
const items = await application.items.items
expect(items.length).to.equal(expectedItemCount)
}).timeout(20000)
it('valid sync date tracking', async function () {
let note = await Factory.createMappedNote(application)
note = await application.mutator.setItemDirty(note)
expectedItemCount++
expect(note.dirty).to.equal(true)
expect(note.payload.dirtyIndex).to.be.at.most(getCurrentDirtyIndex())
note = await application.mutator.changeItem(note, (mutator) => {
mutator.text = `${Math.random()}`
})
const sync = application.sync.sync(syncOptions)
await Factory.sleep(0.1)
note = application.items.findItem(note.uuid)
expect(note.lastSyncBegan).to.be.below(new Date())
await sync
note = application.items.findItem(note.uuid)
expect(note.dirty).to.equal(false)
expect(note.lastSyncEnd).to.be.at.least(note.lastSyncBegan)
})
it('syncing twice without waiting should only execute 1 online sync', async function () {
const expectedEvents = 1
let actualEvents = 0
application.sync.addEventObserver((event, data) => {
if (event === SyncEvent.SyncCompletedWithAllItemsUploaded && data.source === SyncSource.External) {
actualEvents++
}
})
const first = application.sync.sync()
const second = application.sync.sync()
await Promise.all([first, second])
/** Sleep so that any automatic syncs that are triggered are also sent to handler above */
await Factory.sleep(0.5)
expect(actualEvents).to.equal(expectedEvents)
})
it('should keep an item dirty thats been modified after low latency sync request began', async function () {
/**
* If you begin a sync request that takes 20s to complete, then begin modifying an item
* many times and attempt to sync, it will await the initial sync to complete.
* When that completes, it will decide whether an item is still dirty or not.
* It will do based on comparing whether item.dirtyIndex > item.globalDirtyIndexAtLastSync
*/
let note = await Factory.createMappedNote(application)
await application.mutator.setItemDirty(note)
expectedItemCount++
// client A. Don't await, we want to do other stuff.
application.sync.ut_beginLatencySimulator(1500)
const slowSync = application.sync.sync(syncOptions)
await Factory.sleep(0.1)
expect(note.dirty).to.equal(true)
// While that sync is going on, we want to modify this item many times.
const text = `${Math.random()}`
note = await application.mutator.changeItem(note, (mutator) => {
mutator.text = text
})
await application.mutator.setItemDirty(note)
await application.mutator.setItemDirty(note)
await application.mutator.setItemDirty(note)
expect(note.payload.dirtyIndex).to.be.above(note.payload.globalDirtyIndexAtLastSync)
// Now do a regular sync with no latency.
application.sync.ut_endLatencySimulator()
const midSync = application.sync.sync(syncOptions)
await slowSync
await midSync
note = application.items.findItem(note.uuid)
expect(note.dirty).to.equal(false)
expect(note.lastSyncEnd).to.be.above(note.lastSyncBegan)
expect(note.content.text).to.equal(text)
// client B
await application.payloads.resetState()
await application.items.resetState()
await application.sync.clearSyncPositionTokens()
await application.sync.sync(syncOptions)
// Expect that the server value and client value match, and no conflicts are created.
expect(application.items.items.length).to.equal(expectedItemCount)
const foundItem = application.items.findItem(note.uuid)
expect(foundItem.content.text).to.equal(text)
expect(foundItem.text).to.equal(text)
})
it('should sync an item twice if its marked dirty while a sync is ongoing', async function () {
/** We can't track how many times an item is synced, only how many times its mapped */
const expectedSaveCount = 2
let actualSaveCount = 0
/** Create an item and sync it */
let note = await Factory.createMappedNote(application)
application.items.addObserver(ContentType.TYPES.Note, ({ source }) => {
if (source === PayloadEmitSource.RemoteSaved) {
actualSaveCount++
}
})
expectedItemCount++
application.sync.ut_beginLatencySimulator(150)
/** Dont await */
const syncRequest = application.sync.sync(syncOptions)
/** Dirty the item 100ms into 150ms request */
const newText = `${Math.random()}`
setTimeout(
async function () {
await application.mutator.changeItem(note, (mutator) => {
mutator.text = newText
})
}.bind(this),
100,
)
/**
* Await sync request. A sync request will perform another request if there
* are still more dirty items, so awaiting this will perform two syncs.
*/
await syncRequest
expect(actualSaveCount).to.equal(expectedSaveCount)
note = application.items.findItem(note.uuid)
expect(note.text).to.equal(newText)
})
it('marking item dirty after dirty items are prepared for sync but before they are synced should sync again', async function () {
/**
* There is a twilight zone where items needing sync are popped, and then say about 100ms of processing before
* we set those items' lastSyncBegan. If the item is dirtied in between these times, then item.dirtyIndex will be less than
* item.globalDirtyIndexAtLastSync, and it will not by synced again.
*/
const expectedSaveCount = 2
let actualSaveCount = 0
/** Create an item and sync it */
let note = await Factory.createMappedNote(application)
application.items.addObserver(ContentType.TYPES.Note, ({ source }) => {
if (source === PayloadEmitSource.RemoteSaved) {
actualSaveCount++
}
})
expectedItemCount++
/** Dont await */
const syncRequest = application.sync.sync(syncOptions)
/** Dirty the item before lastSyncBegan is set */
let didPerformMutatation = false
const newText = `${Math.random()}`
application.sync.addEventObserver(async (eventName) => {
if (eventName === SyncEvent.SyncDidBeginProcessing && !didPerformMutatation) {
didPerformMutatation = true
await application.mutator.changeItem(note, (mutator) => {
mutator.text = newText
})
}
})
await syncRequest
expect(actualSaveCount).to.equal(expectedSaveCount)
note = application.items.findItem(note.uuid)
expect(note.text).to.equal(newText)
})
it('marking item dirty during presync save should sync again', async function () {
const expectedSaveCount = 2
let actualSaveCount = 0
/** Create an item and sync it */
let note = await Factory.createMappedNote(application)
let didPerformMutatation = false
const newText = `${Math.random()}`
application.items.addObserver(ContentType.TYPES.Note, async ({ changed, source }) => {
if (source === PayloadEmitSource.RemoteSaved) {
actualSaveCount++
} else if (source === PayloadEmitSource.PreSyncSave && !didPerformMutatation) {
didPerformMutatation = true
const mutated = changed[0].payload.copy({
content: { ...note.payload.content, text: newText },
dirty: true,
dirtyIndex: changed[0].payload.globalDirtyIndexAtLastSync + 1,
})
await application.mutator.emitItemFromPayload(mutated)
}
})
expectedItemCount++
/** Dont await */
const syncRequest = application.sync.sync(syncOptions)
await syncRequest
expect(actualSaveCount).to.equal(expectedSaveCount)
note = application.items.findItem(note.uuid)
expect(note.text).to.equal(newText)
})
it('retreiving a remote deleted item should succeed', async function () {
const note = await Factory.createSyncedNote(application)
const preDeleteSyncToken = await application.sync.getLastSyncToken()
await application.mutator.deleteItem(note)
await application.sync.sync()
await application.sync.setLastSyncToken(preDeleteSyncToken)
await application.sync.sync(syncOptions)
expect(application.items.items.length).to.equal(expectedItemCount)
})
it('errored items should not be synced', async function () {
const note = await Factory.createSyncedNote(application)
expectedItemCount++
const lastSyncBegan = note.lastSyncBegan
const lastSyncEnd = note.lastSyncEnd
const encrypted = await application.encryption.encryptSplitSingle({
usesItemsKeyWithKeyLookup: {
items: [note.payload],
},
})
const errored = encrypted.copy({
errorDecrypting: true,
dirty: true,
})
await application.payloads.emitPayload(errored)
await application.sync.sync(syncOptions)
const updatedNote = application.items.findAnyItem(note.uuid)
expect(updatedNote.lastSyncBegan.getTime()).to.equal(lastSyncBegan.getTime())
expect(updatedNote.lastSyncEnd.getTime()).to.equal(lastSyncEnd.getTime())
})
it('should not allow receiving decrypted payloads from server', async function () {
const invalidPayload = new DecryptedPayload(
{ ...Factory.createNotePayload(), uuid: 'rejected' },
PayloadSource.RemoteRetrieved,
)