Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Circuit breaker #18

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
*.swp
/node_modules

#webstorm
.idea
63 changes: 18 additions & 45 deletions ShardedRedisClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ class ShardedRedisClient extends EventEmitter {
});
}

};
}

SHARDABLE.forEach((cmd) => {

Expand All @@ -280,59 +280,32 @@ SHARDABLE.forEach((cmd) => {

mainCb = _.once(mainCb);

const isReadCmd = READ_ONLY.indexOf(cmd) !== -1;
const timeout = isReadCmd ? this._readTimeout : this._writeTimeout;

const _this = this;
let timeoutHandler = null;
let breaker = client._breaker;

const timeoutCb = args[args.length - 1] = function (err) {
if (timeoutHandler)
clearTimeout(timeoutHandler);

if (!err) {
if (breaker)
breaker.pass();

return mainCb.apply(this, arguments);
}

// For now, both emit and log. Eventually, logging will be removed
_this.emit('err', new Error(`sharded-redis-client [${client.address}] err: ${err}`));
console.error(new Date().toISOString(), `sharded-redis-client [${client.address }] err: ${err}`);

if (breaker && err.message !== 'breaker open')
breaker.fail();

if (!client._isMaster) {
client = wrappedClient.slaves.next(client);
execute();

if (client._rrindex == startIndex)
client = findMasterClient(shardKey, _this._wrappedClients);
function execute() {
breaker.exec(cmd, args)
.then(result => mainCb(null, result))
.catch((err) => {
_this.emit('err', new Error(`sharded-redis-client [${client.address}] err: ${err}`));
console.error(new Date().toISOString(), `sharded-redis-client [${client.address }] err: ${err}`);

breaker = client._breaker;
if(!client._isMaster) {
client = wrappedClient.slaves.next(client);

return wrappedCmd(client, args);
}

mainCb.apply(this, arguments);
};

wrappedCmd(client, args);
if (client._rrindex == startIndex)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for this double equal instead of a triple equal?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was the old code, i just copied it. i guess it could be triple equal

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea I saw that after commenting. Probably better to switch to triple equal if we don't explicitly want to allow for anything other than the expected value.

client = findMasterClient(shardKey, _this._wrappedClients);

function wrappedCmd(client, args) {
if (!breaker || breaker.closed()) {
// Intentionally don't do this if timeout was set to 0
if (timeout)
timeoutHandler = setTimeout(timeoutCb, timeout, new Error('Redis call timed out'));
breaker = client._breaker;
return execute();
}

return client[cmd].apply(client, args);
}

timeoutCb(new Error('breaker open'));
mainCb(err);
});
}
}
};

ShardedRedisClient.prototype[cmd] = function () {
const args = arguments;
Expand Down
30 changes: 27 additions & 3 deletions lib/WrappedClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@
const _ = require('lodash');
const redis = require('redis');
const EventEmitter = require('events').EventEmitter;
const CircuitBreaker = require('circuit-breaker');
const RoundRobinSet = require('./RoundRobinSet');
const Brakes = require('brakes');
const Promise = require('bluebird');

function createClient(port, host, options) {
const client = redis.createClient(port, host, options.redisOptions);
Expand All @@ -30,8 +31,31 @@ function createClient(port, host, options) {
if (options.usePing)
setTimeout(() => setInterval(() => client.ping(_.noop), interval), timeout);

if (options.breakerConfig)
client._breaker = new CircuitBreaker(options.breakerConfig);
if (options.breakerConfig) {
options.breakerConfig = _.defaults(options.breakerConfig, {
statInterval: 2500,
threshold: 0.5,
circuitDuration: 15000,
timeout: 5000
});

const brake = new Brakes((cmd, args) => new Promise((resolve, reject) => {
args = _.cloneDeep(args);
args[length - 1] = (err, result) => {
if(err)
return reject(err);
return resolve(result);
};

return client[cmd].apply(client, args);
}), options.breakerConfig);

brake.on('snapshot', (snapshot) => console.log(`Snapshot ${snapshot} received`));
brake.on('circuitOpen', () => console.log(`Circuit Opened at ${new Date().toISOString()}`));
brake.on('circuitClosed', () => console.log(`Circuit Closed at ${new Date().toISOString()}`));

client._breaker = brake;
}

client.on('error', (e) => console.log(`Redis Error [${host}:${port}]: ${e} : ${new Date().toISOString()}`));
client.on('end', (e) => console.log(`Redis End [${host}:${port}]: ${e} : ${new Date().toISOString()}`));
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
"homepage": "https://github.com/Tinder/sharded-redis-client",
"dependencies": {
"async": "2.6.0",
"bluebird": "3.5.1",
"brakes": "2.6.0",
"circuit-breaker": "git://github.com/Tinder/circuit-breaker",
"hiredis": "0.5.0",
"lodash": "4.17.4",
Expand Down