DocumentManager.js 20 KB

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