-
-
Notifications
You must be signed in to change notification settings - Fork 393
/
SyncService.ts
1465 lines (1210 loc) · 45.6 KB
/
SyncService.ts
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 { ConflictParams, ConflictType } from '@standardnotes/responses'
import { log, LoggingDomain } from './../../Logging'
import { AccountSyncOperation } from '@Lib/Services/Sync/Account/Operation'
import { ContentType } from '@standardnotes/common'
import {
Uuids,
extendArray,
isNotUndefined,
isNullOrUndefined,
removeFromIndex,
sleep,
subtractFromArray,
} from '@standardnotes/utils'
import { ItemManager } from '@Lib/Services/Items/ItemManager'
import { OfflineSyncOperation } from '@Lib/Services/Sync/Offline/Operation'
import { PayloadManager } from '../Payloads/PayloadManager'
import { SNApiService } from '../Api/ApiService'
import { SNHistoryManager } from '../History/HistoryManager'
import { SNLog } from '@Lib/Log'
import { SNSessionManager } from '../Session/SessionManager'
import { DiskStorageService } from '../Storage/DiskStorageService'
import { SyncClientInterface } from './SyncClientInterface'
import { SyncPromise } from './Types'
import { SyncOpStatus } from '@Lib/Services/Sync/SyncOpStatus'
import { ServerSyncResponse } from '@Lib/Services/Sync/Account/Response'
import { ServerSyncResponseResolver } from '@Lib/Services/Sync/Account/ResponseResolver'
import { SyncSignal, SyncStats } from '@Lib/Services/Sync/Signals'
import { UuidString } from '../../Types/UuidString'
import {
PayloadSource,
CreateDecryptedItemFromPayload,
FilterDisallowedRemotePayloadsAndMap,
DeltaOutOfSync,
ImmutablePayloadCollection,
CreatePayload,
isEncryptedPayload,
isDecryptedPayload,
EncryptedPayloadInterface,
DecryptedPayloadInterface,
ItemsKeyContent,
FullyFormedPayloadInterface,
DeletedPayloadInterface,
DecryptedPayload,
CreateEncryptedServerSyncPushPayload,
ServerSyncPushContextualPayload,
isDeletedItem,
DeletedItemInterface,
DecryptedItemInterface,
CreatePayloadSplit,
CreateDeletedServerSyncPushPayload,
ItemsKeyInterface,
CreateNonDecryptedPayloadSplit,
DeltaOfflineSaved,
FilteredServerItem,
PayloadEmitSource,
getIncrementedDirtyIndex,
getCurrentDirtyIndex,
ItemContent,
KeySystemItemsKeyContent,
KeySystemItemsKeyInterface,
FullyFormedTransferPayload,
ItemMutator,
isDecryptedOrDeletedItem,
MutationType,
} from '@standardnotes/models'
import {
AbstractService,
SyncEvent,
SyncSource,
InternalEventHandlerInterface,
InternalEventBusInterface,
StorageKey,
InternalEventInterface,
IntegrityEvent,
IntegrityEventPayload,
SyncMode,
SyncOptions,
SyncQueueStrategy,
SyncServiceInterface,
EncryptionService,
DeviceInterface,
isFullEntryLoadChunkResponse,
isChunkFullEntry,
SyncEventReceivedSharedVaultInvitesData,
SyncEventReceivedRemoteSharedVaultsData,
SyncEventReceivedUserEventsData,
SyncEventReceivedAsymmetricMessagesData,
} from '@standardnotes/services'
import { OfflineSyncResponse } from './Offline/Response'
import {
CreateDecryptionSplitWithKeyLookup,
CreateEncryptionSplitWithKeyLookup,
KeyedDecryptionSplit,
SplitPayloadsByEncryptionType,
} from '@standardnotes/encryption'
import { CreatePayloadFromRawServerItem } from './Account/Utilities'
import { ApplicationSyncOptions } from '@Lib/Application/Options/OptionalOptions'
import { DecryptedServerConflictMap, TrustedServerConflictMap } from './Account/ServerConflictMap'
const DEFAULT_MAJOR_CHANGE_THRESHOLD = 15
const INVALID_SESSION_RESPONSE_STATUS = 401
/** Content types appearing first are always mapped first */
const ContentTypeLocalLoadPriorty = [
ContentType.ItemsKey,
ContentType.KeySystemRootKey,
ContentType.KeySystemItemsKey,
ContentType.VaultListing,
ContentType.TrustedContact,
ContentType.UserPrefs,
ContentType.Component,
ContentType.Theme,
]
/**
* The sync service orchestrates with the model manager, api service, and storage service
* to ensure consistent state between the three. When a change is made to an item, consumers
* call the sync service's sync function to first persist pending changes to local storage.
* Then, the items are uploaded to the server. The sync service handles server responses,
* including mapping any retrieved items to application state via model manager mapping.
* After each sync request, any changes made or retrieved are also persisted locally.
* The sync service largely does not perform any task unless it is called upon.
*/
export class SNSyncService
extends AbstractService<SyncEvent>
implements SyncServiceInterface, InternalEventHandlerInterface, SyncClientInterface
{
private dirtyIndexAtLastPresyncSave?: number
private lastSyncDate?: Date
private outOfSync = false
private opStatus: SyncOpStatus
private resolveQueue: SyncPromise[] = []
private spawnQueue: SyncPromise[] = []
/* A DownloadFirst sync must always be the first sync completed */
public completedOnlineDownloadFirstSync = false
private majorChangeThreshold = DEFAULT_MAJOR_CHANGE_THRESHOLD
private clientLocked = false
private databaseLoaded = false
private syncToken?: string
private cursorToken?: string
private syncLock = false
private _simulate_latency?: { latency: number; enabled: boolean }
private dealloced = false
public lastSyncInvokationPromise?: Promise<unknown>
public currentSyncRequestPromise?: Promise<void>
constructor(
private itemManager: ItemManager,
private sessionManager: SNSessionManager,
private protocolService: EncryptionService,
private storageService: DiskStorageService,
private payloadManager: PayloadManager,
private apiService: SNApiService,
private historyService: SNHistoryManager,
private device: DeviceInterface,
private identifier: string,
private readonly options: ApplicationSyncOptions,
protected override internalEventBus: InternalEventBusInterface,
) {
super(internalEventBus)
this.opStatus = this.initializeStatus()
}
/**
* If the database has been newly created (because its new or was previously destroyed)
* we want to reset any sync tokens we have.
*/
public async onNewDatabaseCreated(): Promise<void> {
if (await this.getLastSyncToken()) {
await this.clearSyncPositionTokens()
}
}
private get launchPriorityUuids() {
return this.storageService.getValue<string[]>(StorageKey.LaunchPriorityUuids) ?? []
}
public setLaunchPriorityUuids(launchPriorityUuids: string[]) {
this.storageService.setValue(StorageKey.LaunchPriorityUuids, launchPriorityUuids)
}
public override deinit(): void {
this.dealloced = true
;(this.sessionManager as unknown) = undefined
;(this.itemManager as unknown) = undefined
;(this.protocolService as unknown) = undefined
;(this.payloadManager as unknown) = undefined
;(this.storageService as unknown) = undefined
;(this.apiService as unknown) = undefined
this.opStatus.reset()
;(this.opStatus as unknown) = undefined
this.resolveQueue.length = 0
this.spawnQueue.length = 0
super.deinit()
}
private initializeStatus() {
return new SyncOpStatus(setInterval, (event) => {
void this.notifyEvent(event)
})
}
public lockSyncing(): void {
this.clientLocked = true
}
public unlockSyncing(): void {
this.clientLocked = false
}
public isOutOfSync(): boolean {
return this.outOfSync
}
public getLastSyncDate(): Date | undefined {
return this.lastSyncDate
}
public getSyncStatus(): SyncOpStatus {
return this.opStatus
}
/**
* Called by application when sign in or registration occurs.
*/
public resetSyncState(): void {
this.dirtyIndexAtLastPresyncSave = undefined
this.lastSyncDate = undefined
this.outOfSync = false
}
public isDatabaseLoaded(): boolean {
return this.databaseLoaded
}
private async processPriorityItemsForDatabaseLoad(items: FullyFormedPayloadInterface[]): Promise<void> {
if (items.length === 0) {
return
}
const encryptedPayloads = items.filter(isEncryptedPayload)
const alreadyDecryptedPayloads = items.filter(isDecryptedPayload) as DecryptedPayloadInterface<ItemsKeyContent>[]
const encryptionSplit = SplitPayloadsByEncryptionType(encryptedPayloads)
const decryptionSplit = CreateDecryptionSplitWithKeyLookup(encryptionSplit)
const newlyDecryptedPayloads = await this.protocolService.decryptSplit(decryptionSplit)
await this.payloadManager.emitPayloads(
[...alreadyDecryptedPayloads, ...newlyDecryptedPayloads],
PayloadEmitSource.LocalDatabaseLoaded,
)
}
public async loadDatabasePayloads(): Promise<void> {
log(LoggingDomain.DatabaseLoad, 'Loading database payloads')
if (this.databaseLoaded) {
throw 'Attempting to initialize already initialized local database.'
}
const chunks = await this.device.getDatabaseLoadChunks(
{
batchSize: this.options.loadBatchSize,
contentTypePriority: ContentTypeLocalLoadPriorty,
uuidPriority: this.launchPriorityUuids,
},
this.identifier,
)
const itemsKeyEntries = isFullEntryLoadChunkResponse(chunks)
? chunks.fullEntries.itemsKeys.entries
: await this.device.getDatabaseEntries(this.identifier, chunks.keys.itemsKeys.keys)
const keySystemRootKeyEntries = isFullEntryLoadChunkResponse(chunks)
? chunks.fullEntries.keySystemRootKeys.entries
: await this.device.getDatabaseEntries(this.identifier, chunks.keys.keySystemRootKeys.keys)
const keySystemItemsKeyEntries = isFullEntryLoadChunkResponse(chunks)
? chunks.fullEntries.keySystemItemsKeys.entries
: await this.device.getDatabaseEntries(this.identifier, chunks.keys.keySystemItemsKeys.keys)
const createPayloadFromEntry = (entry: FullyFormedTransferPayload) => {
try {
return CreatePayload(entry, PayloadSource.LocalDatabaseLoaded)
} catch (e) {
console.error('Creating payload failed', e)
return undefined
}
}
await this.processPriorityItemsForDatabaseLoad(itemsKeyEntries.map(createPayloadFromEntry).filter(isNotUndefined))
await this.processPriorityItemsForDatabaseLoad(
keySystemRootKeyEntries.map(createPayloadFromEntry).filter(isNotUndefined),
)
await this.processPriorityItemsForDatabaseLoad(
keySystemItemsKeyEntries.map(createPayloadFromEntry).filter(isNotUndefined),
)
/**
* Map in batches to give interface a chance to update. Note that total decryption
* time is constant regardless of batch size. Decrypting 3000 items all at once or in
* batches will result in the same time spent. It's the emitting/painting/rendering
* that requires batch size optimization.
*/
const payloadCount = chunks.remainingChunksItemCount
let totalProcessedCount = 0
const remainingChunks = isFullEntryLoadChunkResponse(chunks)
? chunks.fullEntries.remainingChunks
: chunks.keys.remainingChunks
let chunkIndex = 0
const ChunkIndexOfContentTypePriorityItems = 0
for (const chunk of remainingChunks) {
const dbEntries = isChunkFullEntry(chunk)
? chunk.entries
: await this.device.getDatabaseEntries(this.identifier, chunk.keys)
const payloads = dbEntries
.map((entry) => {
try {
return CreatePayload(entry, PayloadSource.LocalDatabaseLoaded)
} catch (e) {
console.error('Creating payload failed', e)
return undefined
}
})
.filter(isNotUndefined)
await this.processPayloadBatch(payloads, totalProcessedCount, payloadCount)
const shouldSleepOnlyAfterFirstRegularBatch = chunkIndex > ChunkIndexOfContentTypePriorityItems
if (shouldSleepOnlyAfterFirstRegularBatch) {
await sleep(this.options.sleepBetweenBatches, false, 'Sleeping to allow interface to update')
}
totalProcessedCount += payloads.length
chunkIndex++
}
this.databaseLoaded = true
this.opStatus.setDatabaseLoadStatus(0, 0, true)
}
private async processPayloadBatch(
batch: FullyFormedPayloadInterface<ItemContent>[],
currentPosition?: number,
payloadCount?: number,
) {
log(LoggingDomain.DatabaseLoad, 'Processing batch at index', currentPosition, 'length', batch.length)
const encrypted: EncryptedPayloadInterface[] = []
const nonencrypted: (DecryptedPayloadInterface | DeletedPayloadInterface)[] = []
for (const payload of batch) {
if (isEncryptedPayload(payload)) {
encrypted.push(payload)
} else {
nonencrypted.push(payload)
}
}
const encryptionSplit = SplitPayloadsByEncryptionType(encrypted)
const decryptionSplit = CreateDecryptionSplitWithKeyLookup(encryptionSplit)
const results = await this.protocolService.decryptSplit(decryptionSplit)
await this.payloadManager.emitPayloads([...nonencrypted, ...results], PayloadEmitSource.LocalDatabaseLoaded)
void this.notifyEvent(SyncEvent.LocalDataIncrementalLoad)
if (currentPosition != undefined && payloadCount != undefined) {
this.opStatus.setDatabaseLoadStatus(currentPosition, payloadCount, false)
}
}
private setLastSyncToken(token: string) {
this.syncToken = token
return this.storageService.setValue(StorageKey.LastSyncToken, token)
}
private async setPaginationToken(token: string) {
this.cursorToken = token
if (token) {
return this.storageService.setValue(StorageKey.PaginationToken, token)
} else {
return this.storageService.removeValue(StorageKey.PaginationToken)
}
}
private async getLastSyncToken(): Promise<string> {
if (!this.syncToken) {
this.syncToken = (await this.storageService.getValue(StorageKey.LastSyncToken)) as string
}
return this.syncToken
}
private async getPaginationToken(): Promise<string> {
if (!this.cursorToken) {
this.cursorToken = (await this.storageService.getValue(StorageKey.PaginationToken)) as string
}
return this.cursorToken
}
private async clearSyncPositionTokens() {
this.syncToken = undefined
this.cursorToken = undefined
await this.storageService.removeValue(StorageKey.LastSyncToken)
await this.storageService.removeValue(StorageKey.PaginationToken)
}
private itemsNeedingSync() {
return this.itemManager.getDirtyItems()
}
public async markAllItemsAsNeedingSyncAndPersist(): Promise<void> {
log(LoggingDomain.Sync, 'Marking all items as needing sync')
const items = this.itemManager.items
const payloads = items.map((item) => {
return new DecryptedPayload({
...item.payload.ejected(),
dirty: true,
dirtyIndex: getIncrementedDirtyIndex(),
})
})
await this.payloadManager.emitPayloads(payloads, PayloadEmitSource.LocalChanged)
/**
* When signing into an 003 account (or an account that is not the latest), the temporary items key will be 004
* and will not match user account version, triggering a key not found exception. This error resolves once the
* download first sync completes and the correct key is downloaded. We suppress any persistence
* exceptions here to avoid showing an error to the user.
*/
const hidePersistErrorDueToWaitingOnKeyDownload = true
await this.persistPayloads(payloads, { throwError: !hidePersistErrorDueToWaitingOnKeyDownload })
}
/**
* Return the payloads that need local persistence, before beginning a sync.
* This way, if the application is closed before a sync request completes,
* pending data will be saved to disk, and synced the next time the app opens.
*/
private popPayloadsNeedingPreSyncSave(from: (DecryptedPayloadInterface | DeletedPayloadInterface)[]) {
const lastPreSyncSave = this.dirtyIndexAtLastPresyncSave
if (lastPreSyncSave == undefined) {
return from
}
const payloads = from.filter((candidate) => {
return !candidate.dirtyIndex || candidate.dirtyIndex > lastPreSyncSave
})
this.dirtyIndexAtLastPresyncSave = getCurrentDirtyIndex()
return payloads
}
private queueStrategyResolveOnNext(): Promise<unknown> {
return new Promise((resolve, reject) => {
this.resolveQueue.push({ resolve, reject })
})
}
private queueStrategyForceSpawnNew(options: SyncOptions) {
return new Promise((resolve, reject) => {
this.spawnQueue.push({ resolve, reject, options })
})
}
/**
* For timing strategy SyncQueueStrategy.ForceSpawnNew, we will execute a whole sync request
* and pop it from the queue.
*/
private popSpawnQueue() {
if (this.spawnQueue.length === 0) {
return null
}
const promise = this.spawnQueue[0]
removeFromIndex(this.spawnQueue, 0)
log(LoggingDomain.Sync, 'Syncing again from spawn queue')
return this.sync({
queueStrategy: SyncQueueStrategy.ForceSpawnNew,
source: SyncSource.SpawnQueue,
...promise.options,
})
.then(() => {
promise.resolve()
})
.catch(() => {
promise.reject()
})
}
private async payloadsByPreparingForServer(
payloads: (DecryptedPayloadInterface | DeletedPayloadInterface)[],
): Promise<ServerSyncPushContextualPayload[]> {
const payloadSplit = CreatePayloadSplit(payloads)
const encryptionSplit = SplitPayloadsByEncryptionType(payloadSplit.decrypted)
const keyLookupSplit = CreateEncryptionSplitWithKeyLookup(encryptionSplit)
const encryptedResults = await this.protocolService.encryptSplit(keyLookupSplit)
const contextPayloads = [
...encryptedResults.map(CreateEncryptedServerSyncPushPayload),
...payloadSplit.deleted.map(CreateDeletedServerSyncPushPayload),
]
return contextPayloads
}
public async downloadFirstSync(waitTimeOnFailureMs: number, otherSyncOptions?: Partial<SyncOptions>): Promise<void> {
const maxTries = 5
for (let i = 0; i < maxTries; i++) {
await this.sync({
mode: SyncMode.DownloadFirst,
queueStrategy: SyncQueueStrategy.ForceSpawnNew,
source: SyncSource.External,
...otherSyncOptions,
}).catch(console.error)
if (this.completedOnlineDownloadFirstSync) {
return
} else {
await sleep(waitTimeOnFailureMs)
}
}
console.error(`Failed downloadFirstSync after ${maxTries} tries`)
}
public async awaitCurrentSyncs(): Promise<void> {
await this.lastSyncInvokationPromise
await this.currentSyncRequestPromise
}
public async sync(options: Partial<SyncOptions> = {}): Promise<unknown> {
if (this.clientLocked) {
log(LoggingDomain.Sync, 'Sync locked by client')
return
}
const fullyResolvedOptions: SyncOptions = {
source: SyncSource.External,
...options,
}
this.lastSyncInvokationPromise = this.performSync(fullyResolvedOptions)
return this.lastSyncInvokationPromise
}
private async prepareForSync(options: SyncOptions) {
const items = this.itemsNeedingSync()
/**
* Freeze the begin date immediately after getting items needing sync. This way an
* item dirtied at any point after this date is marked as needing another sync
*/
const beginDate = new Date()
const frozenDirtyIndex = getCurrentDirtyIndex()
/**
* Items that have never been synced and marked as deleted should not be
* uploaded to server, and instead deleted directly after sync completion.
*/
const neverSyncedDeleted: DeletedItemInterface[] = items.filter((item) => {
return item.neverSynced && isDeletedItem(item)
}) as DeletedItemInterface[]
subtractFromArray(items, neverSyncedDeleted)
const decryptedPayloads = items.map((item) => {
return item.payloadRepresentation()
})
const payloadsNeedingSave = this.popPayloadsNeedingPreSyncSave(decryptedPayloads)
const hidePersistErrorDueToWaitingOnKeyDownload = options.mode === SyncMode.DownloadFirst
await this.persistPayloads(payloadsNeedingSave, { throwError: !hidePersistErrorDueToWaitingOnKeyDownload })
if (options.onPresyncSave) {
options.onPresyncSave()
}
return { items, beginDate, frozenDirtyIndex, neverSyncedDeleted }
}
/**
* Allows us to lock this function from triggering duplicate network requests.
* There are two types of locking checks:
* 1. syncLocked(): If a call to sync() call has begun preparing to be sent to the server.
* but not yet completed all the code below before reaching that point.
* (before reaching opStatus.setDidBegin).
* 2. syncOpInProgress: If a sync() call is in flight to the server.
*/
private configureSyncLock(options: SyncOptions) {
const syncInProgress = this.opStatus.syncInProgress
const databaseLoaded = this.databaseLoaded
const canExecuteSync = !this.syncLock
const shouldExecuteSync = canExecuteSync && databaseLoaded && !syncInProgress
if (shouldExecuteSync) {
this.syncLock = true
} else {
log(
LoggingDomain.Sync,
!canExecuteSync
? 'Another function call has begun preparing for sync.'
: syncInProgress
? 'Attempting to sync while existing sync in progress.'
: 'Attempting to sync before local database has loaded.',
options,
)
}
const releaseLock = () => {
this.syncLock = false
}
return { shouldExecuteSync, releaseLock }
}
private deferSyncRequest(options: SyncOptions) {
const useStrategy = !isNullOrUndefined(options.queueStrategy)
? options.queueStrategy
: SyncQueueStrategy.ResolveOnNext
if (useStrategy === SyncQueueStrategy.ResolveOnNext) {
return this.queueStrategyResolveOnNext()
} else if (useStrategy === SyncQueueStrategy.ForceSpawnNew) {
return this.queueStrategyForceSpawnNew(options)
} else {
throw Error(`Unhandled timing strategy ${useStrategy}`)
}
}
private async prepareForSyncExecution(
items: (DecryptedItemInterface | DeletedItemInterface)[],
inTimeResolveQueue: SyncPromise[],
beginDate: Date,
frozenDirtyIndex: number,
) {
this.opStatus.setDidBegin()
await this.notifyEvent(SyncEvent.SyncDidBeginProcessing)
/**
* Subtract from array as soon as we're sure they'll be called.
* resolves are triggered at the end of this function call
*/
subtractFromArray(this.resolveQueue, inTimeResolveQueue)
/**
* lastSyncBegan must be set *after* any point we may have returned above.
* Setting this value means the item was 100% sent to the server.
*/
if (items.length > 0) {
return this.setLastSyncBeganForItems(items, beginDate, frozenDirtyIndex)
} else {
return items
}
}
private async setLastSyncBeganForItems(
itemsToLookupUuidsFor: (DecryptedItemInterface | DeletedItemInterface)[],
date: Date,
globalDirtyIndex: number,
): Promise<(DecryptedItemInterface | DeletedItemInterface)[]> {
const uuids = Uuids(itemsToLookupUuidsFor)
const items = this.itemManager.getCollection().findAll(uuids).filter(isDecryptedOrDeletedItem)
const payloads: (DecryptedPayloadInterface | DeletedPayloadInterface)[] = []
for (const item of items) {
const mutator = new ItemMutator<DecryptedPayloadInterface | DeletedPayloadInterface>(
item,
MutationType.NonDirtying,
)
mutator.setBeginSync(date, globalDirtyIndex)
const payload = mutator.getResult()
payloads.push(payload)
}
await this.payloadManager.emitPayloads(payloads, PayloadEmitSource.PreSyncSave)
return this.itemManager.findAnyItems(uuids) as (DecryptedItemInterface | DeletedItemInterface)[]
}
/**
* The InTime resolve queue refers to any sync requests that were made while we still
* have not sent out the current request. So, anything in the InTime resolve queue
* will have made it "in time" to piggyback on the current request. Anything that comes
* after InTime will schedule a new sync request.
*/
private getPendingRequestsMadeInTimeToPiggyBackOnCurrentRequest() {
return this.resolveQueue.slice()
}
private getOfflineSyncParameters(
payloads: (DecryptedPayloadInterface | DeletedPayloadInterface)[],
mode: SyncMode = SyncMode.Default,
): {
uploadPayloads: (DecryptedPayloadInterface | DeletedPayloadInterface)[]
} {
const uploadPayloads: (DecryptedPayloadInterface | DeletedPayloadInterface)[] =
mode === SyncMode.Default ? payloads : []
return { uploadPayloads }
}
private createOfflineSyncOperation(
payloads: (DeletedPayloadInterface | DecryptedPayloadInterface)[],
options: SyncOptions,
) {
log(
LoggingDomain.Sync,
'Syncing offline user',
'source:',
SyncSource[options.source],
'sourceDesc',
options.sourceDescription,
'mode:',
options.mode && SyncMode[options.mode],
'payloads:',
payloads,
)
const operation = new OfflineSyncOperation(payloads, async (type, response) => {
if (this.dealloced) {
return
}
if (type === SyncSignal.Response && response) {
await this.handleOfflineResponse(response)
}
})
return operation
}
private async getOnlineSyncParameters(
payloads: (DecryptedPayloadInterface | DeletedPayloadInterface)[],
mode: SyncMode = SyncMode.Default,
): Promise<{
uploadPayloads: ServerSyncPushContextualPayload[]
syncMode: SyncMode
}> {
const useMode = !this.completedOnlineDownloadFirstSync ? SyncMode.DownloadFirst : mode
if (useMode === SyncMode.Default && !this.completedOnlineDownloadFirstSync) {
throw Error('Attempting to default mode sync without having completed initial.')
}
const uploadPayloads: ServerSyncPushContextualPayload[] =
useMode === SyncMode.Default ? await this.payloadsByPreparingForServer(payloads) : []
return { uploadPayloads, syncMode: useMode }
}
private async createServerSyncOperation(
payloads: ServerSyncPushContextualPayload[],
options: SyncOptions,
mode: SyncMode = SyncMode.Default,
) {
const syncToken =
options.sharedVaultUuids && options.sharedVaultUuids.length > 0 && options.syncSharedVaultsFromScratch
? undefined
: await this.getLastSyncToken()
const paginationToken =
options.sharedVaultUuids && options.syncSharedVaultsFromScratch ? undefined : await this.getPaginationToken()
const operation = new AccountSyncOperation(
payloads,
async (type: SyncSignal, response?: ServerSyncResponse, stats?: SyncStats) => {
switch (type) {
case SyncSignal.Response:
if (this.dealloced) {
return
}
if (response?.hasError) {
this.handleErrorServerResponse(response)
} else if (response) {
await this.handleSuccessServerResponse(operation, response)
}
break
case SyncSignal.StatusChanged:
if (stats) {
this.opStatus.setUploadStatus(stats.completedUploadCount, stats.totalUploadCount)
}
break
}
},
this.apiService,
{
syncToken,
paginationToken,
sharedVaultUuids: options.sharedVaultUuids,
},
)
log(
LoggingDomain.Sync,
'Syncing online user',
'source',
SyncSource[options.source],
'operation id',
operation.id,
'integrity check',
options.checkIntegrity,
'mode',
SyncMode[mode],
'syncToken',
syncToken,
'cursorToken',
paginationToken,
'payloads',
payloads,
)
return operation
}
private async createSyncOperation(
payloads: (DecryptedPayloadInterface | DeletedPayloadInterface)[],
online: boolean,
options: SyncOptions,
): Promise<{ operation: AccountSyncOperation | OfflineSyncOperation; mode: SyncMode }> {
if (online) {
const { uploadPayloads, syncMode } = await this.getOnlineSyncParameters(payloads, options.mode)
return {
operation: await this.createServerSyncOperation(uploadPayloads, options, syncMode),
mode: syncMode,
}
} else {
const { uploadPayloads } = this.getOfflineSyncParameters(payloads, options.mode)
return {
operation: this.createOfflineSyncOperation(uploadPayloads, options),
mode: options.mode || SyncMode.Default,
}
}
}
private async performSync(options: SyncOptions): Promise<unknown> {
const { shouldExecuteSync, releaseLock } = this.configureSyncLock(options)
const { items, beginDate, frozenDirtyIndex, neverSyncedDeleted } = await this.prepareForSync(options)
const inTimeResolveQueue = this.getPendingRequestsMadeInTimeToPiggyBackOnCurrentRequest()
if (!shouldExecuteSync) {
return this.deferSyncRequest(options)
}
if (this.dealloced) {
return
}
const latestItems = await this.prepareForSyncExecution(items, inTimeResolveQueue, beginDate, frozenDirtyIndex)
const online = this.sessionManager.online()
const { operation, mode: syncMode } = await this.createSyncOperation(
latestItems.map((i) => i.payloadRepresentation()),
online,
options,
)
const operationPromise = operation.run()
this.currentSyncRequestPromise = operationPromise
await operationPromise
if (this.dealloced) {
return
}
releaseLock()
const { hasError } = await this.handleSyncOperationFinish(operation, options, neverSyncedDeleted, syncMode)
if (hasError) {
return
}
const didSyncAgain = await this.potentiallySyncAgainAfterSyncCompletion(
syncMode,
options,
inTimeResolveQueue,
online,
)
if (didSyncAgain) {
return
}
if (options.checkIntegrity) {
await this.notifyEventSync(SyncEvent.SyncRequestsIntegrityCheck, {
source: options.source as SyncSource,
})
}
await this.notifyEventSync(SyncEvent.SyncCompletedWithAllItemsUploadedAndDownloaded, {
source: options.source,
options,
})
this.resolvePendingSyncRequestsThatMadeItInTimeOfCurrentRequest(inTimeResolveQueue)
return undefined
}
private async handleOfflineResponse(response: OfflineSyncResponse) {
log(LoggingDomain.Sync, 'Offline Sync Response', response)
const masterCollection = this.payloadManager.getMasterCollection()
const delta = new DeltaOfflineSaved(masterCollection, response.savedPayloads)
const emit = delta.result()
const payloadsToPersist = await this.payloadManager.emitDeltaEmit(emit)
await this.persistPayloads(payloadsToPersist)
this.opStatus.clearError()
await this.notifyEvent(SyncEvent.PaginatedSyncRequestCompleted, response)
}
private handleErrorServerResponse(response: ServerSyncResponse) {
log(LoggingDomain.Sync, 'Sync Error', response)
if (response.status === INVALID_SESSION_RESPONSE_STATUS) {
void this.notifyEvent(SyncEvent.InvalidSession)
}
this.opStatus?.setError(response.error)
void this.notifyEvent(SyncEvent.SyncError, response)
}
private async handleSuccessServerResponse(operation: AccountSyncOperation, response: ServerSyncResponse) {
if (this._simulate_latency) {
await sleep(this._simulate_latency.latency)
}
this.opStatus.clearError()
this.opStatus.setDownloadStatus(response.retrievedPayloads.length)
const masterCollection = this.payloadManager.getMasterCollection()
const historyMap = this.historyService.getHistoryMapCopy()
if (response.userEvents) {
await this.notifyEventSync(SyncEvent.ReceivedUserEvents, response.userEvents as SyncEventReceivedUserEventsData)
}
if (response.asymmetricMessages) {
await this.notifyEventSync(
SyncEvent.ReceivedAsymmetricMessages,
response.asymmetricMessages as SyncEventReceivedAsymmetricMessagesData,
)
}
if (response.vaults) {
await this.notifyEventSync(
SyncEvent.ReceivedRemoteSharedVaults,
response.vaults as SyncEventReceivedRemoteSharedVaultsData,
)
}
if (response.vaultInvites) {
await this.notifyEventSync(
SyncEvent.ReceivedSharedVaultInvites,
response.vaultInvites as SyncEventReceivedSharedVaultInvitesData,
)
}
const resolver = new ServerSyncResponseResolver(
{
retrievedPayloads: await this.processServerPayloads(response.retrievedPayloads, PayloadSource.RemoteRetrieved),
savedPayloads: response.savedPayloads,
conflicts: await this.decryptServerConflicts(response.conflicts),