-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
index.ts
494 lines (427 loc) · 14.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
/**
* this plugin adds the RxCollection.syncGraphQl()-function to rxdb
* you can use it to sync collections with remote graphql endpoint
*/
import {
BehaviorSubject,
Subject,
Subscription,
Observable
} from 'rxjs';
import {
first,
filter
} from 'rxjs/operators';
import GraphQLClient from 'graphql-client';
import {
promiseWait,
flatClone
} from '../../util';
import Core from '../../core';
import {
hash,
clone
} from '../../util';
import {
DEFAULT_MODIFIER,
wasRevisionfromPullReplication,
createRevisionForPulledDocument,
getDocsWithRevisionsFromPouch
} from './helper';
import {
setLastPushSequence,
getLastPullDocument,
setLastPullDocument,
getChangesSinceLastPushSequence
} from './crawling-checkpoint';
import RxDBWatchForChangesPlugin from '../watch-for-changes';
import RxDBLeaderElectionPlugin from '../leader-election';
import {
changeEventfromPouchChange
} from '../../rx-change-event';
import {
RxCollection,
GraphQLSyncPullOptions,
GraphQLSyncPushOptions
} from '../../types';
Core.plugin(RxDBLeaderElectionPlugin);
/**
* add the watch-for-changes-plugin
* so pouchdb will emit events when something gets written to it
*/
Core.plugin(RxDBWatchForChangesPlugin);
export class RxGraphQLReplicationState {
constructor(
public collection: RxCollection,
url: string,
headers: { [k: string]: string },
public pull: GraphQLSyncPullOptions,
public push: GraphQLSyncPushOptions,
public deletedFlag: string,
public live: boolean,
public liveInterval: number,
public retryTime: number
) {
this.client = GraphQLClient({
url,
headers
});
this.endpointHash = hash(url);
this._prepare();
}
public client: any;
public endpointHash: string;
public _subjects = {
recieved: new Subject(), // all documents that are recieved from the endpoint
send: new Subject(), // all documents that are send to the endpoint
error: new Subject(), // all errors that are revieced from the endpoint, emits new Error() objects
canceled: new BehaviorSubject(false), // true when the replication was canceled
active: new BehaviorSubject(false), // true when something is running, false when not
initialReplicationComplete: new BehaviorSubject(false) // true the initial replication-cycle is over
};
public _runningPromise: Promise<void> = Promise.resolve();
public _subs: Subscription[] = [];
public _runQueueCount: number = 0;
public initialReplicationComplete$: Observable<any> = undefined as any;
public recieved$: Observable<any> = undefined as any;
public send$: Observable<any> = undefined as any;
public error$: Observable<any> = undefined as any;
public canceled$: Observable<any> = undefined as any;
public active$: Observable<boolean> = undefined as any;
/**
* things that are more complex to not belong into the constructor
*/
_prepare() {
// stop sync when collection gets destroyed
this.collection.onDestroy.then(() => {
this.cancel();
});
// create getters for the observables
Object.keys(this._subjects).forEach(key => {
Object.defineProperty(this, key + '$', {
get: function () {
return this._subjects[key].asObservable();
}
});
});
}
isStopped(): boolean {
if (!this.live && this._subjects.initialReplicationComplete['_value']) return true;
if (this._subjects.canceled['_value']) return true;
else return false;
}
awaitInitialReplication(): Promise<true> {
return this.initialReplicationComplete$.pipe(
filter(v => v === true),
first()
).toPromise();
}
// ensures this._run() does not run in parallel
async run(): Promise<void> {
if (this.isStopped()) {
return;
}
if (this._runQueueCount > 2) {
return this._runningPromise;
}
this._runQueueCount++;
this._runningPromise = this._runningPromise.then(async () => {
this._subjects.active.next(true);
const willRetry = await this._run();
this._subjects.active.next(false);
if (!willRetry && this._subjects.initialReplicationComplete['_value'] === false)
this._subjects.initialReplicationComplete.next(true);
this._runQueueCount--;
});
return this._runningPromise;
}
async _run() {
let willRetry = false;
if (this.push) {
const ok = await this.runPush();
if (!ok) {
willRetry = true;
setTimeout(() => this.run(), this.retryTime);
}
}
if (this.pull) {
const ok = await this.runPull();
if (!ok) {
willRetry = true;
setTimeout(() => this.run(), this.retryTime);
}
}
return willRetry;
}
/**
* @return true if no errors occured
*/
async runPull(): Promise<boolean> {
// console.log('RxGraphQLReplicationState.runPull(): start');
if (this.isStopped()) return Promise.resolve(false);
const latestDocument = await getLastPullDocument(this.collection, this.endpointHash);
const latestDocumentData = latestDocument ? latestDocument : null;
const pullGraphQL = this.pull.queryBuilder(latestDocumentData);
let result;
try {
result = await this.client.query(pullGraphQL.query, pullGraphQL.variables);
if (result.errors) {
throw new Error(result.errors);
}
} catch (err) {
this._subjects.error.next(err);
setTimeout(() => this.run(), this.retryTime);
return false;
}
// this assumes that there will be always only one property in the response
// is this correct?
const data = result.data[Object.keys(result.data)[0]];
const modified = data.map((doc: any) => (this.pull as any).modifier(doc));
const docIds = modified.map((doc: any) => doc[this.collection.schema.primaryPath]);
const docsWithRevisions = await getDocsWithRevisionsFromPouch(
this.collection,
docIds
);
await Promise.all(
modified
.map((doc: any) => this.handleDocumentFromRemote(
doc, docsWithRevisions as any))
);
modified.map((doc: any) => this._subjects.recieved.next(doc));
if (modified.length === 0) {
if (this.live) {
// console.log('no more docs, wait for ping');
} else {
// console.log('RxGraphQLReplicationState._run(): no more docs and not live; complete = true');
}
} else {
const newLatestDocument = modified[modified.length - 1];
await setLastPullDocument(
this.collection,
this.endpointHash,
newLatestDocument
);
// we have more docs, re-run
await this.runPull();
}
return true;
}
async runPush() {
// console.log('RxGraphQLReplicationState.runPush(): start');
const changes = await getChangesSinceLastPushSequence(
this.collection,
this.endpointHash,
this.push.batchSize
);
const changesWithDocs = changes.results.map((change: any) => {
let doc = change['doc'];
doc[this.deletedFlag] = !!change['deleted'];
delete doc._rev;
delete doc._deleted;
delete doc._attachments;
doc = (this.push as any).modifier(doc);
const seq = change.seq;
return {
doc,
seq
};
});
let lastSuccessfullChange = null;
try {
/**
* we cannot run all queries parallel
* because then we would not know
* where to start again on errors
* so we run through the docs in series
*/
for (let i = 0; i < changesWithDocs.length; i++) {
const changeWithDoc = changesWithDocs[i];
const pushObj = this.push.queryBuilder(changeWithDoc.doc);
const result = await this.client.query(pushObj.query, pushObj.variables);
if (result.errors) {
throw new Error(result.errors);
} else {
this._subjects.send.next(changeWithDoc.doc);
lastSuccessfullChange = changeWithDoc;
}
}
} catch (err) {
if (lastSuccessfullChange) {
await setLastPushSequence(
this.collection,
this.endpointHash,
lastSuccessfullChange.seq
);
}
this._subjects.error.next(err);
setTimeout(() => this.run(), this.retryTime);
return false;
}
// all docs where successfull, so we use the seq of the changes-fetch
await setLastPushSequence(
this.collection,
this.endpointHash,
changes.last_seq
);
if (changes.results.length === 0) {
if (this.live) {
// console.log('no more docs to push, wait for ping');
} else {
// console.log('RxGraphQLReplicationState._runPull(): no more docs to push and not live; complete = true');
}
} else {
// we have more docs, re-run
await this.runPush();
}
return true;
}
async handleDocumentFromRemote(doc: any, docsWithRevisions: any[]) {
const deletedValue = doc[this.deletedFlag];
const toPouch = this.collection._handleToPouch(doc);
// console.log('handleDocumentFromRemote(' + toPouch._id + ') start');
toPouch._deleted = deletedValue;
delete toPouch[this.deletedFlag];
const primaryValue = toPouch._id;
const pouchState = docsWithRevisions[primaryValue];
let newRevision = createRevisionForPulledDocument(
this.endpointHash,
toPouch
);
if (pouchState) {
const newRevisionHeight = pouchState.revisions.start + 1;
const revisionId = newRevision;
newRevision = newRevisionHeight + '-' + newRevision;
toPouch._revisions = {
start: newRevisionHeight,
ids: pouchState.revisions.ids
};
toPouch._revisions.ids.unshift(revisionId);
} else {
newRevision = '1-' + newRevision;
}
toPouch._rev = newRevision;
await this.collection.pouch.bulkDocs(
[
toPouch
],
{
new_edits: false
}
);
/**
* because bulkDocs with new_edits: false
* does not stream changes to the pouchdb,
* we create the event and emit it,
* so other instances get informed about it
*/
const originalDoc = flatClone(toPouch);
if (deletedValue) {
originalDoc._deleted = deletedValue;
} else {
delete originalDoc._deleted;
}
delete originalDoc[this.deletedFlag];
delete originalDoc._revisions;
originalDoc._rev = newRevision;
const cE = changeEventfromPouchChange(
originalDoc,
this.collection
);
this.collection.$emit(cE);
}
cancel(): Promise<any> {
if (this.isStopped()) return Promise.resolve(false);
this._subs.forEach(sub => sub.unsubscribe());
this._subjects.canceled.next(true);
// TODO
return Promise.resolve(true);
}
}
export function syncGraphQL(
this: RxCollection,
{
url,
headers = {},
waitForLeadership = true,
pull,
push,
deletedFlag,
live = false,
liveInterval = 1000 * 10, // in ms
retryTime = 1000 * 5, // in ms
autoStart = true // if this is false, the replication does nothing at start
}: any
) {
const collection = this;
// fill in defaults for pull & push
if (pull) {
if (!pull.modifier) pull.modifier = DEFAULT_MODIFIER;
}
if (push) {
if (!push.modifier) push.modifier = DEFAULT_MODIFIER;
}
// ensure the collection is listening to plain-pouchdb writes
collection.watchForChanges();
const replicationState = new RxGraphQLReplicationState(
collection,
url,
headers,
pull,
push,
deletedFlag,
live,
liveInterval,
retryTime
);
if (!autoStart) return replicationState;
// run internal so .sync() does not have to be async
const waitTillRun: any = waitForLeadership ? this.database.waitForLeadership() : promiseWait(0);
waitTillRun.then(() => {
// trigger run once
replicationState.run();
// start sync-interval
if (replicationState.live) {
if (pull) {
(async () => {
while (!replicationState.isStopped()) {
await promiseWait(replicationState.liveInterval);
if (replicationState.isStopped()) return;
await replicationState.run();
}
})();
}
if (push) {
/**
* we have to use the rxdb changestream
* because the pouchdb.changes stream sometimes
* does not emit events or stucks
*/
const changeEventsSub = collection.$.subscribe(changeEvent => {
if (replicationState.isStopped()) return;
const rev = changeEvent.data.v._rev;
if (
rev &&
!wasRevisionfromPullReplication(
replicationState.endpointHash,
rev
)
) {
replicationState.run();
}
});
replicationState._subs.push(changeEventsSub);
}
}
});
return replicationState;
}
export const rxdb = true;
export const prototypes = {
RxCollection: (proto: any) => {
proto.syncGraphQL = syncGraphQL;
}
};
export default {
rxdb,
prototypes
};