From 4317123ffebe694322bc7656ae1ed391f360fb70 Mon Sep 17 00:00:00 2001 From: Overtorment Date: Wed, 9 Jan 2019 02:38:54 +0000 Subject: [PATCH] FIX (rel #3) --- class/Lock.js | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/class/Lock.js b/class/Lock.js index 288cf2f..f95c53a 100644 --- a/class/Lock.js +++ b/class/Lock.js @@ -1,5 +1,3 @@ -const crypto = require('crypto'); - export class Lock { /** * @@ -18,20 +16,10 @@ export class Lock { * @returns {Promise} */ async obtainLock() { - if (await this._redis.get(this._lock_key)) { - // someone already has the lock - return false; - } - - // trying to set the lock: - let buffer = crypto.randomBytes(10); - const randomValue = buffer.toString('hex'); - await this._redis.set(this._lock_key, randomValue); - - // checking if it was set: - let value = await this._redis.get(this._lock_key); - if (value !== randomValue) { - // someone else managed to obtain this lock + const timestamp = +new Date(); + let setResult = await this._redis.setnx(this._lock_key, timestamp); + if (!setResult) { + // it already held a value - failed locking return false; }