-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
102 lines (88 loc) · 2.54 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
// redis-eval/index.js
// Evaluate custom lua scripts
// builtin
var fs = require('fs'),
path = require('path'),
crypto = require('crypto');
// vendor
var async = require('async'),
_ = require('underscore');
// Once scripts are loaded into redis, we only refer to them as their sha-1 hash.
var shas = {};
// -- Export --
module.exports = evaluateScript;
// -- Main Eval Function --
function evaluateScript(redis, script_name, keys, args, callback) {
callback = onerror(callback)
var sha = shas[script_name];
if (sha) {
// Script is loaded
return evalSha(redis, sha, keys, args, callback);
}
readScript(script_name, function (err, script) {
if (err) return err;
var sha = shaify(script);
checkLoaded(redis, script_name, sha, function (err, exists) {
if (err) {
return callback(err)
}
if (exists) {
return evalSha(redis, sha, keys, args, callback);
}
// Load and then execute
async.waterfall([
_.bind(loadScript, null, redis, script_name, script),
function (sha, cb) {
evalSha(redis, sha, keys, args, cb);
}
], callback);
});
});
}
// If an error occurs, we must be prudent and assume data was lost. We clean the shas cache.
function onerror(cb) {
return function (err) {
if (err) {
shas = {}
arguments[0] = err instanceof Error ? err : new Error(err.toString())
}
cb.apply(null, arguments)
}
}
// -- Helper functions --
function shaify(script) {
return crypto.createHash('sha1').update(script).digest('hex');
}
function readScript(script_name, callback) {
fs.readFile(script_name, 'utf-8', callback);
}
function checkLoaded(redis, script_name, sha, callback) {
redis.multi()
.script('exists', sha)
.exec(function (err, exists) {
if (!err && exists) {
shas[script_name] = sha;
}
exists = _.flatten(exists);
callback(err, exists && exists.length > 0 && exists[0]);
});
}
// Evaluate a script that is already loaded
function evalSha(redis, sha, keys, args, callback) {
if (sha) {
return redis.evalsha.apply(redis, _.flatten([sha, keys.length, keys, args, callback]));
}
return callback(new Error('evalsha called for not loaded script'));
}
// Load a script into the script cache
function loadScript(redis, script_name, script, callback) {
redis.multi()
.script('load', script)
.exec(function (err, sha1) {
if (err) {
return callback(err);
}
shas[script_name] = sha1 && sha1.length && sha1[0];
callback(null, sha1);
});
}