2017-04-03 11:18:30 -04:00
|
|
|
metrics = require('metrics-sharelatex')
|
2014-11-25 10:26:33 -05:00
|
|
|
Settings = require('settings-sharelatex')
|
2017-05-04 10:22:54 -04:00
|
|
|
RedisWrapper = require("./RedisWrapper")
|
|
|
|
rclient = RedisWrapper.client("lock")
|
2014-11-25 10:26:33 -05:00
|
|
|
logger = require "logger-sharelatex"
|
|
|
|
|
|
|
|
module.exports = LockManager =
|
|
|
|
LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock
|
|
|
|
MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock
|
|
|
|
REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis.
|
|
|
|
|
2017-05-11 10:27:01 -04:00
|
|
|
_blockingKey : (key)-> "lock:web:{#{key}}"
|
2014-11-25 10:26:33 -05:00
|
|
|
|
|
|
|
tryLock : (key, callback = (err, isFree)->)->
|
|
|
|
rclient.set LockManager._blockingKey(key), "locked", "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)->
|
|
|
|
return callback(err) if err?
|
|
|
|
if gotLock == "OK"
|
2017-05-11 10:27:01 -04:00
|
|
|
metrics.inc "lock-not-blocking"
|
2014-11-25 10:26:33 -05:00
|
|
|
callback err, true
|
|
|
|
else
|
2017-05-11 10:27:01 -04:00
|
|
|
metrics.inc "lock-blocking"
|
|
|
|
logger.log key: key, redis_response: gotLock, "lock is locked"
|
2014-11-25 10:26:33 -05:00
|
|
|
callback err, false
|
|
|
|
|
|
|
|
getLock: (key, callback = (error) ->) ->
|
|
|
|
startTime = Date.now()
|
|
|
|
do attempt = () ->
|
|
|
|
if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME
|
|
|
|
return callback(new Error("Timeout"))
|
|
|
|
|
|
|
|
LockManager.tryLock key, (error, gotLock) ->
|
|
|
|
return callback(error) if error?
|
|
|
|
if gotLock
|
|
|
|
callback(null)
|
|
|
|
else
|
|
|
|
setTimeout attempt, LockManager.LOCK_TEST_INTERVAL
|
|
|
|
|
|
|
|
checkLock: (key, callback = (err, isFree)->)->
|
|
|
|
multi = rclient.multi()
|
|
|
|
multi.exists LockManager._blockingKey(key)
|
|
|
|
multi.exec (err, replys)->
|
|
|
|
return callback(err) if err?
|
|
|
|
exists = parseInt replys[0]
|
|
|
|
if exists == 1
|
2017-05-11 10:27:01 -04:00
|
|
|
metrics.inc "lock-blocking"
|
2014-11-25 10:26:33 -05:00
|
|
|
callback err, false
|
|
|
|
else
|
2017-05-11 10:27:01 -04:00
|
|
|
metrics.inc "lock-not-blocking"
|
2014-11-25 10:26:33 -05:00
|
|
|
callback err, true
|
|
|
|
|
|
|
|
releaseLock: (key, callback)->
|
|
|
|
rclient.del LockManager._blockingKey(key), callback
|
|
|
|
|
|
|
|
|