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

fix(race-condition): acquire lock on set and incr if already set #59

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all 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
19 changes: 16 additions & 3 deletions src/RedisStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ const redis = require('redis');
*
* Class RedisStore
*/

async function SET_NX_EX (key, seconds, counter, incrIfExists) {
const OK = await this.client.sendCommand([
'SET', key, counter.toString(),
'NX',
'EX', seconds.toString()
])
if (!OK) var counterUpdated = await this.client.incrBy(key, incrIfExists)
return counterUpdated
}

class RedisStore extends Store {
/**
* constructor
Expand All @@ -51,19 +62,21 @@ class RedisStore extends Store {
async _hit(key, options, weight) {

let [counter, dateEnd] = await this.client.multi().get(key).ttl(key).exec();

if(counter === null) {
counter = weight;
dateEnd = Date.now() + options.interval;

const seconds = Math.ceil(options.interval / 1000);
await this.client.setEx(key, seconds.toString(), counter.toString());
const counterUpdated = await SET_NX_EX.call(this, key, seconds, counter, weight)
if (counterUpdated) { counter = counterUpdated }
} else if (dateEnd === -2 || dateEnd === -1) {
counter = counter + weight;
dateEnd = Date.now() + options.interval;

const seconds = Math.ceil(options.interval / 1000);
await this.client.setEx(key, seconds.toString(), counter.toString());
const counterUpdated = await SET_NX_EX.call(this, key, seconds, counter, weight)
if (counterUpdated) { counter = counterUpdated }
} else {
counter = await this.client.incrBy(key, weight);
}
Expand Down