-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
replicate.js
545 lines (493 loc) · 15.7 KB
/
replicate.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
import { clone, filterChange, nextTick, uuid } from 'pouchdb-utils';
import getDocs from './getDocs';
import Checkpointer from 'pouchdb-checkpointer';
import backOff from './backoff';
import generateReplicationId from 'pouchdb-generate-replication-id';
import { createError } from 'pouchdb-errors';
function replicate(src, target, opts, returnValue, result) {
var batches = []; // list of batches to be processed
var currentBatch; // the batch currently being processed
var pendingBatch = {
seq: 0,
changes: [],
docs: []
}; // next batch, not yet ready to be processed
var writingCheckpoint = false; // true while checkpoint is being written
var changesCompleted = false; // true when all changes received
var replicationCompleted = false; // true when replication has completed
// initial_last_seq is the state of the source db before
// replication started, and it is _not_ updated during
// replication or used anywhere else, as opposed to last_seq
var initial_last_seq = 0;
var last_seq = 0;
var continuous = opts.continuous || opts.live || false;
var batch_size = opts.batch_size || 100;
var batches_limit = opts.batches_limit || 10;
var style = opts.style || 'all_docs';
var changesPending = false; // true while src.changes is running
var doc_ids = opts.doc_ids;
var selector = opts.selector;
var repId;
var checkpointer;
var changedDocs = [];
// Like couchdb, every replication gets a unique session id
var session = uuid();
var taskId;
result = result || {
ok: true,
start_time: new Date().toISOString(),
docs_read: 0,
docs_written: 0,
doc_write_failures: 0,
errors: []
};
var changesOpts = {};
returnValue.ready(src, target);
function initCheckpointer() {
if (checkpointer) {
return Promise.resolve();
}
return generateReplicationId(src, target, opts).then(function (res) {
repId = res;
var checkpointOpts = {};
if (opts.checkpoint === false) {
checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: false };
} else if (opts.checkpoint === 'source') {
checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: false };
} else if (opts.checkpoint === 'target') {
checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: true };
} else {
checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: true };
}
checkpointer = new Checkpointer(src, target, repId, returnValue, checkpointOpts);
});
}
function writeDocs() {
changedDocs = [];
if (currentBatch.docs.length === 0) {
return;
}
var docs = currentBatch.docs;
var bulkOpts = {timeout: opts.timeout};
return target.bulkDocs({docs, new_edits: false}, bulkOpts).then(function (res) {
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
throw new Error('cancelled');
}
// `res` doesn't include full documents (which live in `docs`), so we create a map of
// (id -> error), and check for errors while iterating over `docs`
var errorsById = Object.create(null);
res.forEach(function (res) {
if (res.error) {
errorsById[res.id] = res;
}
});
var errorsNo = Object.keys(errorsById).length;
result.doc_write_failures += errorsNo;
result.docs_written += docs.length - errorsNo;
docs.forEach(function (doc) {
var error = errorsById[doc._id];
if (error) {
result.errors.push(error);
// Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
var errorName = (error.name || '').toLowerCase();
if (errorName === 'unauthorized' || errorName === 'forbidden') {
returnValue.emit('denied', clone(error));
} else {
throw error;
}
} else {
changedDocs.push(doc);
}
});
}, function (err) {
result.doc_write_failures += docs.length;
throw err;
});
}
function finishBatch() {
if (currentBatch.error) {
throw new Error('There was a problem getting docs.');
}
result.last_seq = last_seq = currentBatch.seq;
var outResult = clone(result);
if (changedDocs.length) {
outResult.docs = changedDocs;
// Attach 'pending' property if server supports it (CouchDB 2.0+)
/* istanbul ignore if */
if (typeof currentBatch.pending === 'number') {
outResult.pending = currentBatch.pending;
delete currentBatch.pending;
}
returnValue.emit('change', outResult);
}
writingCheckpoint = true;
src.info().then(function (info) {
var task = src.activeTasks.get(taskId);
if (!currentBatch || !task) {
return;
}
var completed = task.completed_items || 0;
var total_items = parseInt(info.update_seq, 10) - parseInt(initial_last_seq, 10);
src.activeTasks.update(taskId, {
completed_items: completed + currentBatch.changes.length,
total_items
});
});
return checkpointer.writeCheckpoint(currentBatch.seq,
session).then(function () {
returnValue.emit('checkpoint', { 'checkpoint': currentBatch.seq });
writingCheckpoint = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
throw new Error('cancelled');
}
currentBatch = undefined;
getChanges();
}).catch(function (err) {
onCheckpointError(err);
throw err;
});
}
function getDiffs() {
var diff = {};
currentBatch.changes.forEach(function (change) {
returnValue.emit('checkpoint', { 'revs_diff': change });
// Couchbase Sync Gateway emits these, but we can ignore them
/* istanbul ignore if */
if (change.id === "_user/") {
return;
}
diff[change.id] = change.changes.map(function (x) {
return x.rev;
});
});
return target.revsDiff(diff).then(function (diffs) {
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
throw new Error('cancelled');
}
// currentBatch.diffs elements are deleted as the documents are written
currentBatch.diffs = diffs;
});
}
function getBatchDocs() {
return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {
currentBatch.error = !got.ok;
got.docs.forEach(function (doc) {
delete currentBatch.diffs[doc._id];
result.docs_read++;
currentBatch.docs.push(doc);
});
});
}
function startNextBatch() {
if (returnValue.cancelled || currentBatch) {
return;
}
if (batches.length === 0) {
processPendingBatch(true);
return;
}
currentBatch = batches.shift();
returnValue.emit('checkpoint', { 'start_next_batch': currentBatch.seq });
getDiffs()
.then(getBatchDocs)
.then(writeDocs)
.then(finishBatch)
.then(startNextBatch)
.catch(function (err) {
abortReplication('batch processing terminated with error', err);
});
}
function processPendingBatch(immediate) {
if (pendingBatch.changes.length === 0) {
if (batches.length === 0 && !currentBatch) {
if ((continuous && changesOpts.live) || changesCompleted) {
returnValue.state = 'pending';
returnValue.emit('paused');
}
if (changesCompleted) {
completeReplication();
}
}
return;
}
if (
immediate ||
changesCompleted ||
pendingBatch.changes.length >= batch_size
) {
batches.push(pendingBatch);
pendingBatch = {
seq: 0,
changes: [],
docs: []
};
if (returnValue.state === 'pending' || returnValue.state === 'stopped') {
returnValue.state = 'active';
returnValue.emit('active');
}
startNextBatch();
}
}
function abortReplication(reason, err) {
if (replicationCompleted) {
return;
}
if (!err.message) {
err.message = reason;
}
result.ok = false;
result.status = 'aborting';
batches = [];
pendingBatch = {
seq: 0,
changes: [],
docs: []
};
completeReplication(err);
}
function completeReplication(fatalError) {
if (replicationCompleted) {
return;
}
/* istanbul ignore if */
if (returnValue.cancelled) {
result.status = 'cancelled';
if (writingCheckpoint) {
return;
}
}
result.status = result.status || 'complete';
result.end_time = new Date().toISOString();
result.last_seq = last_seq;
replicationCompleted = true;
src.activeTasks.remove(taskId, fatalError);
if (fatalError) {
// need to extend the error because Firefox considers ".result" read-only
fatalError = createError(fatalError);
fatalError.result = result;
// Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
var errorName = (fatalError.name || '').toLowerCase();
if (errorName === 'unauthorized' || errorName === 'forbidden') {
returnValue.emit('error', fatalError);
returnValue.removeAllListeners();
} else {
backOff(opts, returnValue, fatalError, function () {
replicate(src, target, opts, returnValue);
});
}
} else {
returnValue.emit('complete', result);
returnValue.removeAllListeners();
}
}
function onChange(change, pending, lastSeq) {
/* istanbul ignore if */
if (returnValue.cancelled) {
return completeReplication();
}
// Attach 'pending' property if server supports it (CouchDB 2.0+)
/* istanbul ignore if */
if (typeof pending === 'number') {
pendingBatch.pending = pending;
}
var filter = filterChange(opts)(change);
if (!filter) {
// update processed items count by 1
var task = src.activeTasks.get(taskId);
if (task) {
// we can assume that task exists here? shouldn't be deleted by here.
var completed = task.completed_items || 0;
src.activeTasks.update(taskId, {completed_items: ++completed});
}
return;
}
pendingBatch.seq = change.seq || lastSeq;
pendingBatch.changes.push(change);
returnValue.emit('checkpoint', { 'pending_batch': pendingBatch.seq });
nextTick(function () {
processPendingBatch(batches.length === 0 && changesOpts.live);
});
}
function onChangesComplete(changes) {
changesPending = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
return completeReplication();
}
// if no results were returned then we're done,
// else fetch more
if (changes.results.length > 0) {
changesOpts.since = changes.results[changes.results.length - 1].seq;
getChanges();
processPendingBatch(true);
} else {
var complete = function () {
if (continuous) {
changesOpts.live = true;
getChanges();
} else {
changesCompleted = true;
}
processPendingBatch(true);
};
// update the checkpoint so we start from the right seq next time
if (!currentBatch && changes.results.length === 0) {
writingCheckpoint = true;
checkpointer.writeCheckpoint(changes.last_seq,
session).then(function () {
writingCheckpoint = false;
result.last_seq = last_seq = changes.last_seq;
if (returnValue.cancelled) {
completeReplication();
throw new Error('cancelled');
} else {
complete();
}
})
.catch(onCheckpointError);
} else {
complete();
}
}
}
function onChangesError(err) {
changesPending = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
return completeReplication();
}
abortReplication('changes rejected', err);
}
function getChanges() {
if (!(
!changesPending &&
!changesCompleted &&
batches.length < batches_limit
)) {
return;
}
changesPending = true;
function abortChanges() {
changes.cancel();
}
function removeListener() {
returnValue.removeListener('cancel', abortChanges);
}
if (returnValue._changes) { // remove old changes() and listeners
returnValue.removeListener('cancel', returnValue._abortChanges);
returnValue._changes.cancel();
}
returnValue.once('cancel', abortChanges);
var changes = src.changes(changesOpts)
.on('change', onChange);
changes.then(removeListener, removeListener);
changes.then(onChangesComplete)
.catch(onChangesError);
if (opts.retry) {
// save for later so we can cancel if necessary
returnValue._changes = changes;
returnValue._abortChanges = abortChanges;
}
}
function createTask(checkpoint) {
return src.info().then(function (info) {
var total_items = typeof opts.since === 'undefined' ?
parseInt(info.update_seq, 10) - parseInt(checkpoint, 10) :
parseInt(info.update_seq, 10);
taskId = src.activeTasks.add({
name: `${continuous ? 'continuous ' : ''}replication from ${info.db_name}` ,
total_items,
});
return checkpoint;
});
}
function startChanges() {
initCheckpointer().then(function () {
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
return;
}
return checkpointer.getCheckpoint().then(createTask).then(function (checkpoint) {
last_seq = checkpoint;
initial_last_seq = checkpoint;
changesOpts = {
since: last_seq,
limit: batch_size,
batch_size,
style,
doc_ids,
selector,
return_docs: true // required so we know when we're done
};
if (opts.filter) {
if (typeof opts.filter !== 'string') {
// required for the client-side filter in onChange
changesOpts.include_docs = true;
} else { // ddoc filter
changesOpts.filter = opts.filter;
}
}
if ('heartbeat' in opts) {
changesOpts.heartbeat = opts.heartbeat;
}
if ('timeout' in opts) {
changesOpts.timeout = opts.timeout;
}
if (opts.query_params) {
changesOpts.query_params = opts.query_params;
}
if (opts.view) {
changesOpts.view = opts.view;
}
getChanges();
});
}).catch(function (err) {
abortReplication('getCheckpoint rejected with ', err);
});
}
/* istanbul ignore next */
function onCheckpointError(err) {
writingCheckpoint = false;
abortReplication('writeCheckpoint completed with error', err);
}
/* istanbul ignore if */
if (returnValue.cancelled) { // cancelled immediately
completeReplication();
return;
}
if (!returnValue._addedListeners) {
returnValue.once('cancel', completeReplication);
if (typeof opts.complete === 'function') {
returnValue.once('error', opts.complete);
returnValue.once('complete', function (result) {
opts.complete(null, result);
});
}
returnValue._addedListeners = true;
}
if (typeof opts.since === 'undefined') {
startChanges();
} else {
initCheckpointer().then(function () {
writingCheckpoint = true;
return checkpointer.writeCheckpoint(opts.since, session);
}).then(function () {
writingCheckpoint = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
return;
}
last_seq = opts.since;
startChanges();
}).catch(onCheckpointError);
}
}
export default replicate;