wildduck/lib/counters.js

83 lines
2.4 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
2017-10-03 16:18:23 +08:00
const fs = require('fs');
const ttlCounterScript = fs.readFileSync(__dirname + '/lua/ttlcounter.lua', 'utf-8');
const cachedCounterScript = fs.readFileSync(__dirname + '/lua/cachedcounter.lua', 'utf-8');
const limitedCounterScript = fs.readFileSync(__dirname + '/lua/limitedcounter.lua', 'utf-8');
const processLockScript = fs.readFileSync(__dirname + '/lua/process-lock.lua', 'utf-8');
const clientVersion = Date.now();
2017-07-18 16:17:36 +08:00
module.exports = redis => {
2017-10-03 16:18:23 +08:00
redis.defineCommand('ttlcounter', {
numberOfKeys: 1,
lua: ttlCounterScript
});
redis.defineCommand('cachedcounter', {
numberOfKeys: 1,
lua: cachedCounterScript
});
redis.defineCommand('limitedcounter', {
numberOfKeys: 1,
lua: limitedCounterScript
});
redis.defineCommand('processlock', {
numberOfKeys: 1,
lua: processLockScript
});
2019-07-12 15:21:48 +08:00
let asyncTTLCounter = async (key, count, max, windowSize) => {
if (!max || isNaN(max)) {
2019-07-11 15:52:43 +08:00
return {
2019-07-12 15:21:48 +08:00
success: true,
value: 0,
ttl: 0
2019-07-11 15:52:43 +08:00
};
2019-07-12 15:21:48 +08:00
}
let res = await redis.ttlcounter(key, count, max, windowSize || 86400);
return {
success: !!((res && res[0]) || 0),
value: (res && res[1]) || 0,
ttl: (res && res[2]) || 0
};
};
return {
asyncTTLCounter,
2019-07-11 15:52:43 +08:00
ttlcounter(key, count, max, windowSize, callback) {
2019-07-12 15:21:48 +08:00
return asyncTTLCounter(key, count, max, windowSize)
2019-07-11 15:52:43 +08:00
.then(res => callback(null, res))
.catch(callback);
2017-07-18 16:17:36 +08:00
},
cachedcounter(key, count, ttl, callback) {
2017-10-03 16:18:23 +08:00
redis.cachedcounter(key, count, ttl, (err, res) => {
2017-07-18 16:17:36 +08:00
if (err) {
return callback(err);
}
2017-10-03 16:18:23 +08:00
callback(null, res);
2017-07-18 16:17:36 +08:00
});
},
limitedcounter(key, entry, count, limit, callback) {
redis.limitedcounter(key, entry, count, limit, clientVersion, (err, res) => {
if (err) {
return callback(err);
}
return callback(null, {
success: !!((res && res[0]) || 0),
value: (res && res[1]) || 0
});
});
},
async processlock(key, identifier, ttl) {
return await redis.processlock(key, identifier, ttl);
}
};
};