LockManager.js 2.4 KB

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