RedisWebLocker.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. const metrics = require('@overleaf/metrics')
  2. const logger = require('@overleaf/logger')
  3. const os = require('os')
  4. const crypto = require('crypto')
  5. const async = require('async')
  6. const HOST = os.hostname()
  7. const PID = process.pid
  8. const RND = crypto.randomBytes(4).toString('hex')
  9. let COUNT = 0
  10. const LOCK_QUEUES = new Map() // queue lock requests for each name/id so they get the lock on a first-come first-served basis
  11. const UNLOCK_SCRIPT =
  12. 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end'
  13. module.exports = class RedisWebLocker {
  14. constructor({ rclient, getKey, options }) {
  15. this.rclient = rclient
  16. this.getKey = getKey
  17. // ms between each test of the lock
  18. this.LOCK_TEST_INTERVAL = options.lockTestInterval || 50
  19. // back off to ms between each test of the lock
  20. this.MAX_TEST_INTERVAL = options.maxTestInterval || 1000
  21. // ms maximum time to spend trying to get the lock
  22. this.MAX_LOCK_WAIT_TIME = options.maxLockWaitTime || 10000
  23. // seconds. Time until lock auto expires in redis
  24. this.REDIS_LOCK_EXPIRY = options.redisLockExpiry || 30
  25. // ms, if execution takes longer than this then log
  26. this.SLOW_EXECUTION_THRESHOLD = options.slowExecutionThreshold || 5000
  27. // read-only copy for unit tests
  28. this.unlockScript = UNLOCK_SCRIPT
  29. }
  30. // Use a signed lock value as described in
  31. // http://redis.io/topics/distlock#correct-implementation-with-a-single-instance
  32. // to prevent accidental unlocking by multiple processes
  33. randomLock() {
  34. const time = Date.now()
  35. return `locked:host=${HOST}:pid=${PID}:random=${RND}:time=${time}:count=${COUNT++}`
  36. }
  37. runWithLock(namespace, id, runner, callback) {
  38. // runner must be a function accepting a callback, e.g. runner = (cb) ->
  39. // This error is defined here so we get a useful stacktrace
  40. const slowExecutionError = new Error('slow execution during lock')
  41. const timer = new metrics.Timer(`lock.${namespace}`)
  42. const key = this.getKey(namespace, id)
  43. this._getLock(key, namespace, (error, lockValue) => {
  44. if (error != null) {
  45. return callback(error)
  46. }
  47. // The lock can expire in redis but the process carry on. This setTimeout call
  48. // is designed to log if this happens.
  49. function countIfExceededLockTimeout() {
  50. metrics.inc(`lock.${namespace}.exceeded_lock_timeout`)
  51. logger.debug('exceeded lock timeout', {
  52. namespace,
  53. id,
  54. slowExecutionError,
  55. })
  56. }
  57. const exceededLockTimeout = setTimeout(
  58. countIfExceededLockTimeout,
  59. this.REDIS_LOCK_EXPIRY * 1000
  60. )
  61. runner((error1, ...values) =>
  62. this._releaseLock(key, lockValue, error2 => {
  63. clearTimeout(exceededLockTimeout)
  64. const timeTaken = new Date() - timer.start
  65. if (timeTaken > this.SLOW_EXECUTION_THRESHOLD) {
  66. logger.debug('slow execution during lock', {
  67. namespace,
  68. id,
  69. timeTaken,
  70. slowExecutionError,
  71. })
  72. }
  73. timer.done()
  74. error = error1 || error2
  75. if (error != null) {
  76. return callback(error)
  77. }
  78. callback(null, ...values)
  79. })
  80. )
  81. })
  82. }
  83. _tryLock(key, namespace, callback) {
  84. const lockValue = this.randomLock()
  85. this.rclient.set(
  86. key,
  87. lockValue,
  88. 'EX',
  89. this.REDIS_LOCK_EXPIRY,
  90. 'NX',
  91. (err, gotLock) => {
  92. if (err != null) {
  93. return callback(err)
  94. }
  95. if (gotLock === 'OK') {
  96. metrics.inc(`lock.${namespace}.try.success`)
  97. callback(err, true, lockValue)
  98. } else {
  99. metrics.inc(`lock.${namespace}.try.failed`)
  100. logger.debug({ key, redis_response: gotLock }, 'lock is locked')
  101. callback(err, false)
  102. }
  103. }
  104. )
  105. }
  106. // it's sufficient to serialize within a process because that is where the parallel operations occur
  107. _getLock(key, namespace, callback) {
  108. // this is what we need to do for each lock we want to request
  109. const task = next =>
  110. this._getLockByPolling(key, namespace, (error, lockValue) => {
  111. // tell the queue to start trying to get the next lock (if any)
  112. next()
  113. // we have got a lock result, so we can continue with our own execution
  114. callback(error, lockValue)
  115. })
  116. // create a queue for this key if needed
  117. const queueName = `${key}:${namespace}`
  118. let queue = LOCK_QUEUES.get(queueName)
  119. if (queue == null) {
  120. const handler = (fn, cb) => fn(cb)
  121. // set up a new queue for this key
  122. queue = async.queue(handler, 1)
  123. queue.push(task)
  124. // remove the queue object when queue is empty
  125. queue.drain = () => LOCK_QUEUES.delete(queueName)
  126. // store the queue in our global map
  127. LOCK_QUEUES.set(queueName, queue)
  128. } else {
  129. // queue the request to get the lock
  130. queue.push(task)
  131. }
  132. }
  133. _getLockByPolling(key, namespace, callback) {
  134. const startTime = Date.now()
  135. const testInterval = this.LOCK_TEST_INTERVAL
  136. let attempts = 0
  137. const attempt = () => {
  138. if (Date.now() - startTime > this.MAX_LOCK_WAIT_TIME) {
  139. metrics.inc(`lock.${namespace}.get.failed`)
  140. return callback(new Error('Timeout'))
  141. }
  142. attempts += 1
  143. this._tryLock(key, namespace, (error, gotLock, lockValue) => {
  144. if (error != null) {
  145. return callback(error)
  146. }
  147. if (gotLock) {
  148. metrics.gauge(`lock.${namespace}.get.success.tries`, attempts)
  149. callback(null, lockValue)
  150. } else {
  151. setTimeout(attempt, testInterval)
  152. }
  153. })
  154. }
  155. attempt()
  156. }
  157. _releaseLock(key, lockValue, callback) {
  158. this.rclient.eval(this.unlockScript, 1, key, lockValue, (err, result) => {
  159. if (err != null) {
  160. callback(err)
  161. } else if (result != null && result !== 1) {
  162. // successful unlock should release exactly one key
  163. logger.warn(
  164. { key, lockValue, redis_err: err, redis_result: result },
  165. 'unlocking error'
  166. )
  167. metrics.inc('unlock-error')
  168. callback(new Error('tried to release timed out lock'))
  169. } else {
  170. callback(null, result)
  171. }
  172. })
  173. }
  174. }