LockManager.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Fix any style issues and re-enable lint.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS101: Remove unnecessary use of Array.from
  6. * DS102: Remove unnecessary code created because of implicit returns
  7. * DS207: Consider shorter variations of null checks
  8. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  9. */
  10. import { promisify } from 'node:util'
  11. import async from 'async'
  12. import metrics from '@overleaf/metrics'
  13. import Settings from '@overleaf/settings'
  14. import redis from '@overleaf/redis-wrapper'
  15. import os from 'node:os'
  16. import crypto from 'node:crypto'
  17. import logger from '@overleaf/logger'
  18. import OError from '@overleaf/o-error'
  19. const LOCK_TEST_INTERVAL = 50 // 50ms between each test of the lock
  20. const MAX_LOCK_WAIT_TIME = 10000 // 10s maximum time to spend trying to get the lock
  21. export const LOCK_TTL = 360 // seconds
  22. export const MIN_LOCK_EXTENSION_INTERVAL = 1000 // 1s minimum interval when extending a lock
  23. export const UNLOCK_SCRIPT =
  24. 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end'
  25. const EXTEND_SCRIPT =
  26. 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return 0 end'
  27. const HOST = os.hostname()
  28. const PID = process.pid
  29. const RND = crypto.randomBytes(4).toString('hex')
  30. let COUNT = 0
  31. const rclient = redis.createClient(Settings.redis.lock)
  32. /**
  33. * Container for functions that need to be mocked in tests
  34. *
  35. * TODO: Rewrite tests in terms of exported functions only
  36. */
  37. export const _mocks = {}
  38. // Use a signed lock value as described in
  39. // http://redis.io/topics/distlock#correct-implementation-with-a-single-instance
  40. // to prevent accidental unlocking by multiple processes
  41. _mocks.randomLock = () => {
  42. const time = Date.now()
  43. return `locked:host=${HOST}:pid=${PID}:random=${RND}:time=${time}:count=${COUNT++}`
  44. }
  45. export function randomLock(...args) {
  46. return _mocks.randomLock(...args)
  47. }
  48. _mocks.tryLock = (key, callback) => {
  49. if (callback == null) {
  50. callback = function () {}
  51. }
  52. const lockValue = randomLock()
  53. return rclient.set(
  54. key,
  55. lockValue,
  56. 'EX',
  57. LOCK_TTL,
  58. 'NX',
  59. function (err, gotLock) {
  60. if (err != null) {
  61. return callback(
  62. OError.tag(err, 'redis error trying to get lock', { key })
  63. )
  64. }
  65. if (gotLock === 'OK') {
  66. metrics.inc('lock.project.try.success')
  67. return callback(err, true, lockValue)
  68. } else {
  69. metrics.inc('lock.project.try.failed')
  70. return callback(err, false)
  71. }
  72. }
  73. )
  74. }
  75. export function tryLock(...args) {
  76. _mocks.tryLock(...args)
  77. }
  78. _mocks.extendLock = (key, lockValue, callback) => {
  79. if (callback == null) {
  80. callback = function () {}
  81. }
  82. return rclient.eval(
  83. EXTEND_SCRIPT,
  84. 1,
  85. key,
  86. lockValue,
  87. LOCK_TTL,
  88. function (err, result) {
  89. if (err != null) {
  90. return callback(
  91. OError.tag(err, 'redis error trying to extend lock', { key })
  92. )
  93. }
  94. if (result != null && result !== 1) {
  95. // successful extension should release exactly one key
  96. metrics.inc('lock.project.extend.failed')
  97. const error = new OError('failed to extend lock', {
  98. key,
  99. lockValue,
  100. result,
  101. })
  102. return callback(error)
  103. }
  104. metrics.inc('lock.project.extend.success')
  105. return callback()
  106. }
  107. )
  108. }
  109. export function extendLock(...args) {
  110. _mocks.extendLock(...args)
  111. }
  112. _mocks.getLock = (key, callback) => {
  113. let attempt
  114. if (callback == null) {
  115. callback = function () {}
  116. }
  117. const startTime = Date.now()
  118. let attempts = 0
  119. return (attempt = function () {
  120. if (Date.now() - startTime > MAX_LOCK_WAIT_TIME) {
  121. metrics.inc('lock.project.get.failed')
  122. return callback(new OError('Timeout', { key }))
  123. }
  124. attempts += 1
  125. return tryLock(key, function (error, gotLock, lockValue) {
  126. if (error != null) {
  127. return callback(OError.tag(error))
  128. }
  129. if (gotLock) {
  130. metrics.gauge('lock.project.get.success.tries', attempts)
  131. return callback(null, lockValue)
  132. } else {
  133. return setTimeout(attempt, LOCK_TEST_INTERVAL)
  134. }
  135. })
  136. })()
  137. }
  138. export function getLock(...args) {
  139. _mocks.getLock(...args)
  140. }
  141. export function checkLock(key, callback) {
  142. if (callback == null) {
  143. callback = function () {}
  144. }
  145. return rclient.exists(key, function (err, exists) {
  146. if (err != null) {
  147. return callback(OError.tag(err))
  148. }
  149. exists = parseInt(exists)
  150. if (exists === 1) {
  151. return callback(err, false)
  152. } else {
  153. return callback(err, true)
  154. }
  155. })
  156. }
  157. _mocks.releaseLock = (key, lockValue, callback) => {
  158. return rclient.eval(UNLOCK_SCRIPT, 1, key, lockValue, function (err, result) {
  159. if (err != null) {
  160. return callback(OError.tag(err))
  161. }
  162. if (result != null && result !== 1) {
  163. // successful unlock should release exactly one key
  164. const error = new OError('tried to release timed out lock', {
  165. key,
  166. lockValue,
  167. redis_result: result,
  168. })
  169. return callback(error)
  170. }
  171. return callback(err, result)
  172. })
  173. }
  174. export function releaseLock(...args) {
  175. _mocks.releaseLock(...args)
  176. }
  177. export function runWithLock(key, runner, callback) {
  178. if (callback == null) {
  179. callback = function () {}
  180. }
  181. return getLock(key, function (error, lockValue) {
  182. if (error != null) {
  183. return callback(OError.tag(error))
  184. }
  185. const lock = new Lock(key, lockValue)
  186. return runner(lock.extend.bind(lock), (error1, ...args) =>
  187. lock.release(function (error2) {
  188. error = error1 || error2
  189. if (error != null) {
  190. return callback(OError.tag(error), ...Array.from(args))
  191. }
  192. return callback(null, ...Array.from(args))
  193. })
  194. )
  195. })
  196. }
  197. export function healthCheck(callback) {
  198. const action = (extendLock, releaseLock) => releaseLock()
  199. return runWithLock(
  200. `HistoryLock:HealthCheck:host=${HOST}:pid=${PID}:random=${RND}`,
  201. action,
  202. callback
  203. )
  204. }
  205. export function close(callback) {
  206. rclient.quit()
  207. return rclient.once('end', callback)
  208. }
  209. class Lock {
  210. constructor(key, value) {
  211. this.key = key
  212. this.value = value
  213. this.slowExecutionError = new OError('slow execution during lock')
  214. this.lockTakenAt = Date.now()
  215. this.timer = new metrics.Timer('lock.project')
  216. }
  217. extend(callback) {
  218. const lockLength = Date.now() - this.lockTakenAt
  219. if (lockLength < MIN_LOCK_EXTENSION_INTERVAL) {
  220. return async.setImmediate(callback)
  221. }
  222. return extendLock(this.key, this.value, error => {
  223. if (error != null) {
  224. return callback(OError.tag(error))
  225. }
  226. this.lockTakenAt = Date.now()
  227. return callback()
  228. })
  229. }
  230. release(callback) {
  231. // The lock can expire in redis but the process carry on. This setTimout call
  232. // is designed to log if this happens.
  233. const lockLength = Date.now() - this.lockTakenAt
  234. if (lockLength > LOCK_TTL * 1000) {
  235. metrics.inc('lock.project.exceeded_lock_timeout')
  236. logger.debug('exceeded lock timeout', {
  237. key: this.key,
  238. slowExecutionError: this.slowExecutionError,
  239. })
  240. }
  241. return releaseLock(this.key, this.value, error => {
  242. this.timer.done()
  243. if (error != null) {
  244. return callback(OError.tag(error))
  245. }
  246. return callback()
  247. })
  248. }
  249. }
  250. /**
  251. * Promisified version of runWithLock.
  252. *
  253. * @param {string} key
  254. * @param {(extendLock: Function) => Promise<any>} runner
  255. */
  256. async function runWithLockPromises(key, runner) {
  257. const runnerCb = (extendLock, callback) => {
  258. const extendLockPromises = promisify(extendLock)
  259. runner(extendLockPromises)
  260. .then(result => {
  261. callback(null, result)
  262. })
  263. .catch(err => {
  264. callback(err)
  265. })
  266. }
  267. return await new Promise((resolve, reject) => {
  268. runWithLock(key, runnerCb, (err, result) => {
  269. if (err) {
  270. reject(err)
  271. } else {
  272. resolve(result)
  273. }
  274. })
  275. })
  276. }
  277. export const promises = {
  278. tryLock: promisify(tryLock),
  279. extendLock: promisify(extendLock),
  280. getLock: promisify(getLock),
  281. checkLock: promisify(checkLock),
  282. releaseLock: promisify(releaseLock),
  283. runWithLock: runWithLockPromises,
  284. }