DocumentManager.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. PersistenceManager.setDoc(
  288. projectId,
  289. docId,
  290. lines,
  291. version,
  292. ranges,
  293. lastUpdatedAt,
  294. lastUpdatedBy,
  295. (error, result) => {
  296. if (error) {
  297. return callback(error)
  298. }
  299. RedisManager.clearUnflushedTime(docId, err => {
  300. if (err) {
  301. return callback(err)
  302. }
  303. callback(null, result)
  304. })
  305. }
  306. )
  307. }
  308. }
  309. )
  310. },
  311. flushAndDeleteDoc(projectId, docId, options, _callback) {
  312. const timer = new Metrics.Timer('docManager.flushAndDeleteDoc')
  313. const callback = (...args) => {
  314. timer.done()
  315. _callback(...args)
  316. }
  317. DocumentManager.flushDocIfLoaded(projectId, docId, (error, result) => {
  318. if (error) {
  319. if (options.ignoreFlushErrors) {
  320. logger.warn(
  321. { projectId, docId, err: error },
  322. 'ignoring flush error while deleting document'
  323. )
  324. } else {
  325. return callback(error)
  326. }
  327. }
  328. RedisManager.removeDocFromMemory(projectId, docId, error => {
  329. if (error) {
  330. return callback(error)
  331. }
  332. callback(null, result)
  333. })
  334. })
  335. },
  336. acceptChanges(projectId, docId, changeIds, _callback) {
  337. if (changeIds == null) {
  338. changeIds = []
  339. }
  340. const timer = new Metrics.Timer('docManager.acceptChanges')
  341. const callback = (...args) => {
  342. timer.done()
  343. _callback(...args)
  344. }
  345. DocumentManager.getDoc(
  346. projectId,
  347. docId,
  348. (error, lines, version, ranges) => {
  349. if (error) {
  350. return callback(error)
  351. }
  352. if (lines == null || version == null) {
  353. return callback(
  354. new Errors.NotFoundError(`document not found: ${docId}`)
  355. )
  356. }
  357. RangesManager.acceptChanges(changeIds, ranges, (error, newRanges) => {
  358. if (error) {
  359. return callback(error)
  360. }
  361. RedisManager.updateDocument(
  362. projectId,
  363. docId,
  364. lines,
  365. version,
  366. [],
  367. newRanges,
  368. {},
  369. error => {
  370. if (error) {
  371. return callback(error)
  372. }
  373. callback()
  374. }
  375. )
  376. })
  377. }
  378. )
  379. },
  380. deleteComment(projectId, docId, commentId, _callback) {
  381. const timer = new Metrics.Timer('docManager.deleteComment')
  382. const callback = (...args) => {
  383. timer.done()
  384. _callback(...args)
  385. }
  386. DocumentManager.getDoc(
  387. projectId,
  388. docId,
  389. (error, lines, version, ranges) => {
  390. if (error) {
  391. return callback(error)
  392. }
  393. if (lines == null || version == null) {
  394. return callback(
  395. new Errors.NotFoundError(`document not found: ${docId}`)
  396. )
  397. }
  398. RangesManager.deleteComment(commentId, ranges, (error, newRanges) => {
  399. if (error) {
  400. return callback(error)
  401. }
  402. RedisManager.updateDocument(
  403. projectId,
  404. docId,
  405. lines,
  406. version,
  407. [],
  408. newRanges,
  409. {},
  410. error => {
  411. if (error) {
  412. return callback(error)
  413. }
  414. callback()
  415. }
  416. )
  417. })
  418. }
  419. )
  420. },
  421. renameDoc(projectId, docId, userId, update, projectHistoryId, _callback) {
  422. const timer = new Metrics.Timer('docManager.updateProject')
  423. const callback = (...args) => {
  424. timer.done()
  425. _callback(...args)
  426. }
  427. RedisManager.renameDoc(
  428. projectId,
  429. docId,
  430. userId,
  431. update,
  432. projectHistoryId,
  433. callback
  434. )
  435. },
  436. getDocAndFlushIfOld(projectId, docId, callback) {
  437. DocumentManager.getDoc(
  438. projectId,
  439. docId,
  440. (
  441. error,
  442. lines,
  443. version,
  444. ranges,
  445. pathname,
  446. projectHistoryId,
  447. unflushedTime,
  448. alreadyLoaded
  449. ) => {
  450. if (error) {
  451. return callback(error)
  452. }
  453. // if doc was already loaded see if it needs to be flushed
  454. if (
  455. alreadyLoaded &&
  456. unflushedTime != null &&
  457. Date.now() - unflushedTime > MAX_UNFLUSHED_AGE
  458. ) {
  459. DocumentManager.flushDocIfLoaded(projectId, docId, error => {
  460. if (error) {
  461. return callback(error)
  462. }
  463. callback(null, lines, version)
  464. })
  465. } else {
  466. callback(null, lines, version)
  467. }
  468. }
  469. )
  470. },
  471. resyncDocContents(projectId, docId, path, callback) {
  472. logger.debug({ projectId, docId, path }, 'start resyncing doc contents')
  473. RedisManager.getDoc(
  474. projectId,
  475. docId,
  476. (error, lines, version, ranges, pathname, projectHistoryId) => {
  477. if (error) {
  478. return callback(error)
  479. }
  480. // To avoid issues where the same docId appears with different paths,
  481. // we use the path from the resyncProjectStructure update. If we used
  482. // the path from the getDoc call to web then the two occurences of the
  483. // docId would map to the same path, and this would be rejected by
  484. // project-history as an unexpected resyncDocContent update.
  485. if (lines == null || version == null) {
  486. logger.debug(
  487. { projectId, docId },
  488. 'resyncing doc contents - not found in redis - retrieving from web'
  489. )
  490. PersistenceManager.getDoc(
  491. projectId,
  492. docId,
  493. { peek: true },
  494. (error, lines, version, ranges, pathname, projectHistoryId) => {
  495. if (error) {
  496. logger.error(
  497. { projectId, docId, getDocError: error },
  498. 'resyncing doc contents - error retrieving from web'
  499. )
  500. return callback(error)
  501. }
  502. ProjectHistoryRedisManager.queueResyncDocContent(
  503. projectId,
  504. projectHistoryId,
  505. docId,
  506. lines,
  507. version,
  508. path, // use the path from the resyncProjectStructure update
  509. callback
  510. )
  511. }
  512. )
  513. } else {
  514. logger.debug(
  515. { projectId, docId },
  516. 'resyncing doc contents - doc in redis - will queue in redis'
  517. )
  518. ProjectHistoryRedisManager.queueResyncDocContent(
  519. projectId,
  520. projectHistoryId,
  521. docId,
  522. lines,
  523. version,
  524. path, // use the path from the resyncProjectStructure update
  525. callback
  526. )
  527. }
  528. }
  529. )
  530. },
  531. getDocWithLock(projectId, docId, callback) {
  532. const UpdateManager = require('./UpdateManager')
  533. UpdateManager.lockUpdatesAndDo(
  534. DocumentManager.getDoc,
  535. projectId,
  536. docId,
  537. callback
  538. )
  539. },
  540. getDocAndRecentOpsWithLock(projectId, docId, fromVersion, callback) {
  541. const UpdateManager = require('./UpdateManager')
  542. UpdateManager.lockUpdatesAndDo(
  543. DocumentManager.getDocAndRecentOps,
  544. projectId,
  545. docId,
  546. fromVersion,
  547. callback
  548. )
  549. },
  550. getDocAndFlushIfOldWithLock(projectId, docId, callback) {
  551. const UpdateManager = require('./UpdateManager')
  552. UpdateManager.lockUpdatesAndDo(
  553. DocumentManager.getDocAndFlushIfOld,
  554. projectId,
  555. docId,
  556. callback
  557. )
  558. },
  559. setDocWithLock(projectId, docId, lines, source, userId, undoing, callback) {
  560. const UpdateManager = require('./UpdateManager')
  561. UpdateManager.lockUpdatesAndDo(
  562. DocumentManager.setDoc,
  563. projectId,
  564. docId,
  565. lines,
  566. source,
  567. userId,
  568. undoing,
  569. callback
  570. )
  571. },
  572. flushDocIfLoadedWithLock(projectId, docId, callback) {
  573. const UpdateManager = require('./UpdateManager')
  574. UpdateManager.lockUpdatesAndDo(
  575. DocumentManager.flushDocIfLoaded,
  576. projectId,
  577. docId,
  578. callback
  579. )
  580. },
  581. flushAndDeleteDocWithLock(projectId, docId, options, callback) {
  582. const UpdateManager = require('./UpdateManager')
  583. UpdateManager.lockUpdatesAndDo(
  584. DocumentManager.flushAndDeleteDoc,
  585. projectId,
  586. docId,
  587. options,
  588. callback
  589. )
  590. },
  591. acceptChangesWithLock(projectId, docId, changeIds, callback) {
  592. const UpdateManager = require('./UpdateManager')
  593. UpdateManager.lockUpdatesAndDo(
  594. DocumentManager.acceptChanges,
  595. projectId,
  596. docId,
  597. changeIds,
  598. callback
  599. )
  600. },
  601. deleteCommentWithLock(projectId, docId, threadId, callback) {
  602. const UpdateManager = require('./UpdateManager')
  603. UpdateManager.lockUpdatesAndDo(
  604. DocumentManager.deleteComment,
  605. projectId,
  606. docId,
  607. threadId,
  608. callback
  609. )
  610. },
  611. renameDocWithLock(
  612. projectId,
  613. docId,
  614. userId,
  615. update,
  616. projectHistoryId,
  617. callback
  618. ) {
  619. const UpdateManager = require('./UpdateManager')
  620. UpdateManager.lockUpdatesAndDo(
  621. DocumentManager.renameDoc,
  622. projectId,
  623. docId,
  624. userId,
  625. update,
  626. projectHistoryId,
  627. callback
  628. )
  629. },
  630. resyncDocContentsWithLock(projectId, docId, path, callback) {
  631. const UpdateManager = require('./UpdateManager')
  632. UpdateManager.lockUpdatesAndDo(
  633. DocumentManager.resyncDocContents,
  634. projectId,
  635. docId,
  636. path,
  637. callback
  638. )
  639. },
  640. }