-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
1127 lines (984 loc) · 30.6 KB
/
index.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { BackgroundProcessManager } from '@aws-amplify/core/internals/utils';
import { ConsoleLogger, Hub } from '@aws-amplify/core';
import { Observable, SubscriptionLike, filter, of } from 'rxjs';
import {
ConnectionState,
CONNECTION_STATE_CHANGE as PUBSUB_CONNECTION_STATE_CHANGE,
CONTROL_MSG as PUBSUB_CONTROL_MSG,
} from '@aws-amplify/api-graphql';
import { ModelInstanceCreator } from '../datastore/datastore';
import { ModelPredicateCreator } from '../predicates';
import { ExclusiveStorage as Storage } from '../storage/storage';
import {
AmplifyContext,
AuthModeStrategy,
ConflictHandler,
ControlMessageType,
ErrorHandler,
InternalSchema,
ManagedIdentifier,
ModelInit,
ModelInstanceMetadata,
ModelPredicate,
MutableModel,
NamespaceResolver,
OpType,
OptionallyManagedIdentifier,
PersistentModelConstructor,
SchemaModel,
SchemaNamespace,
TypeConstructorMap,
} from '../types';
import type { __modelMeta__ } from '../types';
import { SYNC, USER, getNow } from '../util';
import DataStoreConnectivity from './datastoreConnectivity';
import { ModelMerger } from './merger';
import { MutationEventOutbox } from './outbox';
import { MutationProcessor } from './processors/mutation';
import { CONTROL_MSG, SubscriptionProcessor } from './processors/subscription';
import { SyncProcessor } from './processors/sync';
import {
TransformerMutationType,
createMutationInstanceFromModelOperation,
getIdentifierValue,
predicateToGraphQLCondition,
} from './utils';
const logger = new ConsoleLogger('DataStore');
const ownSymbol = Symbol('sync');
interface StartParams {
fullSyncInterval: number;
}
export declare class MutationEvent {
readonly [__modelMeta__]: {
identifier: OptionallyManagedIdentifier<MutationEvent, 'id'>;
};
public readonly id: string;
public readonly model: string;
public readonly operation: TransformerMutationType;
public readonly modelId: string;
public readonly condition: string;
public readonly data: string;
constructor(init: ModelInit<MutationEvent>);
static copyOf(
src: MutationEvent,
mutator: (draft: MutableModel<MutationEvent>) => void | MutationEvent,
): MutationEvent;
}
export declare class ModelMetadata {
readonly [__modelMeta__]: {
identifier: ManagedIdentifier<ModelMetadata, 'id'>;
};
public readonly id: string;
public readonly namespace: string;
public readonly model: string;
public readonly fullSyncInterval: number;
public readonly lastSync?: number;
public readonly lastFullSync?: number;
public readonly lastSyncPredicate?: null | string;
constructor(init: ModelInit<ModelMetadata>);
static copyOf(
src: ModelMetadata,
mutator: (draft: MutableModel<ModelMetadata>) => void | ModelMetadata,
): ModelMetadata;
}
export enum ControlMessage {
SYNC_ENGINE_STORAGE_SUBSCRIBED = 'storageSubscribed',
SYNC_ENGINE_SUBSCRIPTIONS_ESTABLISHED = 'subscriptionsEstablished',
SYNC_ENGINE_SYNC_QUERIES_STARTED = 'syncQueriesStarted',
SYNC_ENGINE_SYNC_QUERIES_READY = 'syncQueriesReady',
SYNC_ENGINE_MODEL_SYNCED = 'modelSynced',
SYNC_ENGINE_OUTBOX_MUTATION_ENQUEUED = 'outboxMutationEnqueued',
SYNC_ENGINE_OUTBOX_MUTATION_PROCESSED = 'outboxMutationProcessed',
SYNC_ENGINE_OUTBOX_STATUS = 'outboxStatus',
SYNC_ENGINE_NETWORK_STATUS = 'networkStatus',
SYNC_ENGINE_READY = 'ready',
}
export class SyncEngine {
private online = false;
private readonly syncQueriesProcessor: SyncProcessor;
private readonly subscriptionsProcessor: SubscriptionProcessor;
private readonly mutationsProcessor: MutationProcessor;
private readonly modelMerger: ModelMerger;
private readonly outbox: MutationEventOutbox;
private readonly datastoreConnectivity: DataStoreConnectivity;
private readonly modelSyncedStatus = new WeakMap<
PersistentModelConstructor<any>,
boolean
>();
private unsleepSyncQueriesObservable: (() => void) | null;
private waitForSleepState: Promise<void>;
private syncQueriesObservableStartSleeping: (
value?: void | PromiseLike<void>,
) => void;
private stopDisruptionListener: () => void;
private connectionDisrupted = false;
private runningProcesses: BackgroundProcessManager;
public getModelSyncedStatus(
modelConstructor: PersistentModelConstructor<any>,
): boolean {
return this.modelSyncedStatus.get(modelConstructor)!;
}
constructor(
private readonly schema: InternalSchema,
private readonly namespaceResolver: NamespaceResolver,
private readonly modelClasses: TypeConstructorMap,
private readonly userModelClasses: TypeConstructorMap,
private readonly storage: Storage,
private readonly modelInstanceCreator: ModelInstanceCreator,
conflictHandler: ConflictHandler,
errorHandler: ErrorHandler,
private readonly syncPredicates: WeakMap<
SchemaModel,
ModelPredicate<any> | null
>,
private readonly amplifyConfig: Record<string, any> = {},
private readonly authModeStrategy: AuthModeStrategy,
private readonly amplifyContext: AmplifyContext,
private readonly connectivityMonitor?: DataStoreConnectivity,
) {
this.runningProcesses = new BackgroundProcessManager();
this.waitForSleepState = new Promise(resolve => {
this.syncQueriesObservableStartSleeping = resolve;
});
const MutationEventCtor = this.modelClasses
.MutationEvent as PersistentModelConstructor<MutationEvent>;
this.outbox = new MutationEventOutbox(
this.schema,
MutationEventCtor,
modelInstanceCreator,
ownSymbol,
);
this.modelMerger = new ModelMerger(this.outbox, ownSymbol);
this.syncQueriesProcessor = new SyncProcessor(
this.schema,
this.syncPredicates,
this.amplifyConfig,
this.authModeStrategy,
errorHandler,
this.amplifyContext,
);
this.subscriptionsProcessor = new SubscriptionProcessor(
this.schema,
this.syncPredicates,
this.amplifyConfig,
this.authModeStrategy,
errorHandler,
this.amplifyContext,
);
this.mutationsProcessor = new MutationProcessor(
this.schema,
this.storage,
this.userModelClasses,
this.outbox,
this.modelInstanceCreator,
MutationEventCtor,
this.amplifyConfig,
this.authModeStrategy,
errorHandler,
conflictHandler,
this.amplifyContext,
);
this.datastoreConnectivity =
this.connectivityMonitor || new DataStoreConnectivity();
}
start(params: StartParams) {
return new Observable<ControlMessageType<ControlMessage>>(observer => {
logger.log('starting sync engine...');
let subscriptions: SubscriptionLike[] = [];
this.runningProcesses.add(async () => {
try {
await this.setupModels(params);
} catch (err) {
observer.error(err);
return;
}
// this is awaited at the bottom. so, we don't need to register
// this explicitly with the context. it's already contained.
const startPromise = new Promise<void>((resolve, reject) => {
const doneStarting = resolve;
const failedStarting = reject;
this.datastoreConnectivity.status().subscribe(
async ({ online }) =>
this.runningProcesses.isOpen &&
this.runningProcesses.add(async onTerminate => {
// From offline to online
if (online && !this.online) {
this.online = online;
observer.next({
type: ControlMessage.SYNC_ENGINE_NETWORK_STATUS,
data: {
active: this.online,
},
});
this.stopDisruptionListener = this.startDisruptionListener();
// #region GraphQL Subscriptions
const [ctlSubsObservable, dataSubsObservable] =
this.subscriptionsProcessor.start();
try {
await new Promise<void>((_resolve, _reject) => {
onTerminate.then(_reject);
const ctlSubsSubscription = ctlSubsObservable.subscribe({
next: msg => {
if (msg === CONTROL_MSG.CONNECTED) {
_resolve();
}
},
error: err => {
_reject(err);
const handleDisconnect = this.disconnectionHandler();
handleDisconnect(err);
},
});
subscriptions.push(ctlSubsSubscription);
});
} catch (err) {
observer.error(err);
failedStarting();
return;
}
logger.log('Realtime ready');
observer.next({
type: ControlMessage.SYNC_ENGINE_SUBSCRIPTIONS_ESTABLISHED,
});
// #endregion
// #region Base & Sync queries
try {
await new Promise<void>((_resolve, _reject) => {
const syncQuerySubscription =
this.syncQueriesObservable().subscribe({
next: message => {
const { type } = message;
if (
type ===
ControlMessage.SYNC_ENGINE_SYNC_QUERIES_READY
) {
_resolve();
}
observer.next(message);
},
complete: () => {
_resolve();
},
error: error => {
_reject(error);
},
});
if (syncQuerySubscription) {
subscriptions.push(syncQuerySubscription);
}
});
} catch (error) {
observer.error(error);
failedStarting();
return;
}
// #endregion
// #region process mutations (outbox)
subscriptions.push(
this.mutationsProcessor
.start()
.subscribe(({ modelDefinition, model: item, hasMore }) =>
this.runningProcesses.add(async () => {
const modelConstructor = this.userModelClasses[
modelDefinition.name
] as PersistentModelConstructor<any>;
const model = this.modelInstanceCreator(
modelConstructor,
item,
);
await this.storage.runExclusive(storage =>
this.modelMerger.merge(
storage,
model,
modelDefinition,
),
);
observer.next({
type: ControlMessage.SYNC_ENGINE_OUTBOX_MUTATION_PROCESSED,
data: {
model: modelConstructor,
element: model,
},
});
observer.next({
type: ControlMessage.SYNC_ENGINE_OUTBOX_STATUS,
data: {
isEmpty: !hasMore,
},
});
}, 'mutation processor event'),
),
);
// #endregion
// #region Merge subscriptions buffer
subscriptions.push(
dataSubsObservable!.subscribe(
([_transformerMutationType, modelDefinition, item]) =>
this.runningProcesses.add(async () => {
const modelConstructor = this.userModelClasses[
modelDefinition.name
] as PersistentModelConstructor<any>;
const model = this.modelInstanceCreator(
modelConstructor,
item,
);
await this.storage.runExclusive(storage =>
this.modelMerger.merge(
storage,
model,
modelDefinition,
),
);
}, 'subscription dataSubsObservable event'),
),
);
// #endregion
} else if (!online) {
this.online = online;
observer.next({
type: ControlMessage.SYNC_ENGINE_NETWORK_STATUS,
data: {
active: this.online,
},
});
subscriptions.forEach(sub => {
sub.unsubscribe();
});
subscriptions = [];
}
doneStarting();
}, 'datastore connectivity event'),
);
});
this.storage
.observe(null, null, ownSymbol)
.pipe(
filter(({ model }) => {
const modelDefinition = this.getModelDefinition(model);
return modelDefinition.syncable === true;
}),
)
.subscribe({
next: async ({ opType, model, element, condition }) =>
this.runningProcesses.add(async () => {
const namespace =
this.schema.namespaces[this.namespaceResolver(model)];
const MutationEventConstructor = this.modelClasses
.MutationEvent as PersistentModelConstructor<MutationEvent>;
const modelDefinition = this.getModelDefinition(model);
const graphQLCondition = predicateToGraphQLCondition(
condition!,
modelDefinition,
);
const mutationEvent = createMutationInstanceFromModelOperation(
namespace.relationships!,
this.getModelDefinition(model),
opType,
model,
element,
graphQLCondition,
MutationEventConstructor,
this.modelInstanceCreator,
);
await this.outbox.enqueue(this.storage, mutationEvent);
observer.next({
type: ControlMessage.SYNC_ENGINE_OUTBOX_MUTATION_ENQUEUED,
data: {
model,
element,
},
});
observer.next({
type: ControlMessage.SYNC_ENGINE_OUTBOX_STATUS,
data: {
isEmpty: false,
},
});
await startPromise;
// Set by the this.datastoreConnectivity.status().subscribe() loop
if (this.online) {
this.mutationsProcessor.resume();
}
}, 'storage event'),
});
observer.next({
type: ControlMessage.SYNC_ENGINE_STORAGE_SUBSCRIBED,
});
const hasMutationsInOutbox =
(await this.outbox.peek(this.storage)) === undefined;
observer.next({
type: ControlMessage.SYNC_ENGINE_OUTBOX_STATUS,
data: {
isEmpty: hasMutationsInOutbox,
},
});
await startPromise;
observer.next({
type: ControlMessage.SYNC_ENGINE_READY,
});
}, 'sync start');
});
}
private async getModelsMetadataWithNextFullSync(
currentTimeStamp: number,
): Promise<Map<SchemaModel, [string, number]>> {
const modelLastSync = new Map<SchemaModel, [string, number]>(
(
await this.runningProcesses.add(
() => this.getModelsMetadata(),
'sync/index getModelsMetadataWithNextFullSync',
)
).map(
({ namespace, model, lastSync, lastFullSync, fullSyncInterval }) => {
const nextFullSync = lastFullSync! + fullSyncInterval;
const syncFrom =
!lastFullSync || nextFullSync < currentTimeStamp
? 0 // perform full sync if expired
: lastSync; // perform delta sync
return [
this.schema.namespaces[namespace].models[model],
[namespace, syncFrom!],
];
},
),
);
return modelLastSync;
}
private syncQueriesObservable(): Observable<
ControlMessageType<ControlMessage>
> {
if (!this.online) {
return of<ControlMessageType<ControlMessage>>({} as any); // TODO(v6): fix this
}
return new Observable<ControlMessageType<ControlMessage>>(observer => {
let syncQueriesSubscription: SubscriptionLike;
this.runningProcesses.isOpen &&
this.runningProcesses.add(async onTerminate => {
let terminated = false;
while (!observer.closed && !terminated) {
const count = new WeakMap<
PersistentModelConstructor<any>,
{
new: number;
updated: number;
deleted: number;
}
>();
const modelLastSync = await this.getModelsMetadataWithNextFullSync(
Date.now(),
);
const paginatingModels = new Set(modelLastSync.keys());
let lastFullSyncStartedAt: number;
let syncInterval: number;
let start: number;
let syncDuration: number;
let lastStartedAt: number;
await new Promise<void>((resolve, _reject) => {
if (!this.runningProcesses.isOpen) resolve();
onTerminate.then(() => {
resolve();
});
syncQueriesSubscription = this.syncQueriesProcessor
.start(modelLastSync)
.subscribe({
next: async ({
namespace,
modelDefinition,
items,
done,
startedAt,
isFullSync,
}) => {
const modelConstructor = this.userModelClasses[
modelDefinition.name
] as PersistentModelConstructor<any>;
if (!count.has(modelConstructor)) {
count.set(modelConstructor, {
new: 0,
updated: 0,
deleted: 0,
});
start = getNow();
lastStartedAt =
lastStartedAt === undefined
? startedAt
: Math.max(lastStartedAt, startedAt);
}
/**
* If there are mutations in the outbox for a given id, those need to be
* merged individually. Otherwise, we can merge them in batches.
*/
await this.storage.runExclusive(async storage => {
const idsInOutbox =
await this.outbox.getModelIds(storage);
const oneByOne: ModelInstanceMetadata[] = [];
const page = items.filter(item => {
const itemId = getIdentifierValue(
modelDefinition,
item,
);
if (!idsInOutbox.has(itemId)) {
return true;
}
oneByOne.push(item);
return false;
});
const opTypeCount: [any, OpType][] = [];
for (const item of oneByOne) {
const opType = await this.modelMerger.merge(
storage,
item,
modelDefinition,
);
if (opType !== undefined) {
opTypeCount.push([item, opType]);
}
}
opTypeCount.push(
...(await this.modelMerger.mergePage(
storage,
modelConstructor,
page,
modelDefinition,
)),
);
const counts = count.get(modelConstructor)!;
opTypeCount.forEach(([, opType]) => {
switch (opType) {
case OpType.INSERT:
counts.new++;
break;
case OpType.UPDATE:
counts.updated++;
break;
case OpType.DELETE:
counts.deleted++;
break;
default:
throw new Error(`Invalid opType ${opType}`);
}
});
});
if (done) {
const { name: modelName } = modelDefinition;
// #region update last sync for type
let modelMetadata = await this.getModelMetadata(
namespace,
modelName,
);
const { lastFullSync, fullSyncInterval } = modelMetadata;
syncInterval = fullSyncInterval;
lastFullSyncStartedAt =
lastFullSyncStartedAt === undefined
? lastFullSync!
: Math.max(
lastFullSyncStartedAt,
isFullSync ? startedAt : lastFullSync!,
);
modelMetadata = (
this.modelClasses
.ModelMetadata as PersistentModelConstructor<ModelMetadata>
).copyOf(modelMetadata, draft => {
draft.lastSync = startedAt;
draft.lastFullSync = isFullSync
? startedAt
: modelMetadata.lastFullSync;
});
await this.storage.save(
modelMetadata,
undefined,
ownSymbol,
);
// #endregion
const counts = count.get(modelConstructor);
this.modelSyncedStatus.set(modelConstructor, true);
observer.next({
type: ControlMessage.SYNC_ENGINE_MODEL_SYNCED,
data: {
model: modelConstructor,
isFullSync,
isDeltaSync: !isFullSync,
counts,
},
});
paginatingModels.delete(modelDefinition);
if (paginatingModels.size === 0) {
syncDuration = getNow() - start;
resolve();
observer.next({
type: ControlMessage.SYNC_ENGINE_SYNC_QUERIES_READY,
});
syncQueriesSubscription.unsubscribe();
}
}
},
error: error => {
observer.error(error);
},
});
observer.next({
type: ControlMessage.SYNC_ENGINE_SYNC_QUERIES_STARTED,
data: {
models: Array.from(paginatingModels).map(({ name }) => name),
},
});
});
// null is cast to 0 resulting in unexpected behavior.
// undefined in arithmetic operations results in NaN also resulting in unexpected behavior.
// If lastFullSyncStartedAt is null this is the first sync.
// Assume lastStartedAt is is also newest full sync.
let msNextFullSync;
if (!lastFullSyncStartedAt!) {
msNextFullSync = syncInterval! - syncDuration!;
} else {
msNextFullSync =
lastFullSyncStartedAt! +
syncInterval! -
(lastStartedAt! + syncDuration!);
}
logger.debug(
`Next fullSync in ${msNextFullSync / 1000} seconds. (${new Date(
Date.now() + msNextFullSync,
)})`,
);
// TODO: create `BackgroundProcessManager.sleep()` ... but, need to put
// a lot of thought into what that contract looks like to
// support possible use-cases:
//
// 1. non-cancelable
// 2. cancelable, unsleep on exit()
// 3. cancelable, throw Error on exit()
// 4. cancelable, callback first on exit()?
// 5. ... etc. ? ...
//
// TLDR; this is a lot of complexity here for a sleep(),
// but, it's not clear to me yet how to support an
// extensible, centralized cancelable `sleep()` elegantly.
await this.runningProcesses.add(async onRunningProcessTerminate => {
let _sleepTimer;
let unsleep;
const sleep = new Promise(resolve => {
unsleep = resolve;
_sleepTimer = setTimeout(unsleep, msNextFullSync);
});
onRunningProcessTerminate.then(() => {
terminated = true;
this.syncQueriesObservableStartSleeping();
unsleep();
});
this.unsleepSyncQueriesObservable = unsleep;
this.syncQueriesObservableStartSleeping();
return sleep;
}, 'syncQueriesObservable sleep');
this.unsleepSyncQueriesObservable = null;
this.waitForSleepState = new Promise(resolve => {
this.syncQueriesObservableStartSleeping = resolve;
});
}
}, 'syncQueriesObservable main');
});
}
private disconnectionHandler(): (msg: string) => void {
return (msg: string) => {
// This implementation is tied to AWSAppSyncRealTimeProvider 'Connection closed', 'Timeout disconnect' msg
if (
PUBSUB_CONTROL_MSG.CONNECTION_CLOSED === msg ||
PUBSUB_CONTROL_MSG.TIMEOUT_DISCONNECT === msg
) {
this.datastoreConnectivity.socketDisconnected();
}
};
}
public unsubscribeConnectivity() {
this.datastoreConnectivity.unsubscribe();
}
/**
* Stops all subscription activities and resolves when all activies report
* that they're disconnected, done retrying, etc..
*/
public async stop() {
logger.debug('stopping sync engine');
/**
* Gracefully disconnecting subscribers first just prevents *more* work
* from entering the pipelines.
*/
this.unsubscribeConnectivity();
/**
* Stop listening for websocket connection disruption
*/
this.stopDisruptionListener && this.stopDisruptionListener();
/**
* aggressively shut down any lingering background processes.
* some of this might be semi-redundant with unsubscribing. however,
* unsubscribing doesn't allow us to wait for settling.
* (Whereas `stop()` does.)
*/
await this.mutationsProcessor.stop();
await this.subscriptionsProcessor.stop();
await this.datastoreConnectivity.stop();
await this.syncQueriesProcessor.stop();
await this.runningProcesses.close();
await this.runningProcesses.open();
logger.debug('sync engine stopped and ready to restart');
}
private async setupModels(params: StartParams) {
const { fullSyncInterval } = params;
const ModelMetadataConstructor = this.modelClasses
.ModelMetadata as PersistentModelConstructor<ModelMetadata>;
const models: [string, SchemaModel][] = [];
let savedModel;
Object.values(this.schema.namespaces).forEach(namespace => {
Object.values(namespace.models)
.filter(({ syncable }) => syncable)
.forEach(model => {
models.push([namespace.name, model]);
if (namespace.name === USER) {
const modelConstructor = this.userModelClasses[
model.name
] as PersistentModelConstructor<any>;
this.modelSyncedStatus.set(modelConstructor, false);
}
});
});
const promises = models.map(async ([namespace, model]) => {
const modelMetadata = await this.getModelMetadata(namespace, model.name);
const syncPredicate = ModelPredicateCreator.getPredicates(
this.syncPredicates.get(model)!,
false,
);
const lastSyncPredicate = syncPredicate
? JSON.stringify(syncPredicate)
: null;
if (modelMetadata === undefined) {
[[savedModel]] = await this.storage.save(
this.modelInstanceCreator(ModelMetadataConstructor, {
model: model.name,
namespace,
lastSync: null!,
fullSyncInterval,
lastFullSync: null!,
lastSyncPredicate,
}),
undefined,
ownSymbol,
);
} else {
const prevSyncPredicate = modelMetadata.lastSyncPredicate
? modelMetadata.lastSyncPredicate
: null;
const syncPredicateUpdated = prevSyncPredicate !== lastSyncPredicate;
[[savedModel]] = await this.storage.save(
ModelMetadataConstructor.copyOf(modelMetadata, draft => {
draft.fullSyncInterval = fullSyncInterval;
// perform a base sync if the syncPredicate changed in between calls to DataStore.start
// ensures that the local store contains all the data specified by the syncExpression
if (syncPredicateUpdated) {
draft.lastSync = null!;
draft.lastFullSync = null!;
(draft.lastSyncPredicate as any) = lastSyncPredicate;
}
}),
);
}
return savedModel;
});
const result: Record<string, ModelMetadata> = {};
for (const modelMetadata of await Promise.all(promises)) {
const { model: modelName } = modelMetadata;
result[modelName] = modelMetadata;
}
return result;
}
private async getModelsMetadata(): Promise<ModelMetadata[]> {
const ModelMetadataCtor = this.modelClasses
.ModelMetadata as PersistentModelConstructor<ModelMetadata>;
const modelsMetadata = await this.storage.query(ModelMetadataCtor);
return modelsMetadata;
}
private async getModelMetadata(
namespace: string,
model: string,
): Promise<ModelMetadata> {
const ModelMetadataCtor = this.modelClasses
.ModelMetadata as PersistentModelConstructor<ModelMetadata>;
const predicate = ModelPredicateCreator.createFromAST<ModelMetadata>(
this.schema.namespaces[SYNC].models[ModelMetadataCtor.name],
{ and: [{ namespace: { eq: namespace } }, { model: { eq: model } }] },
);
const [modelMetadata] = await this.storage.query(
ModelMetadataCtor,
predicate,
{
page: 0,
limit: 1,
},
);
return modelMetadata;
}
private getModelDefinition(
modelConstructor: PersistentModelConstructor<any>,
): SchemaModel {
const namespaceName = this.namespaceResolver(modelConstructor);
const modelDefinition =
this.schema.namespaces[namespaceName].models[modelConstructor.name];
return modelDefinition;
}
static getNamespace() {
const namespace: SchemaNamespace = {
name: SYNC,
relationships: {},
enums: {
OperationType: {
name: 'OperationType',
values: ['CREATE', 'UPDATE', 'DELETE'],
},
},
nonModels: {},
models: {
MutationEvent: {
name: 'MutationEvent',
pluralName: 'MutationEvents',
syncable: false,
fields: {
id: {
name: 'id',
type: 'ID',
isRequired: true,
isArray: false,
},
model: {
name: 'model',
type: 'String',
isRequired: true,
isArray: false,
},
data: {
name: 'data',
type: 'String',
isRequired: true,
isArray: false,
},