DocumentManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. const { callbackifyAll } = require('@overleaf/promise-utils')
  2. const RedisManager = require('./RedisManager')
  3. const ProjectHistoryRedisManager = require('./ProjectHistoryRedisManager')
  4. const PersistenceManager = require('./PersistenceManager')
  5. const DiffCodec = require('./DiffCodec')
  6. const logger = require('@overleaf/logger')
  7. const Metrics = require('./Metrics')
  8. const HistoryManager = require('./HistoryManager')
  9. const Errors = require('./Errors')
  10. const RangesManager = require('./RangesManager')
  11. const { extractOriginOrSource } = require('./Utils')
  12. const { getTotalSizeOfLines } = require('./Limits')
  13. const Settings = require('@overleaf/settings')
  14. const MAX_UNFLUSHED_AGE = 300 * 1000 // 5 mins, document should be flushed to mongo this time after a change
  15. const DocumentManager = {
  16. async getDoc(projectId, docId) {
  17. const {
  18. lines,
  19. version,
  20. ranges,
  21. resolvedCommentIds,
  22. pathname,
  23. projectHistoryId,
  24. unflushedTime,
  25. historyRangesSupport,
  26. } = await RedisManager.promises.getDoc(projectId, docId)
  27. if (lines == null || version == null) {
  28. logger.debug(
  29. { projectId, docId },
  30. 'doc not in redis so getting from persistence API'
  31. )
  32. const {
  33. lines,
  34. version,
  35. ranges,
  36. resolvedCommentIds,
  37. pathname,
  38. projectHistoryId,
  39. historyRangesSupport,
  40. } = await PersistenceManager.promises.getDoc(projectId, docId)
  41. logger.debug(
  42. {
  43. projectId,
  44. docId,
  45. lines,
  46. ranges,
  47. resolvedCommentIds,
  48. version,
  49. pathname,
  50. projectHistoryId,
  51. historyRangesSupport,
  52. },
  53. 'got doc from persistence API'
  54. )
  55. await RedisManager.promises.putDocInMemory(
  56. projectId,
  57. docId,
  58. lines,
  59. version,
  60. ranges,
  61. resolvedCommentIds,
  62. pathname,
  63. projectHistoryId,
  64. historyRangesSupport
  65. )
  66. return {
  67. lines,
  68. version,
  69. ranges: ranges || {},
  70. resolvedCommentIds,
  71. pathname,
  72. projectHistoryId,
  73. unflushedTime: null,
  74. alreadyLoaded: false,
  75. historyRangesSupport,
  76. }
  77. } else {
  78. return {
  79. lines,
  80. version,
  81. ranges,
  82. pathname,
  83. projectHistoryId,
  84. resolvedCommentIds,
  85. unflushedTime,
  86. alreadyLoaded: true,
  87. historyRangesSupport,
  88. }
  89. }
  90. },
  91. async getDocAndRecentOps(projectId, docId, fromVersion) {
  92. const { lines, version, ranges, pathname, projectHistoryId } =
  93. await DocumentManager.getDoc(projectId, docId)
  94. if (fromVersion === -1) {
  95. return { lines, version, ops: [], ranges, pathname, projectHistoryId }
  96. } else {
  97. const ops = await RedisManager.promises.getPreviousDocOps(
  98. docId,
  99. fromVersion,
  100. version
  101. )
  102. return {
  103. lines,
  104. version,
  105. ops,
  106. ranges,
  107. pathname,
  108. projectHistoryId,
  109. }
  110. }
  111. },
  112. async appendToDoc(projectId, docId, linesToAppend, originOrSource, userId) {
  113. const { lines: currentLines } = await DocumentManager.getDoc(
  114. projectId,
  115. docId
  116. )
  117. const currentLineSize = getTotalSizeOfLines(currentLines)
  118. const addedSize = getTotalSizeOfLines(linesToAppend)
  119. const newlineSize = '\n'.length
  120. if (currentLineSize + newlineSize + addedSize > Settings.max_doc_length) {
  121. throw new Errors.FileTooLargeError(
  122. 'doc would become too large if appending this text'
  123. )
  124. }
  125. return await DocumentManager.setDoc(
  126. projectId,
  127. docId,
  128. currentLines.concat(linesToAppend),
  129. originOrSource,
  130. userId,
  131. false,
  132. false
  133. )
  134. },
  135. async setDoc(
  136. projectId,
  137. docId,
  138. newLines,
  139. originOrSource,
  140. userId,
  141. undoing,
  142. external
  143. ) {
  144. if (newLines == null) {
  145. throw new Error('No lines were provided to setDoc')
  146. }
  147. const UpdateManager = require('./UpdateManager')
  148. const {
  149. lines: oldLines,
  150. version,
  151. alreadyLoaded,
  152. } = await DocumentManager.getDoc(projectId, docId)
  153. if (oldLines != null && oldLines.length > 0 && oldLines[0].text != null) {
  154. logger.debug(
  155. { docId, projectId, oldLines, newLines },
  156. 'document is JSON so not updating'
  157. )
  158. return
  159. }
  160. logger.debug(
  161. { docId, projectId, oldLines, newLines },
  162. 'setting a document via http'
  163. )
  164. const op = DiffCodec.diffAsShareJsOp(oldLines, newLines)
  165. if (undoing) {
  166. for (const o of op || []) {
  167. o.u = true
  168. } // Turn on undo flag for each op for track changes
  169. }
  170. const { origin, source } = extractOriginOrSource(originOrSource)
  171. const update = {
  172. doc: docId,
  173. op,
  174. v: version,
  175. meta: {
  176. user_id: userId,
  177. },
  178. }
  179. if (external) {
  180. update.meta.type = 'external'
  181. }
  182. if (origin) {
  183. update.meta.origin = origin
  184. } else if (source) {
  185. update.meta.source = source
  186. }
  187. // Keep track of external updates, whether they are for live documents
  188. // (flush) or unloaded documents (evict), and whether the update is a no-op.
  189. Metrics.inc('external-update', 1, {
  190. status: op.length > 0 ? 'diff' : 'noop',
  191. method: alreadyLoaded ? 'flush' : 'evict',
  192. path: source,
  193. })
  194. // Do not notify the frontend about a noop update.
  195. // We still want to execute the code below
  196. // to evict the doc if we loaded it into redis for
  197. // this update, otherwise the doc would never be
  198. // removed from redis.
  199. if (op.length > 0) {
  200. await UpdateManager.promises.applyUpdate(projectId, docId, update)
  201. }
  202. // If the document was loaded already, then someone has it open
  203. // in a project, and the usual flushing mechanism will happen.
  204. // Otherwise we should remove it immediately since nothing else
  205. // is using it.
  206. if (alreadyLoaded) {
  207. return await DocumentManager.flushDocIfLoaded(projectId, docId)
  208. } else {
  209. try {
  210. return await DocumentManager.flushAndDeleteDoc(projectId, docId, {})
  211. } finally {
  212. // There is no harm in flushing project history if the previous
  213. // call failed and sometimes it is required
  214. HistoryManager.flushProjectChangesAsync(projectId)
  215. }
  216. }
  217. },
  218. async flushDocIfLoaded(projectId, docId) {
  219. const {
  220. lines,
  221. version,
  222. ranges,
  223. unflushedTime,
  224. lastUpdatedAt,
  225. lastUpdatedBy,
  226. } = await RedisManager.promises.getDoc(projectId, docId)
  227. if (lines == null || version == null) {
  228. Metrics.inc('flush-doc-if-loaded', 1, { status: 'not-loaded' })
  229. logger.debug({ projectId, docId }, 'doc is not loaded so not flushing')
  230. // TODO: return a flag to bail out, as we go on to remove doc from memory?
  231. return
  232. } else if (unflushedTime == null) {
  233. Metrics.inc('flush-doc-if-loaded', 1, { status: 'unmodified' })
  234. logger.debug({ projectId, docId }, 'doc is not modified so not flushing')
  235. return
  236. }
  237. logger.debug({ projectId, docId, version }, 'flushing doc')
  238. Metrics.inc('flush-doc-if-loaded', 1, { status: 'modified' })
  239. const result = await PersistenceManager.promises.setDoc(
  240. projectId,
  241. docId,
  242. lines,
  243. version,
  244. ranges,
  245. lastUpdatedAt,
  246. lastUpdatedBy || null
  247. )
  248. await RedisManager.promises.clearUnflushedTime(docId)
  249. return result
  250. },
  251. async flushAndDeleteDoc(projectId, docId, options) {
  252. let result
  253. try {
  254. result = await DocumentManager.flushDocIfLoaded(projectId, docId)
  255. } catch (error) {
  256. if (options.ignoreFlushErrors) {
  257. logger.warn(
  258. { projectId, docId, err: error },
  259. 'ignoring flush error while deleting document'
  260. )
  261. } else {
  262. throw error
  263. }
  264. }
  265. await RedisManager.promises.removeDocFromMemory(projectId, docId)
  266. return result
  267. },
  268. async acceptChanges(projectId, docId, changeIds) {
  269. if (changeIds == null) {
  270. changeIds = []
  271. }
  272. const {
  273. lines,
  274. version,
  275. ranges,
  276. pathname,
  277. projectHistoryId,
  278. historyRangesSupport,
  279. } = await DocumentManager.getDoc(projectId, docId)
  280. if (lines == null || version == null) {
  281. throw new Errors.NotFoundError(`document not found: ${docId}`)
  282. }
  283. const newRanges = RangesManager.acceptChanges(
  284. projectId,
  285. docId,
  286. changeIds,
  287. ranges,
  288. lines
  289. )
  290. await RedisManager.promises.updateDocument(
  291. projectId,
  292. docId,
  293. lines,
  294. version,
  295. [],
  296. newRanges,
  297. {}
  298. )
  299. if (historyRangesSupport) {
  300. const historyUpdates = RangesManager.getHistoryUpdatesForAcceptedChanges({
  301. docId,
  302. acceptedChangeIds: changeIds,
  303. changes: ranges.changes || [],
  304. lines,
  305. pathname,
  306. projectHistoryId,
  307. })
  308. if (historyUpdates.length === 0) {
  309. return
  310. }
  311. await ProjectHistoryRedisManager.promises.queueOps(
  312. projectId,
  313. ...historyUpdates.map(op => JSON.stringify(op))
  314. )
  315. }
  316. },
  317. async updateCommentState(projectId, docId, commentId, userId, resolved) {
  318. const { lines, version, pathname, historyRangesSupport } =
  319. await DocumentManager.getDoc(projectId, docId)
  320. if (lines == null || version == null) {
  321. throw new Errors.NotFoundError(`document not found: ${docId}`)
  322. }
  323. if (historyRangesSupport) {
  324. await RedisManager.promises.updateCommentState(docId, commentId, resolved)
  325. await ProjectHistoryRedisManager.promises.queueOps(
  326. projectId,
  327. JSON.stringify({
  328. pathname,
  329. commentId,
  330. resolved,
  331. meta: {
  332. ts: new Date(),
  333. user_id: userId,
  334. },
  335. })
  336. )
  337. }
  338. },
  339. async deleteComment(projectId, docId, commentId, userId) {
  340. const { lines, version, ranges, pathname, historyRangesSupport } =
  341. await DocumentManager.getDoc(projectId, docId)
  342. if (lines == null || version == null) {
  343. throw new Errors.NotFoundError(`document not found: ${docId}`)
  344. }
  345. const newRanges = RangesManager.deleteComment(commentId, ranges)
  346. await RedisManager.promises.updateDocument(
  347. projectId,
  348. docId,
  349. lines,
  350. version,
  351. [],
  352. newRanges,
  353. {}
  354. )
  355. if (historyRangesSupport) {
  356. await RedisManager.promises.updateCommentState(docId, commentId, false)
  357. await ProjectHistoryRedisManager.promises.queueOps(
  358. projectId,
  359. JSON.stringify({
  360. pathname,
  361. deleteComment: commentId,
  362. meta: {
  363. ts: new Date(),
  364. user_id: userId,
  365. },
  366. })
  367. )
  368. }
  369. },
  370. async renameDoc(projectId, docId, userId, update, projectHistoryId) {
  371. await RedisManager.promises.renameDoc(
  372. projectId,
  373. docId,
  374. userId,
  375. update,
  376. projectHistoryId
  377. )
  378. },
  379. async getDocAndFlushIfOld(projectId, docId) {
  380. const { lines, version, unflushedTime, alreadyLoaded } =
  381. await DocumentManager.getDoc(projectId, docId)
  382. // if doc was already loaded see if it needs to be flushed
  383. if (
  384. alreadyLoaded &&
  385. unflushedTime != null &&
  386. Date.now() - unflushedTime > MAX_UNFLUSHED_AGE
  387. ) {
  388. await DocumentManager.flushDocIfLoaded(projectId, docId)
  389. }
  390. return { lines, version }
  391. },
  392. async resyncDocContents(projectId, docId, path, opts = {}) {
  393. logger.debug({ projectId, docId, path }, 'start resyncing doc contents')
  394. let {
  395. lines,
  396. ranges,
  397. resolvedCommentIds,
  398. version,
  399. projectHistoryId,
  400. historyRangesSupport,
  401. } = await RedisManager.promises.getDoc(projectId, docId)
  402. // To avoid issues where the same docId appears with different paths,
  403. // we use the path from the resyncProjectStructure update. If we used
  404. // the path from the getDoc call to web then the two occurences of the
  405. // docId would map to the same path, and this would be rejected by
  406. // project-history as an unexpected resyncDocContent update.
  407. if (lines == null || version == null) {
  408. logger.debug(
  409. { projectId, docId },
  410. 'resyncing doc contents - not found in redis - retrieving from web'
  411. )
  412. ;({
  413. lines,
  414. ranges,
  415. resolvedCommentIds,
  416. version,
  417. projectHistoryId,
  418. historyRangesSupport,
  419. } = await PersistenceManager.promises.getDoc(projectId, docId, {
  420. peek: true,
  421. }))
  422. } else {
  423. logger.debug(
  424. { projectId, docId },
  425. 'resyncing doc contents - doc in redis - will queue in redis'
  426. )
  427. }
  428. if (opts.historyRangesMigration) {
  429. historyRangesSupport = opts.historyRangesMigration === 'forwards'
  430. }
  431. await ProjectHistoryRedisManager.promises.queueResyncDocContent(
  432. projectId,
  433. projectHistoryId,
  434. docId,
  435. lines,
  436. ranges ?? {},
  437. resolvedCommentIds,
  438. version,
  439. // use the path from the resyncProjectStructure update
  440. path,
  441. historyRangesSupport
  442. )
  443. if (opts.historyRangesMigration) {
  444. await RedisManager.promises.setHistoryRangesSupportFlag(
  445. docId,
  446. historyRangesSupport
  447. )
  448. }
  449. },
  450. async getDocWithLock(projectId, docId) {
  451. const UpdateManager = require('./UpdateManager')
  452. return await UpdateManager.promises.lockUpdatesAndDo(
  453. DocumentManager.getDoc,
  454. projectId,
  455. docId
  456. )
  457. },
  458. async getDocAndRecentOpsWithLock(projectId, docId, fromVersion) {
  459. const UpdateManager = require('./UpdateManager')
  460. return await UpdateManager.promises.lockUpdatesAndDo(
  461. DocumentManager.getDocAndRecentOps,
  462. projectId,
  463. docId,
  464. fromVersion
  465. )
  466. },
  467. async getDocAndFlushIfOldWithLock(projectId, docId) {
  468. const UpdateManager = require('./UpdateManager')
  469. return await UpdateManager.promises.lockUpdatesAndDo(
  470. DocumentManager.getDocAndFlushIfOld,
  471. projectId,
  472. docId
  473. )
  474. },
  475. async setDocWithLock(
  476. projectId,
  477. docId,
  478. lines,
  479. source,
  480. userId,
  481. undoing,
  482. external
  483. ) {
  484. const UpdateManager = require('./UpdateManager')
  485. return await UpdateManager.promises.lockUpdatesAndDo(
  486. DocumentManager.setDoc,
  487. projectId,
  488. docId,
  489. lines,
  490. source,
  491. userId,
  492. undoing,
  493. external
  494. )
  495. },
  496. async appendToDocWithLock(projectId, docId, lines, source, userId) {
  497. const UpdateManager = require('./UpdateManager')
  498. return await UpdateManager.promises.lockUpdatesAndDo(
  499. DocumentManager.appendToDoc,
  500. projectId,
  501. docId,
  502. lines,
  503. source,
  504. userId
  505. )
  506. },
  507. async flushDocIfLoadedWithLock(projectId, docId) {
  508. const UpdateManager = require('./UpdateManager')
  509. return await UpdateManager.promises.lockUpdatesAndDo(
  510. DocumentManager.flushDocIfLoaded,
  511. projectId,
  512. docId
  513. )
  514. },
  515. async flushAndDeleteDocWithLock(projectId, docId, options) {
  516. const UpdateManager = require('./UpdateManager')
  517. return await UpdateManager.promises.lockUpdatesAndDo(
  518. DocumentManager.flushAndDeleteDoc,
  519. projectId,
  520. docId,
  521. options
  522. )
  523. },
  524. async acceptChangesWithLock(projectId, docId, changeIds) {
  525. const UpdateManager = require('./UpdateManager')
  526. await UpdateManager.promises.lockUpdatesAndDo(
  527. DocumentManager.acceptChanges,
  528. projectId,
  529. docId,
  530. changeIds
  531. )
  532. },
  533. async updateCommentStateWithLock(
  534. projectId,
  535. docId,
  536. threadId,
  537. userId,
  538. resolved
  539. ) {
  540. const UpdateManager = require('./UpdateManager')
  541. await UpdateManager.promises.lockUpdatesAndDo(
  542. DocumentManager.updateCommentState,
  543. projectId,
  544. docId,
  545. threadId,
  546. userId,
  547. resolved
  548. )
  549. },
  550. async deleteCommentWithLock(projectId, docId, threadId, userId) {
  551. const UpdateManager = require('./UpdateManager')
  552. await UpdateManager.promises.lockUpdatesAndDo(
  553. DocumentManager.deleteComment,
  554. projectId,
  555. docId,
  556. threadId,
  557. userId
  558. )
  559. },
  560. async renameDocWithLock(projectId, docId, userId, update, projectHistoryId) {
  561. const UpdateManager = require('./UpdateManager')
  562. await UpdateManager.promises.lockUpdatesAndDo(
  563. DocumentManager.renameDoc,
  564. projectId,
  565. docId,
  566. userId,
  567. update,
  568. projectHistoryId
  569. )
  570. },
  571. async resyncDocContentsWithLock(projectId, docId, path, opts) {
  572. const UpdateManager = require('./UpdateManager')
  573. await UpdateManager.promises.lockUpdatesAndDo(
  574. DocumentManager.resyncDocContents,
  575. projectId,
  576. docId,
  577. path,
  578. opts
  579. )
  580. },
  581. }
  582. module.exports = {
  583. ...callbackifyAll(DocumentManager, {
  584. multiResult: {
  585. getDoc: [
  586. 'lines',
  587. 'version',
  588. 'ranges',
  589. 'pathname',
  590. 'projectHistoryId',
  591. 'unflushedTime',
  592. 'alreadyLoaded',
  593. 'historyRangesSupport',
  594. ],
  595. getDocWithLock: [
  596. 'lines',
  597. 'version',
  598. 'ranges',
  599. 'pathname',
  600. 'projectHistoryId',
  601. 'unflushedTime',
  602. 'alreadyLoaded',
  603. 'historyRangesSupport',
  604. ],
  605. getDocAndFlushIfOld: ['lines', 'version'],
  606. getDocAndFlushIfOldWithLock: ['lines', 'version'],
  607. getDocAndRecentOps: [
  608. 'lines',
  609. 'version',
  610. 'ops',
  611. 'ranges',
  612. 'pathname',
  613. 'projectHistoryId',
  614. ],
  615. getDocAndRecentOpsWithLock: [
  616. 'lines',
  617. 'version',
  618. 'ops',
  619. 'ranges',
  620. 'pathname',
  621. 'projectHistoryId',
  622. ],
  623. },
  624. }),
  625. promises: DocumentManager,
  626. }