DocArchiveManager.js 5.7 KB

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