-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathcache.js
262 lines (232 loc) · 6.32 KB
/
cache.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
var async = require('async');
var transactionTypes = require('../helpers/transactionTypes.js');
var cacheReady = true;
var errorCacheDisabled = 'Cache Unavailable';
var client;
var self;
var logger;
var cacheEnabled;
/**
* Cache module
* @constructor
* @param {Function} cb
* @param {Object} scope
*/
function Cache (cb, scope) {
self = this;
client = scope.cache.client;
logger = scope.logger;
cacheEnabled = scope.cache.cacheEnabled;
setImmediate(cb, null, self);
}
/**
* It gets the status of the redis connection
* @return {Boolean} status
*/
Cache.prototype.isConnected = function () {
// using client.ready because this variable is updated on client connected
return cacheEnabled && client && client.ready;
};
/**
* It gets the caching readiness and the connection of redis
* @return {Boolean} status
*/
Cache.prototype.isReady = function () {
return cacheReady && self.isConnected();
};
/**
* It gets the json value for a key from redis
* @param {String} key
* @param {Function} cb
* @return {Function} cb
*/
Cache.prototype.getJsonForKey = async function (key, cb) {
if (!self.isConnected()) {
return cb(errorCacheDisabled);
}
let parsedValue;
try {
const value = await client.get(key);
parsedValue = JSON.parse(value);
} catch (err) {
cb(err, key);
return;
}
cb(null, parsedValue);
};
/**
* It sets json value for a key in redis
* @param {String} key
* @param {Object} value
* @param {Function} cb
*/
Cache.prototype.setJsonForKey = async function (key, value, cb) {
if (!self.isConnected()) {
if (typeof cb === 'function') {
cb(errorCacheDisabled);
}
return;
}
let res;
try {
// redis calls toString on objects, which converts it to object [object] so calling stringify before saving
res = await client.set(key, JSON.stringify(value))
} catch (err) {
if (typeof cb === 'function') {
cb(err, value);
}
}
if (typeof cb === 'function') {
cb(null, res);
}
};
/**
* It deletes json value for a key in redis
* @param {String} key
*/
Cache.prototype.deleteJsonForKey = function (key, cb) {
if (!self.isConnected()) {
return cb(errorCacheDisabled);
}
client.del(key)
.then((res) => cb(null, res))
.catch((err) => cb(err, key));
};
/**
* It scans keys with provided pattern in redis db and deletes the entries that match
* @param {String} pattern
* @param {Function} cb
*/
Cache.prototype.removeByPattern = function (pattern, cb) {
if (!self.isConnected()) {
return cb(errorCacheDisabled);
}
var keys, cursor = 0;
async.doWhilst(function iteratee (whilstCb) {
client.scan(cursor, { MATCH: pattern })
.then((res) => {
cursor = res.cursor;
keys = res.keys;
if (keys.length > 0) {
client.del(keys)
.then((res) => whilstCb(null, res))
.catch((err) => whilstCb(err));
} else {
return whilstCb();
}
})
.catch((err) => {
return whilstCb(err);
});
}, function test (...args) {
return args[args.length - 1](null, cursor > 0);
}, cb);
};
/**
* It removes all entries from redis db
* @param {Function} cb
*/
Cache.prototype.flushDb = function (cb) {
if (!self.isConnected()) {
return cb(errorCacheDisabled);
}
client.flushDb()
.then((res) => cb(null, res))
.catch((err) => cb(err));
};
/**
* On application clean event, it quits the redis connection
* @param {Function} cb
*/
Cache.prototype.cleanup = function (cb) {
self.quit(cb);
};
/**
* it quits the redis connection
* @param {Function} cb
*/
Cache.prototype.quit = function (cb) {
if (!self.isConnected()) {
// because connection isn't established in the first place.
return cb();
}
client.quit()
.then((res) => cb(null, res))
.catch((err) => cb(err));
};
/**
* This function will be triggered on new block, it will clear all cache entires.
* @param {Block} block
* @param {Broadcast} broadcast
* @param {Function} cb
*/
Cache.prototype.onNewBlock = function (block, broadcast, cb) {
cb = cb || function () { };
if (!self.isReady()) { return cb(errorCacheDisabled); }
async.map(['/api/blocks*', '/api/transactions*'], function (pattern, mapCb) {
self.removeByPattern(pattern, function (err) {
if (err) {
logger.error(['Error clearing keys with pattern:', pattern, ' on new block'].join(' '));
} else {
logger.debug(['keys with pattern:', pattern, 'cleared from cache on new block'].join(' '));
}
mapCb(err);
});
}, cb);
};
/**
* This function will be triggered when a round finishes, it will clear all cache entires.
* @param {Round} round
* @param {Function} cb
*/
Cache.prototype.onFinishRound = function (round, cb) {
cb = cb || function () { };
if (!self.isReady()) { return cb(errorCacheDisabled); }
var pattern = '/api/delegates*';
self.removeByPattern(pattern, function (err) {
if (err) {
logger.error(['Error clearing keys with pattern:', pattern, ' round finish'].join(' '));
} else {
logger.debug(['keys with pattern: ', pattern, 'cleared from cache new Round'].join(' '));
}
return cb(err);
});
};
/**
* This function will be triggered when transactions are processed, it will clear all cache entires if there is a delegate type transaction.
* @param {Transactions[]} transactions
* @param {Function} cb
*/
Cache.prototype.onTransactionsSaved = function (transactions, cb) {
cb = cb || function () { };
if (!self.isReady()) { return cb(errorCacheDisabled); }
var pattern = '/api/delegates*';
var delegateTransaction = transactions.find(function (trs) {
return !!trs && trs.type === transactionTypes.DELEGATE;
});
if (!!delegateTransaction) {
self.removeByPattern(pattern, function (err) {
if (err) {
logger.error(['Error clearing keys with pattern:', pattern, ' on delegate trs'].join(' '));
} else {
logger.debug(['keys with pattern:', pattern, 'cleared from cache on delegate trs'].join(' '));
}
return cb(err);
});
} else {
cb();
}
};
/**
* Disable any changes in cache while syncing
*/
Cache.prototype.onSyncStarted = function () {
cacheReady = false;
};
/**
* Enable changes in cache after syncing finished
*/
Cache.prototype.onSyncFinished = function () {
cacheReady = true;
};
module.exports = Cache;