-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathindex.ts
503 lines (459 loc) · 19.2 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
/**
* This plugin contains the primitives to create
* a RxDB client-server replication.
* It is used in the other replication plugins
* but also can be used as standalone with a custom replication handler.
*/
import {
BehaviorSubject,
combineLatest,
mergeMap,
Observable,
Subject,
Subscription
} from 'rxjs';
import type {
ReplicationOptions,
ReplicationPullHandlerResult,
ReplicationPullOptions,
ReplicationPushOptions,
RxCollection,
RxDocumentData,
RxError,
RxReplicationPullStreamItem,
RxReplicationWriteToMasterRow,
RxStorageInstance,
RxStorageInstanceReplicationState,
RxStorageReplicationMeta,
RxTypeError,
WithDeleted
} from '../../types';
import { RxDBLeaderElectionPlugin } from '../leader-election';
import {
ensureNotFalsy,
errorToPlainJson,
flatClone,
getFromMapOrCreate,
PROMISE_RESOLVE_FALSE,
PROMISE_RESOLVE_TRUE,
toArray
} from '../../plugins/utils';
import {
awaitRxStorageReplicationFirstInSync,
awaitRxStorageReplicationInSync,
cancelRxStorageReplication,
getRxReplicationMetaInstanceSchema,
replicateRxStorageInstance
} from '../../replication-protocol';
import { newRxError } from '../../rx-error';
import {
awaitRetry,
DEFAULT_MODIFIER,
swapDefaultDeletedTodeletedField,
handlePulledDocuments
} from './replication-helper';
import {
addConnectedStorageToCollection
} from '../../rx-database-internal-store';
import { addRxPlugin } from '../../plugin';
import { hasEncryption } from '../../rx-storage-helper';
import { overwritable } from '../../overwritable';
import {
runAsyncPluginHooks
} from '../../hooks';
export const REPLICATION_STATE_BY_COLLECTION: WeakMap<RxCollection, RxReplicationState<any, any>[]> = new WeakMap();
export class RxReplicationState<RxDocType, CheckpointType> {
public readonly subs: Subscription[] = [];
public readonly subjects = {
received: new Subject<RxDocumentData<RxDocType>>(), // all documents that are received from the endpoint
send: new Subject<WithDeleted<RxDocType>>(), // all documents that are send to the endpoint
error: new Subject<RxError | RxTypeError>(), // all errors that are received from the endpoint, emits new Error() objects
canceled: new BehaviorSubject<boolean>(false), // true when the replication was canceled
active: new BehaviorSubject<boolean>(false) // true when something is running, false when not
};
readonly received$: Observable<RxDocumentData<RxDocType>> = this.subjects.received.asObservable();
readonly send$: Observable<WithDeleted<RxDocType>> = this.subjects.send.asObservable();
readonly error$: Observable<RxError | RxTypeError> = this.subjects.error.asObservable();
readonly canceled$: Observable<any> = this.subjects.canceled.asObservable();
readonly active$: Observable<boolean> = this.subjects.active.asObservable();
private startPromise: Promise<void>;
constructor(
/**
* hash of the identifier, used to flag revisions
* and to identify which documents state came from the remote.
*/
public readonly replicationIdentifierHash: string,
public readonly collection: RxCollection<RxDocType>,
public readonly deletedField: string,
public readonly pull?: ReplicationPullOptions<RxDocType, CheckpointType>,
public readonly push?: ReplicationPushOptions<RxDocType>,
public readonly live?: boolean,
public retryTime?: number,
public autoStart?: boolean,
) {
const replicationStates = getFromMapOrCreate(
REPLICATION_STATE_BY_COLLECTION,
collection,
() => []
);
replicationStates.push(this);
// stop the replication when the collection gets destroyed
this.collection.onDestroy.push(() => this.cancel());
// create getters for the observables
Object.keys(this.subjects).forEach(key => {
Object.defineProperty(this, key + '$', {
get: function () {
return this.subjects[key].asObservable();
}
});
});
const startPromise = new Promise<void>(res => {
this.callOnStart = res;
});
this.startPromise = startPromise;
}
private callOnStart: () => void = undefined as any;
public internalReplicationState?: RxStorageInstanceReplicationState<RxDocType>;
public metaInstance?: RxStorageInstance<RxStorageReplicationMeta, any, {}, any>;
public remoteEvents$: Subject<RxReplicationPullStreamItem<RxDocType, CheckpointType>> = new Subject();
public async start(): Promise<void> {
if (this.isStopped()) {
return;
}
// fill in defaults for pull & push
const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;
const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;
const database = this.collection.database;
const metaInstanceCollectionName = this.collection.name + '-rx-replication-' + this.replicationIdentifierHash;
const metaInstanceSchema = getRxReplicationMetaInstanceSchema(
this.collection.schema.jsonSchema,
hasEncryption(this.collection.schema.jsonSchema)
);
const [metaInstance] = await Promise.all([
this.collection.database.storage.createStorageInstance({
databaseName: database.name,
collectionName: metaInstanceCollectionName,
databaseInstanceToken: database.token,
multiInstance: database.multiInstance, // TODO is this always false?
options: {},
schema: metaInstanceSchema,
password: database.password,
devMode: overwritable.isDevMode()
}),
addConnectedStorageToCollection(
this.collection,
metaInstanceCollectionName,
metaInstanceSchema
)
]);
this.metaInstance = metaInstance;
this.internalReplicationState = replicateRxStorageInstance({
pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,
pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,
initialCheckpoint: {
upstream: this.push ? this.push.initialCheckpoint : undefined,
downstream: this.pull ? this.pull.initialCheckpoint : undefined
},
forkInstance: this.collection.storageInstance,
metaInstance: this.metaInstance,
hashFunction: database.hashFunction,
identifier: 'rxdbreplication' + this.replicationIdentifierHash,
conflictHandler: this.collection.conflictHandler,
replicationHandler: {
masterChangeStream$: this.remoteEvents$.asObservable().pipe(
mergeMap(async (ev) => {
if (ev === 'RESYNC') {
return ev;
}
const useEv = flatClone(ev);
useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);
useEv.documents = await Promise.all(
useEv.documents.map(d => pullModifier(d))
);
return useEv;
})
),
masterChangesSince: async (
checkpoint: CheckpointType,
batchSize: number
) => {
if (!this.pull) {
return {
checkpoint: null,
documents: []
};
}
/**
* Retries must be done here in the replication primitives plugin,
* because the replication protocol itself has no
* error handling.
*/
let done = false;
let result: ReplicationPullHandlerResult<RxDocType, CheckpointType> = {} as any;
while (!done && !this.isStopped()) {
try {
result = await this.pull.handler(
checkpoint,
batchSize
);
done = true;
} catch (err: any | Error | Error[]) {
const emitError = newRxError('RC_PULL', {
checkpoint,
errors: toArray(err).map(er => errorToPlainJson(er)),
direction: 'pull'
});
this.subjects.error.next(emitError);
await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));
}
}
if (this.isStopped()) {
return {
checkpoint: null,
documents: []
};
}
const useResult = flatClone(result);
useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);
useResult.documents = await Promise.all(
useResult.documents.map(d => pullModifier(d))
);
return useResult;
},
masterWrite: async (
rows: RxReplicationWriteToMasterRow<RxDocType>[]
) => {
if (!this.push) {
return [];
}
let done = false;
await runAsyncPluginHooks('preReplicationMasterWrite', {
rows,
collection: this.collection
});
const useRows = await Promise.all(
rows.map(async (row) => {
row.newDocumentState = await pushModifier(row.newDocumentState);
if (row.assumedMasterState) {
row.assumedMasterState = await pushModifier(row.assumedMasterState);
}
if (this.deletedField !== '_deleted') {
row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;
if (row.assumedMasterState) {
row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;
}
}
return row;
})
);
let result: WithDeleted<RxDocType>[] = null as any;
// In case all the rows have been filtered and nothing has to be sent
if (useRows.length === 0) {
done = true;
result = [];
}
while (!done && !this.isStopped()) {
try {
result = await this.push.handler(useRows);
/**
* It is a common problem that people have wrongly behaving backend
* that do not return an array with the conflicts on push requests.
* So we run this check here to make it easier to debug.
* @link https://github.com/pubkey/rxdb/issues/4103
*/
if (!Array.isArray(result)) {
throw newRxError(
'RC_PUSH_NO_AR',
{
pushRows: rows,
direction: 'push',
args: { result }
}
);
}
done = true;
} catch (err: any | Error | Error[] | RxError) {
const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {
pushRows: rows,
errors: toArray(err).map(er => errorToPlainJson(er)),
direction: 'push'
});
this.subjects.error.next(emitError);
await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));
}
}
if (this.isStopped()) {
return [];
}
await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {
result,
collection: this.collection
});
const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));
return conflicts;
}
}
});
this.subs.push(
this.internalReplicationState.events.error.subscribe(err => {
this.subjects.error.next(err);
}),
this.internalReplicationState.events.processed.down
.subscribe(row => this.subjects.received.next(row.document as any)),
this.internalReplicationState.events.processed.up
.subscribe(writeToMasterRow => {
this.subjects.send.next(writeToMasterRow.newDocumentState);
}),
combineLatest([
this.internalReplicationState.events.active.down,
this.internalReplicationState.events.active.up
]).subscribe(([down, up]) => {
const isActive = down || up;
this.subjects.active.next(isActive);
})
);
if (
this.pull &&
this.pull.stream$ &&
this.live
) {
this.subs.push(
this.pull.stream$.subscribe({
next: ev => {
this.remoteEvents$.next(ev);
},
error: err => {
this.subjects.error.next(err);
}
})
);
}
/**
* Non-live replications run once
* and then automatically get canceled.
*/
if (!this.live) {
await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);
await awaitRxStorageReplicationInSync(this.internalReplicationState);
await this.cancel();
}
this.callOnStart();
}
isStopped(): boolean {
if (this.subjects.canceled.getValue()) {
return true;
}
return false;
}
async awaitInitialReplication(): Promise<void> {
await this.startPromise;
return awaitRxStorageReplicationFirstInSync(
ensureNotFalsy(this.internalReplicationState)
);
}
/**
* Returns a promise that resolves when:
* - All local data is replicated with the remote
* - No replication cycle is running or in retry-state
*
* WARNING: USing this function directly in a multi-tab browser application
* is dangerous because only the leading instance will ever be replicated,
* so this promise will not resolve in the other tabs.
* For multi-tab support you should set and observe a flag in a local document.
*/
async awaitInSync(): Promise<true> {
await this.startPromise;
await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));
/**
* Often awaitInSync() is called directly after a document write,
* like in the unit tests.
* So we first have to await the idleness to ensure that all RxChangeEvents
* are processed already.
*/
await this.collection.database.requestIdlePromise();
await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));
return true;
}
reSync() {
this.remoteEvents$.next('RESYNC');
}
emitEvent(ev: RxReplicationPullStreamItem<RxDocType, CheckpointType>) {
this.remoteEvents$.next(ev);
}
cancel(): Promise<any> {
if (this.isStopped()) {
return PROMISE_RESOLVE_FALSE;
}
const promises: Promise<any>[] = [];
if (this.internalReplicationState) {
cancelRxStorageReplication(this.internalReplicationState);
}
if (this.metaInstance) {
promises.push(
ensureNotFalsy(this.internalReplicationState).checkpointQueue
.then(() => ensureNotFalsy(this.metaInstance).close())
);
}
this.subs.forEach(sub => sub.unsubscribe());
this.subjects.canceled.next(true);
this.subjects.active.complete();
this.subjects.canceled.complete();
this.subjects.error.complete();
this.subjects.received.complete();
this.subjects.send.complete();
return Promise.all(promises);
}
}
export function replicateRxCollection<RxDocType, CheckpointType>(
{
replicationIdentifier,
collection,
deletedField = '_deleted',
pull,
push,
live = true,
retryTime = 1000 * 5,
waitForLeadership = true,
autoStart = true,
}: ReplicationOptions<RxDocType, CheckpointType>
): RxReplicationState<RxDocType, CheckpointType> {
addRxPlugin(RxDBLeaderElectionPlugin);
const replicationIdentifierHash = collection.database.hashFunction(
[
collection.database.name,
collection.name,
replicationIdentifier
].join('|')
);
const replicationState = new RxReplicationState<RxDocType, CheckpointType>(
replicationIdentifierHash,
collection,
deletedField,
pull,
push,
live,
retryTime,
autoStart
);
startReplicationOnLeaderShip(waitForLeadership, replicationState);
return replicationState as any;
}
export function startReplicationOnLeaderShip(
waitForLeadership: boolean,
replicationState: RxReplicationState<any, any>
) {
/**
* Always await this Promise to ensure that the current instance
* is leader when waitForLeadership=true
*/
const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;
const waitTillRun: Promise<any> = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;
return waitTillRun.then(() => {
if (replicationState.isStopped()) {
return;
}
if (replicationState.autoStart) {
replicationState.start();
}
});
}