DocManager.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import MongoManager from './MongoManager.js'
  2. import Errors from './Errors.js'
  3. import logger from '@overleaf/logger'
  4. import _ from 'lodash'
  5. import DocArchive from './DocArchiveManager.js'
  6. import RangeManager from './RangeManager.js'
  7. import Settings from '@overleaf/settings'
  8. import { setTimeout } from 'node:timers/promises'
  9. import Metrics from '@overleaf/metrics'
  10. /**
  11. * @import { Document } from 'mongodb'
  12. * @import { WithId } from 'mongodb'
  13. */
  14. const DocManager = {
  15. /**
  16. * @param {string} projectId
  17. * @param {string} docId
  18. * @param {{inS3: boolean}} filter
  19. * @returns {Promise<WithId<Document>>}
  20. * @private
  21. */
  22. async _getDoc(projectId, docId, filter) {
  23. if (filter == null) {
  24. filter = {}
  25. }
  26. if (filter.inS3 !== true) {
  27. throw new Error('must include inS3 when getting doc')
  28. }
  29. const doc = await MongoManager.findDoc(projectId, docId, filter)
  30. if (doc == null) {
  31. throw new Errors.NotFoundError(
  32. `No such doc: ${docId} in project ${projectId}`
  33. )
  34. }
  35. if (doc.inS3) {
  36. await DocArchive.unarchiveDoc(projectId, docId)
  37. return await DocManager._getDoc(projectId, docId, filter)
  38. }
  39. if (filter.ranges) {
  40. RangeManager.fixCommentIds(doc)
  41. }
  42. return doc
  43. },
  44. async isDocDeleted(projectId, docId) {
  45. const doc = await MongoManager.findDoc(projectId, docId, {
  46. deleted: true,
  47. })
  48. if (!doc) {
  49. throw new Errors.NotFoundError(
  50. `No such project/doc: ${projectId}/${docId}`
  51. )
  52. }
  53. // `doc.deleted` is `undefined` for non deleted docs
  54. return Boolean(doc.deleted)
  55. },
  56. async getFullDoc(projectId, docId) {
  57. const doc = await DocManager._getDoc(projectId, docId, {
  58. lines: true,
  59. rev: true,
  60. deleted: true,
  61. version: true,
  62. ranges: true,
  63. inS3: true,
  64. })
  65. return doc
  66. },
  67. // returns the doc without any version information
  68. async _peekRawDoc(projectId, docId) {
  69. const doc = await MongoManager.findDoc(projectId, docId, {
  70. lines: true,
  71. rev: true,
  72. deleted: true,
  73. version: true,
  74. ranges: true,
  75. inS3: true,
  76. })
  77. if (doc == null) {
  78. throw new Errors.NotFoundError(
  79. `No such doc: ${docId} in project ${projectId}`
  80. )
  81. }
  82. if (doc.inS3) {
  83. // skip the unarchiving to mongo when getting a doc
  84. const archivedDoc = await DocArchive.getDoc(projectId, docId)
  85. Object.assign(doc, archivedDoc)
  86. }
  87. return doc
  88. },
  89. // get the doc from mongo if possible, or from the persistent store otherwise,
  90. // without unarchiving it (avoids unnecessary writes to mongo)
  91. async peekDoc(projectId, docId) {
  92. const doc = await DocManager._peekRawDoc(projectId, docId)
  93. await MongoManager.checkRevUnchanged(doc)
  94. return doc
  95. },
  96. async getDocLines(projectId, docId) {
  97. const doc = await DocManager._getDoc(projectId, docId, {
  98. lines: true,
  99. inS3: true,
  100. })
  101. if (!doc) throw new Errors.NotFoundError()
  102. if (!Array.isArray(doc.lines)) throw new Errors.DocWithoutLinesError()
  103. return doc.lines.join('\n')
  104. },
  105. async getAllDeletedDocs(projectId, filter) {
  106. return await MongoManager.getProjectsDeletedDocs(projectId, filter)
  107. },
  108. async getAllNonDeletedDocs(projectId, filter) {
  109. await DocArchive.unArchiveAllDocs(projectId)
  110. const docs = await MongoManager.getProjectsDocs(
  111. projectId,
  112. { include_deleted: false },
  113. filter
  114. )
  115. if (docs == null) {
  116. throw new Errors.NotFoundError(`No docs for project ${projectId}`)
  117. }
  118. if (filter.ranges) {
  119. for (const doc of docs) {
  120. RangeManager.fixCommentIds(doc)
  121. }
  122. }
  123. return docs
  124. },
  125. async getCommentThreadIds(projectId) {
  126. const docs = await DocManager.getAllNonDeletedDocs(projectId, {
  127. _id: true,
  128. ranges: true,
  129. })
  130. const byDoc = new Map()
  131. for (const doc of docs) {
  132. const ids = new Set()
  133. for (const comment of doc.ranges?.comments || []) {
  134. ids.add(comment.op.t)
  135. }
  136. if (ids.size > 0) byDoc.set(doc._id.toString(), Array.from(ids))
  137. }
  138. return Object.fromEntries(byDoc.entries())
  139. },
  140. async getTrackedChangesUserIds(projectId) {
  141. const docs = await DocManager.getAllNonDeletedDocs(projectId, {
  142. ranges: true,
  143. })
  144. const userIds = new Set()
  145. for (const doc of docs) {
  146. for (const change of doc.ranges?.changes || []) {
  147. if (change.metadata.user_id === 'anonymous-user') continue
  148. userIds.add(change.metadata.user_id)
  149. }
  150. }
  151. return Array.from(userIds)
  152. },
  153. async projectHasRanges(projectId) {
  154. const docs = await MongoManager.getProjectsDocs(projectId, {}, { _id: 1 })
  155. const docIds = docs.map(doc => doc._id)
  156. for (const docId of docIds) {
  157. const doc = await DocManager.peekDoc(projectId, docId)
  158. if (
  159. (doc.ranges?.comments != null && doc.ranges.comments.length > 0) ||
  160. (doc.ranges?.changes != null && doc.ranges.changes.length > 0)
  161. ) {
  162. return true
  163. }
  164. }
  165. return false
  166. },
  167. async updateDoc(projectId, docId, lines, version, ranges) {
  168. const MAX_ATTEMPTS = 2
  169. for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
  170. try {
  171. const { modified, rev } = await DocManager._tryUpdateDoc(
  172. projectId,
  173. docId,
  174. lines,
  175. version,
  176. ranges
  177. )
  178. return { modified, rev }
  179. } catch (err) {
  180. if (err instanceof Errors.DocRevValueError && attempt < MAX_ATTEMPTS) {
  181. // Another updateDoc call was racing with ours.
  182. // Retry once in a bit.
  183. logger.warn(
  184. { projectId, docId, err },
  185. 'detected concurrent updateDoc call'
  186. )
  187. await setTimeout(100 + Math.random() * 100)
  188. continue
  189. } else {
  190. throw err
  191. }
  192. }
  193. }
  194. },
  195. async _tryUpdateDoc(projectId, docId, lines, version, ranges) {
  196. if (lines == null || version == null || ranges == null) {
  197. throw new Error('no lines, version or ranges provided')
  198. }
  199. let doc
  200. try {
  201. doc = await DocManager._getDoc(projectId, docId, {
  202. version: true,
  203. rev: true,
  204. lines: true,
  205. ranges: true,
  206. inS3: true,
  207. })
  208. } catch (err) {
  209. if (err instanceof Errors.NotFoundError) {
  210. doc = null
  211. } else {
  212. throw err
  213. }
  214. }
  215. ranges = RangeManager.jsonRangesToMongo(ranges)
  216. let updateLines, updateRanges, updateVersion
  217. if (doc == null) {
  218. // If the document doesn't exist, we'll make sure to create/update all parts of it.
  219. updateLines = true
  220. updateVersion = true
  221. updateRanges = true
  222. } else {
  223. if (doc.version > version) {
  224. // Reject update when the version was decremented.
  225. // Potential reasons: racing flush, broken history.
  226. throw new Errors.DocVersionDecrementedError('rejecting stale update', {
  227. updateVersion: version,
  228. flushedVersion: doc.version,
  229. })
  230. }
  231. updateLines = !_.isEqual(doc.lines, lines)
  232. if (doc.lines.length === lines.length) {
  233. Metrics.inc('mongo_docs_update_delta', 1, {
  234. status: 'same-line-length',
  235. })
  236. } else if (doc.lines.length > lines.length) {
  237. Metrics.inc('mongo_docs_update_delta', 1, {
  238. status: 'smaller-line-length',
  239. })
  240. } else if (doc.lines.length < lines.length) {
  241. Metrics.inc('mongo_docs_update_delta', 1, {
  242. status: 'larger-line-length',
  243. })
  244. }
  245. updateVersion = doc.version !== version
  246. updateRanges = RangeManager.shouldUpdateRanges(doc.ranges, ranges)
  247. }
  248. let modified = false
  249. let rev = doc?.rev || 0
  250. if (updateLines || updateRanges || updateVersion) {
  251. const update = {}
  252. if (updateLines) {
  253. update.lines = lines
  254. }
  255. if (updateRanges) {
  256. update.ranges = ranges
  257. }
  258. if (updateVersion) {
  259. update.version = version
  260. }
  261. logger.debug(
  262. { projectId, docId, oldVersion: doc?.version, newVersion: version },
  263. 'updating doc'
  264. )
  265. if (updateLines || updateRanges) {
  266. rev += 1 // rev will be incremented in mongo by MongoManager.upsertIntoDocCollection
  267. }
  268. modified = true
  269. await MongoManager.upsertIntoDocCollection(
  270. projectId,
  271. docId,
  272. doc?.rev,
  273. update
  274. )
  275. } else {
  276. logger.debug({ projectId, docId }, 'doc has not changed - not updating')
  277. }
  278. return { modified, rev }
  279. },
  280. async patchDoc(projectId, docId, meta) {
  281. const projection = { _id: 1, deleted: true }
  282. const doc = await MongoManager.findDoc(projectId, docId, projection)
  283. if (!doc) {
  284. throw new Errors.NotFoundError(
  285. `No such project/doc to delete: ${projectId}/${docId}`
  286. )
  287. }
  288. if (meta.deleted && Settings.docstore.archiveOnSoftDelete) {
  289. // The user will not read this doc anytime soon. Flush it out of mongo.
  290. DocArchive.archiveDoc(projectId, docId).catch(err => {
  291. logger.warn(
  292. { projectId, docId, err },
  293. 'archiving a single doc in the background failed'
  294. )
  295. })
  296. }
  297. await MongoManager.patchDoc(projectId, docId, meta)
  298. },
  299. }
  300. export default DocManager