ProjectPersistenceManager.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. let ProjectPersistenceManager
  11. const UrlCache = require('./UrlCache')
  12. const CompileManager = require('./CompileManager')
  13. const async = require('async')
  14. const logger = require('@overleaf/logger')
  15. const oneDay = 24 * 60 * 60 * 1000
  16. const Settings = require('@overleaf/settings')
  17. const diskusage = require('diskusage')
  18. const { callbackify } = require('util')
  19. const Path = require('path')
  20. const fs = require('fs')
  21. // projectId -> timestamp mapping.
  22. const LAST_ACCESS = new Map()
  23. async function refreshExpiryTimeout() {
  24. const paths = [
  25. Settings.path.compilesDir,
  26. Settings.path.outputDir,
  27. Settings.path.clsiCacheDir,
  28. ]
  29. for (const path of paths) {
  30. try {
  31. const stats = await diskusage.check(path)
  32. const lowDisk = stats.available / stats.total < 0.1
  33. const lowerExpiry = ProjectPersistenceManager.EXPIRY_TIMEOUT * 0.9
  34. if (lowDisk && Settings.project_cache_length_ms / 2 < lowerExpiry) {
  35. logger.warn(
  36. {
  37. stats,
  38. newExpiryTimeoutInDays: (lowerExpiry / oneDay).toFixed(2),
  39. },
  40. 'disk running low on space, modifying EXPIRY_TIMEOUT'
  41. )
  42. ProjectPersistenceManager.EXPIRY_TIMEOUT = lowerExpiry
  43. break
  44. }
  45. } catch (err) {
  46. logger.err({ err, path }, 'error getting disk usage')
  47. }
  48. }
  49. }
  50. module.exports = ProjectPersistenceManager = {
  51. EXPIRY_TIMEOUT: Settings.project_cache_length_ms || oneDay * 2.5,
  52. promises: {
  53. refreshExpiryTimeout,
  54. },
  55. refreshExpiryTimeout: callbackify(refreshExpiryTimeout),
  56. init() {
  57. fs.readdir(Settings.path.compilesDir, (err, dirs) => {
  58. if (err) {
  59. logger.warn({ err }, 'cannot get project listing')
  60. dirs = []
  61. }
  62. async.eachLimit(
  63. dirs,
  64. 10,
  65. (projectAndUserId, cb) => {
  66. const compileDir = Path.join(
  67. Settings.path.compilesDir,
  68. projectAndUserId
  69. )
  70. const projectId = projectAndUserId.slice(0, 24)
  71. fs.stat(compileDir, (err, stats) => {
  72. if (err) {
  73. // Schedule for immediate cleanup
  74. LAST_ACCESS.set(projectId, 0)
  75. } else {
  76. // Cleanup eventually.
  77. LAST_ACCESS.set(projectId, stats.mtime.getTime())
  78. }
  79. cb()
  80. })
  81. },
  82. () => {
  83. setInterval(() => {
  84. ProjectPersistenceManager.refreshExpiryTimeout(() => {
  85. ProjectPersistenceManager.clearExpiredProjects(err => {
  86. if (err) {
  87. logger.error({ err }, 'clearing expired projects failed')
  88. }
  89. })
  90. })
  91. }, 10 * 60 * 1000)
  92. }
  93. )
  94. })
  95. },
  96. markProjectAsJustAccessed(projectId, callback) {
  97. LAST_ACCESS.set(projectId, Date.now())
  98. callback()
  99. },
  100. clearExpiredProjects(callback) {
  101. if (callback == null) {
  102. callback = function () {}
  103. }
  104. return ProjectPersistenceManager._findExpiredProjectIds(function (
  105. error,
  106. projectIds
  107. ) {
  108. if (error != null) {
  109. return callback(error)
  110. }
  111. logger.debug({ projectIds }, 'clearing expired projects')
  112. const jobs = Array.from(projectIds || []).map(projectId =>
  113. (
  114. projectId => callback =>
  115. ProjectPersistenceManager.clearProjectFromCache(
  116. projectId,
  117. { reason: 'expired' },
  118. function (err) {
  119. if (err != null) {
  120. logger.error({ err, projectId }, 'error clearing project')
  121. }
  122. return callback()
  123. }
  124. )
  125. )(projectId)
  126. )
  127. return async.series(jobs, function (error) {
  128. if (error != null) {
  129. return callback(error)
  130. }
  131. return CompileManager.clearExpiredProjects(
  132. ProjectPersistenceManager.EXPIRY_TIMEOUT,
  133. error => callback(error)
  134. )
  135. })
  136. })
  137. }, // ignore any errors from deleting directories
  138. clearProject(projectId, userId, callback) {
  139. if (callback == null) {
  140. callback = function () {}
  141. }
  142. logger.debug({ projectId, userId }, 'clearing project for user')
  143. return CompileManager.clearProject(projectId, userId, function (error) {
  144. if (error != null) {
  145. return callback(error)
  146. }
  147. return ProjectPersistenceManager.clearProjectFromCache(
  148. projectId,
  149. { reason: 'cleared' },
  150. function (error) {
  151. if (error != null) {
  152. return callback(error)
  153. }
  154. return callback()
  155. }
  156. )
  157. })
  158. },
  159. clearProjectFromCache(projectId, options, callback) {
  160. if (callback == null) {
  161. callback = function () {}
  162. }
  163. logger.debug({ projectId }, 'clearing project from cache')
  164. return UrlCache.clearProject(projectId, options, function (error) {
  165. if (error != null) {
  166. logger.err({ error, projectId }, 'error clearing project from cache')
  167. return callback(error)
  168. }
  169. return ProjectPersistenceManager._clearProjectFromDatabase(
  170. projectId,
  171. function (error) {
  172. if (error != null) {
  173. logger.err(
  174. { error, projectId },
  175. 'error clearing project from database'
  176. )
  177. }
  178. return callback(error)
  179. }
  180. )
  181. })
  182. },
  183. _clearProjectFromDatabase(projectId, callback) {
  184. LAST_ACCESS.delete(projectId)
  185. callback()
  186. },
  187. _findExpiredProjectIds(callback) {
  188. const expiredFrom = Date.now() - ProjectPersistenceManager.EXPIRY_TIMEOUT
  189. const expiredProjectsIds = []
  190. for (const [projectId, lastAccess] of LAST_ACCESS.entries()) {
  191. if (lastAccess < expiredFrom) {
  192. expiredProjectsIds.push(projectId)
  193. }
  194. }
  195. // ^ may be a fairly busy loop, continue detached.
  196. setTimeout(() => callback(null, expiredProjectsIds), 0)
  197. },
  198. }
  199. logger.debug(
  200. { EXPIRY_TIMEOUT: ProjectPersistenceManager.EXPIRY_TIMEOUT },
  201. 'project assets kept timeout'
  202. )