1 | 'use strict';
|
2 |
|
3 | var util = require('util');
|
4 | var Promise = require('bluebird');
|
5 | var EventEmitter = require('events');
|
6 |
|
7 |
|
8 | if(typeof EventEmitter.EventEmitter === 'function')
|
9 | EventEmitter = EventEmitter.EventEmitter;
|
10 |
|
11 |
|
12 |
|
13 | var unlockScript = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
|
14 | var extendScript = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("pexpire", KEYS[1], ARGV[2]) else return 0 end';
|
15 |
|
16 |
|
17 | var defaults = {
|
18 | driftFactor: 0.01,
|
19 | retryCount: 3,
|
20 | retryDelay: 200
|
21 | };
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | function LockError(message) {
|
31 | Error.call(this);
|
32 | Error.captureStackTrace(this, LockError);
|
33 | this.name = 'LockError';
|
34 | this.message = message || 'Failed to lock the resource.';
|
35 | }
|
36 |
|
37 | util.inherits(LockError, Error);
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 | function Lock(redlock, resource, value, expiration) {
|
50 | this.redlock = redlock;
|
51 | this.resource = resource;
|
52 | this.value = value;
|
53 | this.expiration = expiration;
|
54 | }
|
55 |
|
56 | Lock.prototype.unlock = function unlock(callback) {
|
57 | return this.redlock.unlock(this, callback);
|
58 | };
|
59 |
|
60 | Lock.prototype.extend = function extend(ttl, callback) {
|
61 | return this.redlock.extend(this, ttl, callback);
|
62 | };
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | function Redlock(clients, options) {
|
75 |
|
76 | options = options || {};
|
77 | this.driftFactor = typeof options.driftFactor === 'number' ? options.driftFactor : defaults.driftFactor;
|
78 | this.retryCount = typeof options.retryCount === 'number' ? options.retryCount : defaults.retryCount;
|
79 | this.retryDelay = typeof options.retryDelay === 'number' ? options.retryDelay : defaults.retryDelay;
|
80 |
|
81 |
|
82 | this.servers = clients;
|
83 | if(this.servers.length === 0)
|
84 | throw new Error('Redlock must be instantiated with at least one redis server.');
|
85 | }
|
86 |
|
87 |
|
88 | util.inherits(Redlock, EventEmitter);
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | Redlock.LockError = LockError;
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 | Redlock.prototype.acquire =
|
110 | Redlock.prototype.lock = function lock(resource, ttl, callback) {
|
111 | return this._lock(resource, null, ttl, callback);
|
112 | };
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 | Redlock.prototype.disposer = function disposer(resource, ttl, errorHandler) {
|
131 | errorHandler = errorHandler || function(err) {};
|
132 | return this._lock(resource, null, ttl).disposer(function(lock){
|
133 | return lock.unlock().catch(errorHandler);
|
134 | });
|
135 | };
|
136 |
|
137 |
|
138 |
|
139 |
|
140 |
|
141 |
|
142 |
|
143 |
|
144 | Redlock.prototype.release =
|
145 | Redlock.prototype.unlock = function unlock(lock, callback) {
|
146 | var self = this;
|
147 | return new Promise(function(resolve, reject) {
|
148 |
|
149 |
|
150 | lock.expiration = 0;
|
151 |
|
152 |
|
153 | var votes = 0;
|
154 |
|
155 |
|
156 | var quorum = Math.floor(self.servers.length / 2) + 1;
|
157 |
|
158 |
|
159 | var waiting = self.servers.length;
|
160 |
|
161 |
|
162 | self.servers.forEach(function(server){
|
163 | server.eval(unlockScript, 1, lock.resource, lock.value, loop);
|
164 | });
|
165 |
|
166 | function loop(err, response) {
|
167 | if(err) self.emit('clientError', err);
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 |
|
174 | if(typeof response === 'number' && (response === 0 || response === 1))
|
175 | votes++;
|
176 |
|
177 | if(waiting-- > 1) return;
|
178 |
|
179 |
|
180 | if(votes >= quorum)
|
181 | return resolve();
|
182 |
|
183 |
|
184 | return reject(new LockError('Unable to fully release the lock on resource "' + lock.resource + '".'));
|
185 | }
|
186 | })
|
187 |
|
188 |
|
189 | .nodeify(callback);
|
190 | };
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 | Redlock.prototype.extend = function extend(lock, ttl, callback) {
|
197 | var self = this;
|
198 |
|
199 |
|
200 | if(lock.expiration < Date.now())
|
201 | return Promise.reject(new LockError('Cannot extend lock on resource "' + lock.resource + '" because the lock has already expired.')).nodeify(callback);
|
202 |
|
203 |
|
204 | return self._lock(lock.resource, lock.value, ttl)
|
205 |
|
206 |
|
207 | .then(function(extension){
|
208 | lock.value = extension.value;
|
209 | lock.expiration = extension.expiration;
|
210 | return lock;
|
211 | })
|
212 |
|
213 |
|
214 | .nodeify(callback);
|
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 | Redlock.prototype._lock = function _lock(resource, value, ttl, callback) {
|
248 | var self = this;
|
249 | return new Promise(function(resolve, reject) {
|
250 | var request;
|
251 |
|
252 |
|
253 | var attempts = 0;
|
254 |
|
255 |
|
256 |
|
257 | if(value === null) {
|
258 | value = self._random();
|
259 | request = function(server, loop){
|
260 | return server.set(resource, value, 'NX', 'PX', ttl, loop);
|
261 | };
|
262 | }
|
263 |
|
264 |
|
265 | else {
|
266 | request = function(server, loop){
|
267 | return server.eval(extendScript, 1, resource, value, ttl, loop);
|
268 | };
|
269 | }
|
270 |
|
271 | function attempt(){
|
272 | attempts++;
|
273 |
|
274 |
|
275 | var start = Date.now();
|
276 |
|
277 |
|
278 | var votes = 0;
|
279 |
|
280 |
|
281 | var quorum = Math.floor(self.servers.length / 2) + 1;
|
282 |
|
283 |
|
284 | var waiting = self.servers.length;
|
285 |
|
286 | function loop(err, response) {
|
287 | if(err) self.emit('clientError', err);
|
288 | if(response) votes++;
|
289 | if(waiting-- > 1) return;
|
290 |
|
291 |
|
292 |
|
293 | var drift = Math.round(self.driftFactor * ttl) + 2;
|
294 | var lock = new Lock(self, resource, value, start + ttl - drift);
|
295 |
|
296 |
|
297 | if(votes >= quorum && lock.expiration > Date.now())
|
298 | return resolve(lock);
|
299 |
|
300 |
|
301 |
|
302 | return lock.unlock(function(){
|
303 |
|
304 |
|
305 | if(attempts <= self.retryCount)
|
306 | return setTimeout(attempt, self.retryDelay);
|
307 |
|
308 |
|
309 | return reject(new LockError('Exceeded ' + self.retryCount + ' attempts to lock the resource "' + resource + '".'));
|
310 | });
|
311 | }
|
312 |
|
313 | return self.servers.forEach(function(server){
|
314 | return request(server, loop);
|
315 | });
|
316 | }
|
317 |
|
318 | return attempt();
|
319 | })
|
320 |
|
321 |
|
322 | .nodeify(callback);
|
323 | };
|
324 |
|
325 |
|
326 | Redlock.prototype._random = function _random(){
|
327 | return Math.random().toString(36).slice(2);
|
328 | };
|
329 |
|
330 |
|
331 | module.exports = Redlock;
|