DocArchiveManager.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. const MongoManager = require('./MongoManager')
  2. const Errors = require('./Errors')
  3. const logger = require('@overleaf/logger')
  4. const Settings = require('@overleaf/settings')
  5. const crypto = require('node:crypto')
  6. const { ReadableString } = require('@overleaf/stream-utils')
  7. const RangeManager = require('./RangeManager')
  8. const PersistorManager = require('./PersistorManager')
  9. const pMap = require('p-map')
  10. const { streamToBuffer } = require('./StreamToBuffer')
  11. const { BSON } = require('mongodb-legacy')
  12. const PARALLEL_JOBS = Settings.parallelArchiveJobs
  13. const UN_ARCHIVE_BATCH_SIZE = Settings.unArchiveBatchSize
  14. async function archiveAllDocs(projectId) {
  15. if (!_isArchivingEnabled()) {
  16. return
  17. }
  18. const docIds = await MongoManager.getNonArchivedProjectDocIds(projectId)
  19. await pMap(docIds, docId => archiveDoc(projectId, docId), {
  20. concurrency: PARALLEL_JOBS,
  21. })
  22. }
  23. async function archiveDoc(projectId, docId) {
  24. if (!_isArchivingEnabled()) {
  25. return
  26. }
  27. const doc = await MongoManager.getDocForArchiving(projectId, docId)
  28. if (!doc) {
  29. // The doc wasn't found, it was already archived, or the lock couldn't be
  30. // acquired. Since we don't know which it is, silently return.
  31. return
  32. }
  33. logger.debug({ projectId, docId: doc._id }, 'sending doc to persistor')
  34. const key = `${projectId}/${doc._id}`
  35. if (doc.lines == null) {
  36. throw new Error('doc has no lines')
  37. }
  38. RangeManager.fixCommentIds(doc)
  39. // warn about any oversized docs already in mongo
  40. const linesSize = BSON.calculateObjectSize(doc.lines || {})
  41. const rangesSize = BSON.calculateObjectSize(doc.ranges || {})
  42. if (
  43. linesSize > Settings.max_doc_length ||
  44. rangesSize > Settings.max_doc_length
  45. ) {
  46. logger.warn(
  47. { projectId, docId: doc._id, linesSize, rangesSize },
  48. 'large doc found when archiving project'
  49. )
  50. }
  51. const json = JSON.stringify({
  52. lines: doc.lines,
  53. ranges: doc.ranges,
  54. rev: doc.rev,
  55. schema_v: 1,
  56. })
  57. // this should never happen, but protects against memory-corruption errors that
  58. // have happened in the past
  59. if (json.indexOf('\u0000') > -1) {
  60. const error = new Error('null bytes detected')
  61. logger.err({ err: error, doc }, error.message)
  62. throw error
  63. }
  64. const md5 = crypto.createHash('md5').update(json).digest('hex')
  65. const stream = new ReadableString(json)
  66. await PersistorManager.sendStream(Settings.docstore.bucket, key, stream, {
  67. sourceMd5: md5,
  68. })
  69. await MongoManager.markDocAsArchived(projectId, docId, doc.rev)
  70. }
  71. async function unArchiveAllDocs(projectId) {
  72. if (!_isArchivingEnabled()) {
  73. return
  74. }
  75. while (true) {
  76. let docs
  77. if (Settings.docstore.keepSoftDeletedDocsArchived) {
  78. docs = await MongoManager.getNonDeletedArchivedProjectDocs(
  79. projectId,
  80. UN_ARCHIVE_BATCH_SIZE
  81. )
  82. } else {
  83. docs = await MongoManager.getArchivedProjectDocs(
  84. projectId,
  85. UN_ARCHIVE_BATCH_SIZE
  86. )
  87. }
  88. if (!docs || docs.length === 0) {
  89. break
  90. }
  91. await pMap(docs, doc => unarchiveDoc(projectId, doc._id), {
  92. concurrency: PARALLEL_JOBS,
  93. })
  94. }
  95. }
  96. // get the doc from the PersistorManager without storing it in mongo
  97. async function getDoc(projectId, docId) {
  98. const key = `${projectId}/${docId}`
  99. const sourceMd5 = await PersistorManager.getObjectMd5Hash(
  100. Settings.docstore.bucket,
  101. key
  102. )
  103. const stream = await PersistorManager.getObjectStream(
  104. Settings.docstore.bucket,
  105. key
  106. )
  107. stream.resume()
  108. const buffer = await streamToBuffer(projectId, docId, stream)
  109. const md5 = crypto.createHash('md5').update(buffer).digest('hex')
  110. if (sourceMd5 !== md5) {
  111. throw new Errors.Md5MismatchError('md5 mismatch when downloading doc', {
  112. key,
  113. sourceMd5,
  114. md5,
  115. })
  116. }
  117. return _deserializeArchivedDoc(buffer)
  118. }
  119. // get the doc and unarchive it to mongo
  120. async function unarchiveDoc(projectId, docId) {
  121. logger.debug({ projectId, docId }, 'getting doc from persistor')
  122. const mongoDoc = await MongoManager.findDoc(projectId, docId, {
  123. inS3: 1,
  124. rev: 1,
  125. })
  126. if (!mongoDoc.inS3) {
  127. // The doc is already unarchived
  128. return
  129. }
  130. if (!_isArchivingEnabled()) {
  131. throw new Error(
  132. 'found archived doc, but archiving backend is not configured'
  133. )
  134. }
  135. const archivedDoc = await getDoc(projectId, docId)
  136. if (archivedDoc.rev == null) {
  137. // Older archived docs didn't have a rev. Assume that the rev of the
  138. // archived doc is the rev that was stored in Mongo when we retrieved it
  139. // earlier.
  140. archivedDoc.rev = mongoDoc.rev
  141. }
  142. await MongoManager.restoreArchivedDoc(projectId, docId, archivedDoc)
  143. }
  144. async function destroyProject(projectId) {
  145. const tasks = [MongoManager.destroyProject(projectId)]
  146. if (_isArchivingEnabled()) {
  147. tasks.push(
  148. PersistorManager.deleteDirectory(Settings.docstore.bucket, projectId)
  149. )
  150. }
  151. await Promise.all(tasks)
  152. }
  153. function _deserializeArchivedDoc(buffer) {
  154. const doc = JSON.parse(buffer)
  155. const result = {}
  156. if (doc.schema_v === 1 && doc.lines != null) {
  157. result.lines = doc.lines
  158. if (doc.ranges != null) {
  159. result.ranges = RangeManager.jsonRangesToMongo(doc.ranges)
  160. }
  161. } else if (Array.isArray(doc)) {
  162. result.lines = doc
  163. } else {
  164. throw new Error("I don't understand the doc format in s3")
  165. }
  166. if (doc.rev != null) {
  167. result.rev = doc.rev
  168. }
  169. return result
  170. }
  171. function _isArchivingEnabled() {
  172. const backend = Settings.docstore.backend
  173. if (!backend) {
  174. return false
  175. }
  176. // The default backend is S3. If another backend is configured or the S3
  177. // backend itself is correctly configured, then archiving is enabled.
  178. if (backend === 's3' && Settings.docstore.s3 == null) {
  179. return false
  180. }
  181. return true
  182. }
  183. module.exports = {
  184. archiveAllDocs,
  185. archiveDoc,
  186. unArchiveAllDocs,
  187. unarchiveDoc,
  188. destroyProject,
  189. getDoc,
  190. }