-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathredis-ext.js
336 lines (288 loc) · 9.6 KB
/
redis-ext.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
// redis-ext.js
// 2014, Laura Doktorova, https://github.com/olado/redis-ext
// Licensed under the MIT license.
var redis = require('redis')
, RedisClient = redis.RedisClient
, net = require('net')
, debug = require('debug')('redis-ext')
, debugjobs = require('debug')('jobs:redis-ext')
;
//redis.debug_mode = true;
redis.Sentinel = Sentinel;
redis.Queue = Queue;
module.exports = redis;
redis.createWithSentinel = function (sentinels, master, options) {
debug("create client with sentinel " + master);
return new Sentinel(sentinels).createClient(master, options);
};
redis.createQueue = function(client, queuekey, workFn) {
return new Queue(client, queuekey, workFn);
};
/*****************************************************************************
* Seemless sentinel support with auto-reconnect
*****************************************************************************/
function Sentinel(sentinels) {
this.sentinels = sentinels.concat();
this.clients = [];
};
Sentinel.prototype.createClient = function(master, options) {
var self = this
, stream = new net.Socket()
, client = new RedisClient(stream, {max_attempts:1})
, retry_max_delay = +(options && options.retry_max_delay) || 5*60*1000
, retry_min_delay = +(options && options.retry_delay) || 100
, retry_max_total = +(options && options.connect_timeout) || undefined
, retry_delay = retry_min_delay
, retry_total_time = 0
;
client.keepalive = true;
client.on("connect", function () {
retry_delay = retry_min_delay;
retry_total_time = 0;
});
// must be listened for to prevent exceptions, do not remove
client.on("error", function(err) {
debug("connection error: " + master + " " + client.host + ":" + client.port + ": " + err);
});
if (debug.enabled) {
client.on("ready", function() {
debug("connected OK " + master);
});
client.on("end", function (err) {
debug("connection ended " + master);
});
}
function onFailover() {
client.connection_gone("error");
}
client.quit = function() {
self.unsubscribe(onFailover);
client.keepalive = false;
RedisClient.prototype.quit.call(client);
};
client.return_error = function (err) {
RedisClient.prototype.return_error.call(client, err);
if (client.keepalive && !client.closing && !client.connecting
&& err && err.message && err.message.toLowerCase().indexOf("read only slave") !== -1) {
client.connection_gone("error");
}
};
client.connection_gone = function(why) {
debug("in connection gone " + master + " - " + why + " for " + client.host + ":" + client.port + ". Is closing? " + client.closing);
if (client.keepalive && !client.closing
&& (why === 'error' || why === 'end' || why === 'close')) {
if (!client.connecting) {
retry_delay = Math.min(Math.floor(retry_delay * 1.7), retry_max_delay);
retry_total_time += retry_delay;
if (retry_max_total !== undefined && retry_total_time > retry_max_total) {
return RedisClient.prototype.connection_gone.call(client, why);
} else {
debug("retrying " + master + " in " + retry_delay + " ms");
client.connecting = setTimeout(connect, retry_delay);
}
}
} else {
return RedisClient.prototype.connection_gone.call(client, why);
}
};
function connect() {
self.getMaster(master, function (err, host, port) {
if (client.connecting) {
clearTimeout(client.connecting);
client.connecting = undefined;
}
debug("in connect " + master + ": " + err + " " + host + ":" + port + " " + client.closing + " " + client.connected);
if (!client.closing) {
if (err || !host || !port) {
debug("SENTINEL ERROR, what happens next?");
client.on_error("sentinel error");
} else {
client.host = host;
client.port = port;
client.stream.connect(port, host);
}
}
});
}
onFailover.master = master;
this.subscribe(onFailover);
connect();
return client;
};
Sentinel.prototype.subscribe = function(callback) {
this.clients.push(callback);
};
Sentinel.prototype.unsubscribe = function(callback) {
var index = this.clients.indexOf(callback);
if (index !== -1) this.clients.splice(index, 1);
if (this.clients.length === 0 && this.pubsubClient) {
debug("Unsubscribed from sentinel pubsub");
this.pubsubClient.unsubscribe();
this.pubsubClient.quit();
this.pubsubClient = null;
}
};
function updateSubscription() {
if (this.pubsubClient) {
this.pubsubClient.unsubscribe();
this.pubsubClient.quit();
this.pubsubClient = null;
}
if (this.clients.length && this.sentinels[0]) {
var self = this, endpoint = this.sentinels[0];
this.pubsubClient = redis.createClient(endpoint.port, endpoint.host,{max_attempts:1});
this.pubsubClient.on("message", function(channel, message) {
debug("got failover message from sentinel", message);
var switchedMaster = message.substring(0, message.indexOf(" "));
for(var i = self.clients.length-1; i>=0; i--) {
if (self.clients[i].master === switchedMaster) self.clients[i]();
}
});
this.pubsubClient.on("error", function(err) {
debug("on error", err);
});
this.pubsubClient.on("end", function(err) {
if (this === self.pubsubClient) {
debug("on pubsub end");
self.pubsubClient = null;
// lost connectin with sentinel, refresh connections
for(var i = self.clients.length-1; i>=0; i--) {
self.clients[i]();
}
}
});
this.pubsubClient.subscribe('+switch-master');
}
}
Sentinel.prototype.getMaster = function(master, callback) {
var total = this.sentinels.length, index = -1, self = this;
// sequential as per http://redis.io/topics/sentinel-clients
function done(err, host, port) {
debug("in done for " + master + ": " + (err && err.message || '') + " " + host + ":" + port + " , index: " + index );
if (err || !host || !port) {
if (++index < total) {
getMasterFromSentinel(self.sentinels[index], master, done);
} else callback(err);
} else {
if (index) {
var failed = self.sentinels[0];
if (debug.enabled) debug("sentinel", failed.host, failed.port
, "failed, switching to"
, self.sentinels[index].host, self.sentinels[index].port);
self.sentinels[0] = self.sentinels[index];
self.sentinels[index] = failed;
updateSubscription.call(self);
} else if (!self.pubsubClient) {
updateSubscription.call(self);
}
callback(null, host, port);
return;
}
}
done();
};
function getMasterFromSentinel(endpoint, master, callback) {
var callbackSent = false
, sentinelClient = redis.createClient(endpoint.port, endpoint.host, {max_attempts:1});
sentinelClient.on("error", function(err) {
debug("error on talking to sentinel",endpoint.host,endpoint.port,"for",master,", ", callbackSent, err);
if (!callbackSent) {
callbackSent = true;
callback(err);
}
sentinelClient.end();
});
sentinelClient.send_command('SENTINEL', ['get-master-addr-by-name', master], function(err, result) {
if (callbackSent) return;
callbackSent = true;
if (err) return callback(err);
if (result) return callback(null, result[0], result[1]);
callback(new Error("Unkown master name: " + master));
});
sentinelClient.quit();
}
/*****************************************************************************
* Queue - auto-reconnecting queue
* connect
* send
* urgent
* close
*****************************************************************************/
function Queue(client, key, workFn, options) {
if (typeof client === 'function') {
this.clientFn = client;
} else {
this.client = client;
}
this.queueKey = key;
if (workFn) {
this.workFn = workFn;
this.timeout = (options && options.timeout || 5000)/1000;
}
}
Queue.prototype.close = function() {
if (this.client) this.client.quit();
};
Queue.prototype.send = function(msg) {
this.client.rpush(this.queueKey, msg);
};
Queue.prototype.urgent = function(msg) {
this.client.lpush(this.queueKey, msg);
};
Queue.prototype.connect = function() {
var self = this;
if (this.clientFn) {
if (this.client) this.client.quit();
this.client = this.clientFn();
}
var client = this.client;
// must be listened for to prevent exceptions, do not remove
client.on("error", function (err) {
debug(self.queueKey + ": Error " + err);
if (err && err._source === "worker") {
// if we reached here, throw it up
// you can listen for "workererror" to prevent this from happening
throw err;
}
});
if (debug.enabled) {
client.on("connect", function () {
debug("connected to queue " + self.queueKey + " @ " + client.host + ":" + client.port);
});
client.on("end", function (err) {
debug("connection to queue " + self.queueKey + " closed;" + (err ? " error: " + err : ""));
});
}
client.on("ready", function () {
if (self.workFn) {
debug("ready to accept jobs " + self.queueKey);
nextJob();
} else {
debug("ready to send jobs " + self.queueKey);
}
});
if (this.workFn) {
function nextJob() {
client.blpop(self.queueKey, self.timeout, function (err, replies) {
if (err) {
if (debugjobs.enabled) debugjobs("error on next job " + self.queueKey + " " + err);
} else if (replies && replies[1]) {
if (debugjobs.enabled) debugjobs(self.queueKey + " >" + replies[1]);
// node_redis has a try/catch block and emits an "error" event
try {
self.workFn.call(null, replies[1]);
} catch(callbackerr) {
if (!client.emit("workererror", callbackerr)) {
// If nobody cares we throw an exception here and then
// from on("error") above and further jobs won't be processed
callbackerr._source = "worker";
throw callbackerr;
}
}
}
if (!client.closing) setImmediate(nextJob);
});
}
}
return client;
};