DocumentManager.js 18 KB

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