forked from mediocre/petty-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
875 lines (695 loc) · 30.2 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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
const async = require('async');
const lock = require('lock').Lock();
const memoryCache = require('memory-cache');
const redis = require('redis');
function PettyCache(options) {
const intervals = {};
let redisClient;
if (options instanceof redis.RedisClient) {
redisClient = options;
} else {
redisClient = redis.createClient(options);
}
redisClient.on('error', err => console.warn(`Warning: Redis reported a client error: ${err}`));
function bulkGetFromRedis(keys, callback) {
// Try to get values from Redis
redisClient.mget(keys, function(err, data) {
if (err) {
return callback(err);
}
const values = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = data[i];
if (value === null) {
values[key] = { exists: false };
continue;
}
values[key] = { exists: true, value: PettyCache.parse(value) };
}
callback(null, values);
});
}
function getFromMemoryCache(key) {
// Try to get value from memory cache
const value = memoryCache.get(key);
// Return value from the memory cache if it's not null
if (value !== null) {
return { exists: true, value };
}
// If the key exists, the value in the memory cache is null
if (memoryCache.keys().includes(key)) {
return { exists: true, value: null };
}
// The key wasn't found in memory cache
return { exists: false };
}
function getFromRedis(key, callback) {
// Try to get value from Redis
redisClient.get(key, function(err, data) {
if (err) {
return callback(err);
}
// Return if the key wasn't found in Redis
if (data === null) {
return callback(null, { exists: false });
}
callback(null, { exists: true, value: PettyCache.parse(data) });
});
}
function getTtl(options) {
// Default TTL is 30-60 seconds
var ttl = {
max: 60000,
min: 30000
};
if (Object.prototype.hasOwnProperty.call(options, 'ttl')) {
if (typeof options.ttl === 'number') {
ttl.max = options.ttl;
ttl.min = options.ttl;
} else {
if (Object.prototype.hasOwnProperty.call(options.ttl, 'max')) {
ttl.max = options.ttl.max;
}
if (Object.prototype.hasOwnProperty.call(options.ttl, 'min')) {
ttl.min = options.ttl.min;
}
}
}
return ttl;
}
/**
* @param {Array} keys - An array of keys.
*/
this.bulkFetch = function(keys, func, callback) {
// If there aren't any keys, return
if (!keys.length) {
return callback(null, {});
}
const _keys = Array.from(new Set(keys));
const values = {};
// Try to get values from memory cache
for (var i = _keys.length - 1; i >= 0; i--) {
const key = _keys[i];
const result = getFromMemoryCache(key);
if (result.exists) {
values[key] = result.value;
_keys.splice(i, 1);
}
}
// If there aren't any keys left, return
if (!_keys.length) {
return callback(null, values);
}
const _this = this;
// Try to get values from Redis
bulkGetFromRedis(_keys, function(err, results) {
if (err) {
return callback(err);
}
for (var i = _keys.length - 1; i >= 0; i--) {
const key = _keys[i];
const result = results[key];
if (result.exists) {
_keys.splice(i, 1);
values[key] = result.value;
// Store value in memory cache with a short expiration
memoryCache.put(key, result.value, random(2000, 5000));
}
}
// If there aren't any keys left, return
if (!_keys.length) {
return callback(null, values);
}
// Execute the specified function for remaining keys
func(_keys, function(err, data) {
if (err) {
return callback(err);
}
Object.keys(data).forEach(key => values[key] = data[key]);
_this.bulkSet(data, err => callback(err, values));
});
});
};
/**
* @param {Array} keys - An array of keys.
*/
this.bulkGet = function(keys, callback) {
// If there aren't any keys, return
if (!keys.length) {
return callback(null, {});
}
const _keys = Array.from(new Set(keys));
const values = {};
// Try to get values from memory cache
for (var i = _keys.length - 1; i >= 0; i--) {
const key = _keys[i];
const result = getFromMemoryCache(key);
if (result.exists) {
values[key] = result.value;
_keys.splice(i, 1);
}
}
// If there aren't any keys left, return
if (!_keys.length) {
return callback(null, values);
}
// Try to get values from Redis
bulkGetFromRedis(_keys, function(err, results) {
if (err) {
return callback(err);
}
for (var i = 0; i < _keys.length; i++) {
var key = _keys[i];
var result = results[key];
if (!result.exists) {
values[key] = null;
continue;
}
values[key] = result.value;
// Store value in memory cache with a short expiration
memoryCache.put(key, result.value, random(2000, 5000));
}
callback(null, values);
});
};
this.bulkSet = function(values, options, callback) {
// Options are optional
if (!callback) {
callback = options;
options = {};
}
// Redis does not have a MSETEX command so we batch commands: http://redis.js.org/#api-clientbatchcommands
var batch = redisClient.batch();
Object.keys(values).forEach(key => {
var value = values[key];
// Store value in memory cache with a short expiration
memoryCache.put(key, value, random(2000, 5000));
// Default TTL is 30-60 seconds
var ttl = {
max: 60000,
min: 30000
};
if (Object.prototype.hasOwnProperty.call(options, 'ttl')) {
if (typeof options.ttl === 'number') {
ttl.max = options.ttl;
ttl.min = options.ttl;
} else {
if (Object.prototype.hasOwnProperty.call(options.ttl, 'max')) {
ttl.max = options.ttl.max;
}
if (Object.prototype.hasOwnProperty.call(options.ttl, 'min')) {
ttl.min = options.ttl.min;
}
}
}
// Add Redis command
batch.psetex(key, random(ttl.min, ttl.max), PettyCache.stringify(value));
});
batch.exec(function(err) {
callback(err);
});
};
this.del = function(key, callback) {
redisClient.del(key, function(err) {
if (err) {
return callback(err);
}
memoryCache.del(key);
callback();
});
};
// Returns data from cache if available;
// otherwise executes the specified function and places the results in cache before returning the data.
this.fetch = function(key, func, options, callback) {
options = options || {};
if (typeof options === 'function') {
callback = options;
options = {};
}
// Default callback is a noop
callback = callback || function() {};
// Try to get value from memory cache
var result = getFromMemoryCache(key);
// Return value from memory cache if it exists
if (result.exists) {
return callback(null, result.value);
}
const _this = this;
// Double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking
lock(`fetch-memory-cache-lock-${key}`, function(releaseMemoryCacheLock) {
async.reflect(function(callback) {
// Try to get value from memory cache
result = getFromMemoryCache(key);
// Return value from memory cache if it exists
if (result.exists) {
return callback(null, result.value);
}
// Try to get value from Redis
getFromRedis(key, function(err, result) {
if (err) {
return callback(err);
}
// Return value from Redis if it exists
if (result.exists) {
memoryCache.put(key, result.value, random(2000, 5000));
return callback(null, result.value);
}
// Double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking
lock(`fetch-redis-lock-${key}`, function(releaseRedisLock) {
async.reflect(function(callback) {
// Try to get value from memory cache
result = getFromMemoryCache(key);
// Return value from memory cache if it exists
if (result.exists) {
return callback(null, result.value);
}
// Try to get value from Redis
getFromRedis(key, function(err, result) {
if (err) {
return callback(err);
}
// Return value from Redis if it exists
if (result.exists) {
memoryCache.put(key, result.value, random(2000, 5000));
return callback(null, result.value);
}
// Execute the specified function and place the results in cache before returning the data
func(function(err, data) {
if (err) {
return callback(err);
}
_this.set(key, data, options, function(err) {
callback(err, data);
});
});
});
})(releaseRedisLock(function(err, result) {
if (result.error) {
return callback(result.error);
}
callback(null, result.value);
}));
});
});
})(releaseMemoryCacheLock(function(err, result) {
if (result.error) {
return callback(result.error);
}
callback(null, result.value);
}));
});
};
this.fetchAndRefresh = function(key, func, options, callback) {
options = options || {};
if (typeof options === 'function') {
callback = options;
options = {};
}
// Default callback is a noop
callback = callback || function() {};
options.ttl = getTtl(options);
const _this = this;
if (!intervals[key]) {
const delay = options.ttl.min / 2;
intervals[key] = setInterval(function() {
// This distributed lock prevents multiple clients from executing func at the same time
_this.mutex.lock(`interval-${key}`, { ttl: delay - 100 }, function(err) {
if (err) {
return;
}
// Execute the specified function and update cache
func(function(err, data) {
if (err) {
return;
}
_this.set(key, data, options);
});
});
}, delay);
}
this.fetch(key, func, options, callback);
};
this.get = function(key, callback) {
// Try to get value from memory cache
var result = getFromMemoryCache(key);
// Return value from memory cache if it exists
if (result.exists) {
return callback(null, result.value);
}
// Double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking
lock(`get-memory-cache-lock-${key}`, function(releaseMemoryCacheLock) {
async.reflect(function(callback) {
// Try to get value from memory cache
result = getFromMemoryCache(key);
// Return value from memory cache if it exists
if (result.exists) {
return callback(null, result.value);
}
getFromRedis(key, function(err, result) {
if (err) {
return callback(err);
}
if (!result.exists) {
return callback(null, null);
}
memoryCache.put(key, result.value, random(2000, 5000));
callback(null, result.value);
});
})(releaseMemoryCacheLock(function(err, result) {
if (result.error) {
return callback(result.error);
}
callback(null, result.value);
}));
});
};
this.mutex = {
lock: function(key, options, callback) {
// Options are optional
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
callback = callback || function() {};
options = options || {};
options.retry = Object.prototype.hasOwnProperty.call(options, 'retry') ? options.retry : {};
options.retry.interval = Object.prototype.hasOwnProperty.call(options.retry, 'interval') ? options.retry.interval : 100;
options.retry.times = Object.prototype.hasOwnProperty.call(options.retry, 'times') ? options.retry.times : 1;
options.ttl = Object.prototype.hasOwnProperty.call(options, 'ttl') ? options.ttl : 1000;
async.retry({ interval: options.retry.interval, times: options.retry.times }, function(callback) {
redisClient.set(key, '1', 'NX', 'PX', options.ttl, function(err, res) {
if (err) {
return callback(err);
}
if (!res) {
return callback(new Error());
}
if (res !== 'OK') {
return callback(new Error(res));
}
callback();
});
}, callback);
},
unlock: function(key, callback) {
callback = callback || function() {};
redisClient.del(key, callback);
}
};
this.patch = function(key, value, options, callback) {
if (!callback) {
callback = options;
options = {};
}
const _this = this;
this.get(key, function(err, data) {
if (err) {
return callback(err);
}
if (!data) {
return callback(new Error(`Key ${key} does not exist`));
}
for (var k in value) {
data[k] = value[k];
}
_this.set(key, data, options, callback);
});
};
this.semaphore = {
acquireLock: function(key, options, callback) {
// Options are optional
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
options.retry = Object.prototype.hasOwnProperty.call(options, 'retry') ? options.retry : {};
options.retry.interval = Object.prototype.hasOwnProperty.call(options.retry, 'interval') ? options.retry.interval : 100;
options.retry.times = Object.prototype.hasOwnProperty.call(options.retry, 'times') ? options.retry.times : 1;
options.ttl = Object.prototype.hasOwnProperty.call(options, 'ttl') ? options.ttl : 1000;
const _this = this;
async.retry({ interval: options.retry.interval, times: options.retry.times }, function(callback) {
// Mutex lock around semaphore
_this.mutex.lock(`lock:${key}`, { retry: { times: 100 } }, function(err) {
if (err) {
return callback(err);
}
redisClient.get(key, function(err, data) {
// If we encountered an error, unlock the mutex lock and return error
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
// If we don't have a previously created semaphore, unlock the mutex lock and return error
if (!data) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Semaphore ${key} doesn't exist.`)); });
}
var pool = JSON.parse(data);
// Try to find a slot that's available.
var index = pool.findIndex(s => s.status === 'available');
if (index === -1) {
index = pool.findIndex(s => s.ttl <= Date.now());
}
// If we don't have a previously created semaphore, unlock the mutex lock and return error
if (index === -1) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Semaphore ${key} doesn't have any available slots.`)); });
}
pool[index] = { status: 'acquired', ttl: Date.now() + options.ttl };
redisClient.set(key, JSON.stringify(pool), function(err) {
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
_this.mutex.unlock(`lock:${key}`, () => { callback(null, index); });
});
});
});
}, callback);
},
consumeLock: function(key, index, callback) {
callback = callback || function() {};
const _this = this;
// Mutex lock around semaphore
_this.mutex.lock(`lock:${key}`, { retry: { times: 100 } }, function(err) {
if (err) {
return callback(err);
}
redisClient.get(key, function(err, data) {
// If we encountered an error, unlock the mutex lock and return error
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
// If we don't have a previously created semaphore, unlock the mutex lock and return error
if (!data) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Semaphore ${key} doesn't exist.`)); });
}
var pool = JSON.parse(data);
// Ensure index exists.
if (pool.length <= index) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Index ${index} for semaphore ${key} is invalid.`)); });
}
pool[index] = { status: 'consumed' };
// Ensure at least one slot isn't consumed
if (pool.every(s => s.status === 'consumed')) {
pool[index] = { status: 'available' };
}
redisClient.set(key, JSON.stringify(pool), function(err) {
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
_this.mutex.unlock(`lock:${key}`, () => { callback(); });
});
});
});
},
expand: function(key, size, callback) {
callback = callback || function() {};
const _this = this;
_this.mutex.lock(`lock:${key}`, { retry: { times: 100 } }, function(err) {
if (err) {
return callback(err);
}
redisClient.get(key, function(err, data) {
// If we encountered an error, unlock the mutex lock and return error
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
// If we don't have a previously created semaphore, unlock the mutex lock and return error
if (!data) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Semaphore ${key} doesn't exist.`)); });
}
var pool = JSON.parse(data);
if (pool.length > size) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Cannot shrink pool, size is ${pool.length} and you requested a size of ${size}.`)); });
}
if (pool.length === size) {
return _this.mutex.unlock(`lock:${key}`, () => callback());
}
pool = pool.concat(Array(size - pool.length).fill({ status: 'available' }));
redisClient.set(key, JSON.stringify(pool), function(err) {
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
_this.mutex.unlock(`lock:${key}`, () => { callback(); });
});
});
});
},
releaseLock: function(key, index, callback) {
callback = callback || function() {};
const _this = this;
// Mutex lock around semaphore
_this.mutex.lock(`lock:${key}`, { retry: { times: 100 } }, function(err) {
if (err) {
return callback(err);
}
redisClient.get(key, function(err, data) {
// If we encountered an error, unlock the mutex lock and return error
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
// If we don't have a previously created semaphore, unlock the mutex lock and return error
if (!data) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Semaphore ${key} doesn't exist.`)); });
}
var pool = JSON.parse(data);
// Ensure index exists.
if (pool.length <= index) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Index ${index} for semaphore ${key} is invalid.`)); });
}
pool[index] = { status: 'available' };
redisClient.set(key, JSON.stringify(pool), function(err) {
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
_this.mutex.unlock(`lock:${key}`, () => { callback(); });
});
});
});
},
reset: function(key, callback) {
callback = callback || function() {};
const _this = this;
// Mutex lock around semaphore
this.mutex.lock(`lock:${key}`, { retry: { times: 100 } }, function(err) {
if (err) {
return callback(err);
}
// Try to get previously created semaphore
redisClient.get(key, function(err, data) {
// If we encountered an error, unlock the mutex lock and return error
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
// If we don't have a previously created semaphore, unlock the mutex lock and return error
if (!data) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(new Error(`Semaphore ${key} doesn't exist.`)); });
}
var pool = JSON.parse(data);
pool = Array(pool.length).fill({ status: 'available' });
redisClient.set(key, JSON.stringify(pool), function(err) {
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
_this.mutex.unlock(`lock:${key}`, () => { callback(null, pool); });
});
});
});
},
retrieveOrCreate: function(key, options, callback) {
// Options are optional
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
callback = callback || function() {};
options = options || {};
const _this = this;
// Mutex lock around semaphore retrival or creation
this.mutex.lock(`lock:${key}`, { retry: { times: 100 } }, function(err) {
if (err) {
return callback(err);
}
// Try to get previously created semaphore
redisClient.get(key, function(err, data) {
// If we encountered an error, unlock the mutex lock and return error
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
// If we retreived a previously created semaphore, unlock the mutex lock and return
if (data) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(null, JSON.parse(data)); });
}
var getSize = function(callback) {
if (typeof options.size === 'function') {
return options.size(callback);
}
callback(null, Object.prototype.hasOwnProperty.call(options, 'size') ? options.size : 1);
};
getSize(function(err, size) {
// If we encountered an error, unlock the mutex lock and return error
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
var pool = Array(Math.max(size, 1)).fill({ status: 'available' });
redisClient.set(key, JSON.stringify(pool), function(err) {
if (err) {
return _this.mutex.unlock(`lock:${key}`, () => { callback(err); });
}
_this.mutex.unlock(`lock:${key}`, () => { callback(null, pool); });
});
});
});
});
}
};
this.set = function(key, value, options, callback) {
options = options || {};
if (typeof options === 'function') {
callback = options;
options = {};
}
// Default callback is a noop
callback = callback || function() {};
// Store value in memory cache with a short expiration
memoryCache.put(key, value, random(2000, 5000));
// Get TTL based on specified options
const ttl = getTtl(options);
// Store value is Redis
redisClient.psetex(key, random(ttl.min, ttl.max), PettyCache.stringify(value), callback);
};
// Semaphore functions need to be bound to the main PettyCache object
for (var method in this.semaphore) {
this.semaphore[method] = this.semaphore[method].bind(this);
}
}
function random(min, max) {
if (min === max) {
return min;
}
return Math.floor(Math.random() * (max - min + 1) + min);
}
PettyCache.parse = function(text) {
return JSON.parse(text, function(k, v) {
if (v === '__NaN') {
return NaN;
} else if (v === '__null') {
return null;
} else if (v === '__undefined') {
return undefined;
}
return v;
});
};
PettyCache.stringify = function(value) {
return JSON.stringify(value, function(k, v) {
if (typeof v === 'number' && isNaN(v)) {
return '__NaN';
} else if (v === null) {
return '__null';
} else if (v === undefined) {
return '__undefined';
}
return v;
});
};
module.exports = PettyCache;