-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
324 lines (299 loc) · 10.5 KB
/
index.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
'use strict';
var redisLib = require('redis');
var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN;
var inherits = require('inherits');
var Buffer = require('safe-buffer').Buffer;
var url = require('url');
var RDIterator = require('./iterator');
var scriptsLoader = require('./scriptsLoader');
var setImmediate = require('immediate');
/**
* @param location prefix for the database.
*/
function RedisDown(location) {
if (!(this instanceof RedisDown)) {
return new RedisDown(location);
}
AbstractLevelDOWN.call(this, {
snapshots: false,
seek: false
});
this.location = location;
}
module.exports = RedisDown;
// default number of items fetched at once during by an iterator
RedisDown.defaultHighWaterMark = 128;
// our new prototype inherits from AbstractLevelDOWN
inherits(RedisDown, AbstractLevelDOWN);
// host:port -> { db: client, locations: [] }
RedisDown.dbs = {};
// location as passed in the constructor -> connection-options
// Used by pouchdb when calling RedisDown.destroy
RedisDown.connectionByLocation = {};
/**
* @param options: either one of
* - redis-client instance.
* - object with { redis: redis-client}
* - object with { port: portNumber, host: host, ... other options passed to node-redis }
*
* When a client is created it is reused across instances of
* RedisDOWN unless the option `ownClient` is truthy.
* For a client to be reused, it requires the same port, host and options.
*/
RedisDown.prototype._open = function (options, callback) {
var originalOptions = {};
Object.assign(originalOptions, options);
this.highWaterMark = options.highWaterMark || RedisDown.defaultHighWaterMark;
if (typeof options.hget === 'function') {
this.db = options.hget;
this.quitDbOnClose = false;
} else if (options.redis && typeof options.redis.hget === 'function') {
this.db = options.redis;
this.quitDbOnClose = false;
} else if (!options.ownClient) {
options = _makeRedisId(this.location, options);
this.redisId = JSON.stringify(options);
var dbDesc = RedisDown.dbs[this.redisId];
if (dbDesc) {
this.db = dbDesc.db;
dbDesc.locations.push(sanitizeLocation(this.location));
}
} else {
options = _makeRedisId(this.location, options);
this.quitDbOnClose = true;
}
var uriLocation = this.location;
if (typeof RedisDown.connectionByLocation[uriLocation] === 'undefined' && originalOptions.createIfMissing === false) {
setImmediate(function () {
callback(new Error('Database does not exist.'));
});
} else {
this.location = sanitizeLocation(this.location);
if (!this.db) {
if (options.port || options.host) {
// Set return_buffers to true by default
if (options['return_buffers'] !== false) {
options['return_buffers'] = true;
}
this.db = redisLib.createClient(options.port, options.host, options);
} else {
this.db = redisLib.createClient({return_buffers: true});
}
if (!options.ownClient) {
RedisDown.dbs[this.redisId] = {db: this.db, locations: [this.location]};
}
}
// Also store the options to connect to the database for RedisDown.destroy
RedisDown.connectionByLocation[uriLocation] = options;
var self = this;
if (options && options.destroyOnOpen) {
return this.destroy(false, function () {
setImmediate(function () {
callback(null, self);
});
});
}
scriptsLoader.preload(this.db, function () {
setImmediate(function () {
callback(null, self);
});
});
}
};
RedisDown.prototype._get = function (key, options, callback) {
this.db.hget(this.location + ':h', cleanKey(key), function (e, v) {
if (e) {
return setImmediate(function callNext() {
return callback(e);
});
}
if (v === null || typeof v === undefined) {
return setImmediate(function callNext() {
callback(new Error('NotFound'), undefined);
});
}
if (options.asBuffer === false || options.raw) {
callback(null, String(v || ''));
} else if (v === null || v === undefined) {
callback(null, Buffer.from(''));
} else {
callback(null, Buffer.from(v));
}
});
};
RedisDown.prototype._put = function (key, rawvalue, opt, callback) {
if (typeof rawvalue === 'undefined' || rawvalue === null) {
rawvalue = '';
}
this.__exec(this.__appendPutCmd([], key, rawvalue.toString()), callback);
};
RedisDown.prototype._del = function (key, opt, cb) {
this.__exec(this.__appendDelCmd([], key), cb);
};
RedisDown.prototype._batch = function (operationArray, options, callback) {
var commandList = [];
for (var i = 0; i < operationArray.length; i++) {
var operation = operationArray[i];
if (operation.type === 'put') {
this.__appendPutCmd(commandList, operation.key, operation.value, operation.prefix);
} else if (operation.type === 'del') {
this.__appendDelCmd(commandList, operation.key, operation.prefix);
} else {
return callback(new Error('Unknow type of operation ' + JSON.stringify(operation)));
}
}
this.__exec(commandList, callback);
};
RedisDown.prototype.__getPrefix = function (prefix) {
return prefix || this.location;
};
RedisDown.prototype.__appendPutCmd = function (commandList, key, value, prefix) {
var resolvedPrefix = this.__getPrefix(prefix);
key = cleanKey(key);
commandList.push(['hset', resolvedPrefix + ':h', key, value === undefined ? '' : value]);
commandList.push(['zadd', resolvedPrefix + ':z', 0, key]);
return commandList;
};
RedisDown.prototype.__appendDelCmd = function (commandList, key, prefix) {
key = cleanKey(key);
var resolvedPrefix = this.__getPrefix(prefix);
commandList.push(['hdel', resolvedPrefix + ':h', key]);
commandList.push(['zrem', resolvedPrefix + ':z', key]);
return commandList;
};
RedisDown.prototype.__exec = function (commandList, callback) {
this.db.multi(commandList).exec(callback);
};
RedisDown.prototype._close = function (callback) {
this.closed = true;
if (this.quitDbOnClose === false) {
return setImmediate(callback);
}
if (this.quitDbOnClose !== true) {
// close the client only if it is not used by others:
var dbDesc = RedisDown.dbs[this.redisId];
if (dbDesc) {
var location = this.location;
dbDesc.locations = dbDesc.locations.filter(function (loc) {
return loc !== location;
});
if (dbDesc.locations.length !== 0) {
// a still used by another RedisDOWN
return setImmediate(callback);
}
delete RedisDown.dbs[this.redisId];
}
}
try {
this.db.quit();
} catch (x) {
console.log('Error attempting to quit the redis client', x);
}
setImmediate(callback);
};
RedisDown.prototype._iterator = function (options) {
return new RDIterator(this, options);
};
// Special operations
/**
* Opens a new redis client del the hset.
* Quit the client.
* Callbacks
*/
RedisDown.destroy = function (location, options, callback) {
if (typeof options === 'function') {
callback = options;
options = RedisDown.connectionByLocation[location];
delete RedisDown.connectionByLocation[location];
}
if (!options) {
return callback(new Error('No connection registered for "' + location + '"'));
}
var sanitizedLocation = sanitizeLocation(location);
var client = redisLib.createClient(options.port, options.host, options);
client.del(sanitizedLocation + ':h', sanitizedLocation + ':z', function (e) {
client.quit();
callback(e);
});
};
/**
* @param doClose: optional parameter, by default true to close the client
*/
RedisDown.prototype.destroy = function (doClose, callback) {
if (!callback && typeof doClose === 'function') {
callback = doClose;
doClose = true;
}
var self = this;
this.db.del(this.location + ':h', this.location + ':z', function (e) {
if (doClose) {
self.close(callback);
} else {
callback();
}
});
};
/**
* Internal: generate the options for redis.
* create an identifier for a redis client from the options passed to _open.
* when the identifier is identical, it is safe to reuse the same client.
*/
function _makeRedisId(location, options) {
var redisIdOptions = ['host', 'port',
'parser', 'return_buffers', 'detect_buffers', 'socket_nodelay', 'no_ready_check',
'enable_offline_queue', 'retry_max_delay', 'connect_timeout', 'max_attempts'
];
var redisOptions = {};
redisIdOptions.forEach(function (opt) {
if (options[opt] !== undefined && options[opt] !== null) {
redisOptions[opt] = options[opt];
}
});
if (options.url || (location && location.indexOf('://') !== -1)) {
var redisURL = url.parse(options.url || location);
redisOptions.port = redisURL.port;
redisOptions.host = redisURL.hostname;
if (redisURL.auth) {
redisOptions.auth_pass = redisURL.auth.split(':')[1];
}
}
return redisOptions;
}
function sanitizeLocation(location) {
if (!location) {
return 'rd';
}
if (location.indexOf('://')) {
location = url.parse(location).pathname || 'rd';
}
if (location.charAt(0) === '/') {
return location.substring(1);
}
// Keep the hash delimited by curly brackets safe
// as it is used by redis-cluster to force the selection of a slot.
if (location.indexOf('%7B') === 0 && location.indexOf('%7D') > 0) {
location = location.replace('%7B', '{').replace('%7D', '}');
}
return location;
}
function cleanKey(key) {
if (Buffer.isBuffer(key)) {
return key;
} else {
return key.toString();
}
}
RedisDown.reset = function (callback) {
for (var k in RedisDown.dbs) {
if (RedisDown.dbs.hasOwnProperty(k)) {
try {
var db = RedisDown.dbs[k].db;
db.quit();
} catch (x) {
}
}
}
if (callback) {
return callback();
}
};