LockManager.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* eslint-disable
  2. no-unused-vars,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS101: Remove unnecessary use of Array.from
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS207: Consider shorter variations of null checks
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. let LockManager
  14. const Settings = require('@overleaf/settings')
  15. const logger = require('@overleaf/logger')
  16. const Lockfile = require('lockfile') // from https://github.com/npm/lockfile
  17. const Errors = require('./Errors')
  18. const fs = require('fs')
  19. const Path = require('path')
  20. module.exports = LockManager = {
  21. LOCK_TEST_INTERVAL: 1000, // 50ms between each test of the lock
  22. MAX_LOCK_WAIT_TIME: 15000, // 10s maximum time to spend trying to get the lock
  23. LOCK_STALE: 5 * 60 * 1000, // 5 mins time until lock auto expires
  24. runWithLock(path, runner, callback) {
  25. if (callback == null) {
  26. callback = function () {}
  27. }
  28. const lockOpts = {
  29. wait: this.MAX_LOCK_WAIT_TIME,
  30. pollPeriod: this.LOCK_TEST_INTERVAL,
  31. stale: this.LOCK_STALE,
  32. }
  33. return Lockfile.lock(path, lockOpts, function (error) {
  34. if ((error != null ? error.code : undefined) === 'EEXIST') {
  35. return callback(new Errors.AlreadyCompilingError('compile in progress'))
  36. } else if (error != null) {
  37. return fs.lstat(path, (statLockErr, statLock) =>
  38. fs.lstat(Path.dirname(path), (statDirErr, statDir) =>
  39. fs.readdir(Path.dirname(path), function (readdirErr, readdirDir) {
  40. logger.err(
  41. {
  42. error,
  43. path,
  44. statLock,
  45. statLockErr,
  46. statDir,
  47. statDirErr,
  48. readdirErr,
  49. readdirDir,
  50. },
  51. 'unable to get lock'
  52. )
  53. return callback(error)
  54. })
  55. )
  56. )
  57. } else {
  58. return runner((error1, ...args) =>
  59. Lockfile.unlock(path, function (error2) {
  60. error = error1 || error2
  61. if (error != null) {
  62. return callback(error)
  63. }
  64. return callback(null, ...Array.from(args))
  65. })
  66. )
  67. }
  68. })
  69. },
  70. }