|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var Slouch = require('couch-slouch'), |
| 4 | + squadron = require('squadron'); |
| 5 | + |
| 6 | +// params |
| 7 | +// source |
| 8 | +// target |
| 9 | +// concurrency |
| 10 | +// skip |
| 11 | +var Cluster = function (params) { |
| 12 | + this._params = params; |
| 13 | + |
| 14 | + this._sourceSlouch = new Slouch(params.source); |
| 15 | + this._targetSlouch = new Slouch(params.target); |
| 16 | + |
| 17 | + if (this._params.concurrency === 1) { |
| 18 | + // Don't use a throttler |
| 19 | + this._throttler = undefined; |
| 20 | + } else { |
| 21 | + // Create a throttler with the specified or default concurrency |
| 22 | + var concurrency = this._params.concurrency ? this._params.concurrency : null; |
| 23 | + this._throttler = new squadron.Throttler(concurrency); |
| 24 | + } |
| 25 | +}; |
| 26 | + |
| 27 | +Cluster.prototype.replicate = function () { |
| 28 | + var self = this; |
| 29 | + return self._sourceSlouch.db.all().each(function (db) { |
| 30 | + if (!self._params.skip || self._params.skip.indexOf(db) === -1) { |
| 31 | + return self._replicateDB(db, db); |
| 32 | + } |
| 33 | + }, self._throttler); |
| 34 | +}; |
| 35 | + |
| 36 | +Cluster.prototype._createDBIfMissing = function (db) { |
| 37 | + var self = this; |
| 38 | + return self._targetSlouch.db.exists(db).then(function (exists) { |
| 39 | + if (!exists) { |
| 40 | + return self._targetSlouch.db.create(db); |
| 41 | + } |
| 42 | + }); |
| 43 | +}; |
| 44 | + |
| 45 | +Cluster.prototype._replicateSecurity = function (sourceDB, targetDB) { |
| 46 | + var self = this; |
| 47 | + return self._sourceSlouch.security.get(sourceDB).then(function (security) { |
| 48 | + return self._targetSlouch.security.set(targetDB, security); |
| 49 | + }); |
| 50 | +}; |
| 51 | + |
| 52 | +Cluster.prototype._replicateRawDB = function (sourceDB, targetDB) { |
| 53 | + return this._sourceSlouch.db.replicate({ |
| 54 | + source: this._params.source + '/' + sourceDB, |
| 55 | + target: this._params.target + '/' + targetDB |
| 56 | + }); |
| 57 | +}; |
| 58 | + |
| 59 | +Cluster.prototype._replicateDB = function (sourceDB, targetDB) { |
| 60 | + var self = this; |
| 61 | + return self._createDBIfMissing(targetDB).then(function () { |
| 62 | + // Replicate security first so that security is put in place before data is copied over |
| 63 | + return self._replicateSecurity(sourceDB, targetDB); |
| 64 | + }).then(function () { |
| 65 | + return self._replicateRawDB(sourceDB, targetDB); |
| 66 | + }); |
| 67 | +}; |
| 68 | + |
| 69 | +module.exports = Cluster; |
0 commit comments