index.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. const { Binary, ObjectId } = require('mongodb')
  2. const { projects, deletedProjects, backedUpBlobs } = require('../mongodb')
  3. const OError = require('@overleaf/o-error')
  4. // List projects with pending backups older than the specified interval
  5. function listPendingBackups(timeIntervalMs = 0, limit = null) {
  6. const cutoffTime = new Date(Date.now() - timeIntervalMs)
  7. const options = {
  8. projection: { 'overleaf.backup.pendingChangeAt': 1 },
  9. sort: { 'overleaf.backup.pendingChangeAt': 1 },
  10. }
  11. // Apply limit if provided
  12. if (limit) {
  13. options.limit = limit
  14. }
  15. const cursor = projects.find(
  16. {
  17. 'overleaf.backup.pendingChangeAt': {
  18. $exists: true,
  19. $lt: cutoffTime,
  20. },
  21. },
  22. options
  23. )
  24. return cursor
  25. }
  26. // List projects that have never been backed up and are older than the specified interval
  27. function listUninitializedBackups(timeIntervalMs = 0, limit = null) {
  28. const cutoffTimeInSeconds = (Date.now() - timeIntervalMs) / 1000
  29. const options = {
  30. projection: { _id: 1 },
  31. sort: { _id: 1 },
  32. }
  33. // Apply limit if provided
  34. if (limit) {
  35. options.limit = limit
  36. }
  37. const cursor = projects.find(
  38. {
  39. 'overleaf.backup.lastBackedUpVersion': null,
  40. _id: {
  41. $lt: ObjectId.createFromTime(cutoffTimeInSeconds),
  42. },
  43. },
  44. options
  45. )
  46. return cursor
  47. }
  48. // Retrieve the history ID for a given project without giving direct access to the
  49. // projects collection.
  50. async function getHistoryId(projectId) {
  51. const project = await projects.findOne(
  52. { _id: new ObjectId(projectId) },
  53. {
  54. projection: {
  55. 'overleaf.history.id': 1,
  56. },
  57. }
  58. )
  59. if (!project) {
  60. throw new Error('Project not found')
  61. }
  62. return project.overleaf.history.id
  63. }
  64. async function getBackupStatus(projectId, options = {}) {
  65. const projection = {
  66. 'overleaf.history': 1,
  67. 'overleaf.backup': 1,
  68. }
  69. if (options.includeRootFolder) {
  70. projection.rootFolder = 1
  71. }
  72. const project = await projects.findOne(
  73. { _id: new ObjectId(projectId) },
  74. {
  75. projection,
  76. }
  77. )
  78. if (!project) {
  79. // Check whether the project was deleted
  80. const deletedProject = await deletedProjects.findOne({
  81. 'deleterData.deletedProjectId': new ObjectId(projectId),
  82. })
  83. if (deletedProject) {
  84. throw new Error('Project deleted')
  85. }
  86. throw new Error('Project not found')
  87. }
  88. return {
  89. backupStatus: project.overleaf.backup,
  90. historyId: `${project.overleaf.history.id}`,
  91. currentEndVersion: project.overleaf.history.currentEndVersion,
  92. currentEndTimestamp: project.overleaf.history.currentEndTimestamp,
  93. ...(options.includeRootFolder && { rootFolder: project.rootFolder?.[0] }),
  94. }
  95. }
  96. /**
  97. * Recursively traverses the file tree and collects file hashes into a Set.
  98. *
  99. * @param {object} rootFolder - The root folder object of the file tree.
  100. * @returns {Set<string>} A Set containing all unique file hashes found in the file tree.
  101. */
  102. function getHashesFromFileTree(rootFolder) {
  103. const hashSet = new Set()
  104. function processFolder(folder) {
  105. for (const file of folder.fileRefs || []) {
  106. if (file?.hash) {
  107. hashSet.add(file.hash)
  108. }
  109. }
  110. for (const subfolder of folder.folders || []) {
  111. if (subfolder?._id) {
  112. processFolder(subfolder)
  113. }
  114. }
  115. }
  116. processFolder(rootFolder)
  117. return hashSet
  118. }
  119. async function setBackupVersion(
  120. projectId,
  121. previousBackedUpVersion,
  122. currentBackedUpVersion,
  123. currentBackedUpAt
  124. ) {
  125. // FIXME: include a check to handle race conditions
  126. // to make sure only one process updates the version numbers
  127. const result = await projects.updateOne(
  128. {
  129. _id: new ObjectId(projectId),
  130. 'overleaf.backup.lastBackedUpVersion': previousBackedUpVersion,
  131. },
  132. {
  133. $set: {
  134. 'overleaf.backup.lastBackedUpVersion': currentBackedUpVersion,
  135. 'overleaf.backup.lastBackedUpAt': currentBackedUpAt,
  136. },
  137. }
  138. )
  139. if (result.matchedCount === 0 || result.modifiedCount === 0) {
  140. throw new OError('Failed to update backup version', {
  141. previousBackedUpVersion,
  142. currentBackedUpVersion,
  143. currentBackedUpAt,
  144. result,
  145. })
  146. }
  147. }
  148. async function updateCurrentMetadataIfNotSet(projectId, latestChunkMetadata) {
  149. await projects.updateOne(
  150. {
  151. _id: new ObjectId(projectId),
  152. 'overleaf.history.currentEndVersion': { $exists: false },
  153. 'overleaf.history.currentEndTimestamp': { $exists: false },
  154. },
  155. {
  156. $set: {
  157. 'overleaf.history.currentEndVersion': latestChunkMetadata.endVersion,
  158. 'overleaf.history.currentEndTimestamp':
  159. latestChunkMetadata.endTimestamp,
  160. },
  161. }
  162. )
  163. }
  164. /**
  165. * Updates the pending change timestamp for a project's backup status
  166. * @param {string} projectId - The ID of the project to update
  167. * @param {Date} backupStartTime - The timestamp to set for pending changes
  168. * @returns {Promise<void>}
  169. *
  170. * If the project's last backed up version matches the current end version,
  171. * the pending change timestamp is removed. Otherwise, it's set to the provided
  172. * backup start time.
  173. */
  174. async function updatePendingChangeTimestamp(projectId, backupStartTime) {
  175. await projects.updateOne({ _id: new ObjectId(projectId) }, [
  176. {
  177. $set: {
  178. 'overleaf.backup.pendingChangeAt': {
  179. $cond: {
  180. if: {
  181. $eq: [
  182. '$overleaf.backup.lastBackedUpVersion',
  183. '$overleaf.history.currentEndVersion',
  184. ],
  185. },
  186. then: '$$REMOVE',
  187. else: backupStartTime,
  188. },
  189. },
  190. },
  191. },
  192. ])
  193. }
  194. async function getBackedUpBlobHashes(projectId) {
  195. const result = await backedUpBlobs.findOne(
  196. { _id: new ObjectId(projectId) },
  197. { projection: { blobs: 1 } }
  198. )
  199. if (!result) {
  200. return new Set()
  201. }
  202. const hashes = result.blobs.map(b => b.buffer.toString('hex'))
  203. return new Set(hashes)
  204. }
  205. async function unsetBackedUpBlobHashes(projectId, hashes) {
  206. const binaryHashes = hashes.map(h => new Binary(Buffer.from(h, 'hex')))
  207. const result = await backedUpBlobs.findOneAndUpdate(
  208. { _id: new ObjectId(projectId) },
  209. {
  210. $pullAll: {
  211. blobs: binaryHashes,
  212. },
  213. },
  214. { returnDocument: 'after' }
  215. )
  216. if (result && result.blobs.length === 0) {
  217. await backedUpBlobs.deleteOne({
  218. _id: new ObjectId(projectId),
  219. blobs: { $size: 0 },
  220. })
  221. }
  222. return result
  223. }
  224. module.exports = {
  225. getHistoryId,
  226. getBackupStatus,
  227. setBackupVersion,
  228. updateCurrentMetadataIfNotSet,
  229. updatePendingChangeTimestamp,
  230. listPendingBackups,
  231. listUninitializedBackups,
  232. getBackedUpBlobHashes,
  233. unsetBackedUpBlobHashes,
  234. getHashesFromFileTree,
  235. }