Copy utils from cytube-common and remove dep

The `cytube-common` module was created as part of a now-defunct
experiment and since then has just remained a crufty container for a few
utils.  Moved the utils to the main repo and removed the dependency.
This commit is contained in:
Calvin Montgomery 2017-07-19 20:47:02 -07:00
parent e780e7dadb
commit ff3ececc36
13 changed files with 358 additions and 9 deletions

44
src/redis/lualoader.js Normal file
View file

@ -0,0 +1,44 @@
import fs from 'fs';
import logger from '../logger';
const CACHE = {};
const EVALSHA_CACHE = {};
export function loadLuaScript(filename) {
if (CACHE.hasOwnProperty(filename)) {
return CACHE[filename];
}
CACHE[filename] = fs.readFileSync(filename).toString('utf8');
return CACHE[filename];
}
function loadAndExecuteScript(redisClient, filename, args) {
return redisClient.scriptAsync('load', loadLuaScript(filename))
.then(sha => {
EVALSHA_CACHE[filename] = sha;
logger.debug(`Cached ${filename} as ${sha}`);
return runEvalSha(redisClient, filename, args);
});
}
function runEvalSha(redisClient, filename, args) {
const evalInput = args.slice();
evalInput.unshift(EVALSHA_CACHE[filename])
return redisClient.evalshaAsync.apply(redisClient, evalInput);
}
export function runLuaScript(redisClient, filename, args) {
if (EVALSHA_CACHE.hasOwnProperty(filename)) {
return runEvalSha(redisClient, filename, args).catch(error => {
if (error.code === 'NOSCRIPT') {
logger.warn(`Got NOSCRIPT error for ${filename}, reloading script`);
return loadAndExecuteScript(redisClient, filename, args);
} else {
throw error;
}
});
} else {
return loadAndExecuteScript(redisClient, filename, args);
}
}

View file

@ -0,0 +1,49 @@
import clone from 'clone';
import redis from 'redis';
import Promise from 'bluebird';
Promise.promisifyAll(redis.RedisClient.prototype);
Promise.promisifyAll(redis.Multi.prototype);
/**
* Provider for RedisClients.
*/
class RedisClientProvider {
/**
* Create a new RedisClientProvider.
*
* @param {Object} redisConfig default configuration to use
* @see {@link https://www.npmjs.com/package/redis}
*/
constructor(redisConfig) {
this.redisConfig = redisConfig;
}
/**
* Get a RedisClient.
*
* @param {Object} options optional override configuration for the RedisClient
* @return {RedisClient} redis client using the provided configuration
*/
get(options = {}) {
const config = clone(this.redisConfig);
for (const key in options) {
config[key] = options[key];
}
const client = redis.createClient(config);
client.on('error', this._defaultErrorHandler);
return client;
}
/**
* Handle an <code>'error'</code> event from a provided client.
*
* @param {Error} err error from the client
* @private
*/
_defaultErrorHandler(err) {
}
}
export default RedisClientProvider