DocumentUpdaterHandler.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. const request = require('request').defaults({ timeout: 30 * 1000 })
  2. const OError = require('@overleaf/o-error')
  3. const settings = require('@overleaf/settings')
  4. const _ = require('lodash')
  5. const async = require('async')
  6. const logger = require('@overleaf/logger')
  7. const metrics = require('@overleaf/metrics')
  8. const { promisify, callbackify } = require('util')
  9. const { promisifyMultiResult } = require('@overleaf/promise-utils')
  10. const ProjectGetter = require('../Project/ProjectGetter')
  11. const FileStoreHandler = require('../FileStore/FileStoreHandler')
  12. const Features = require('../../infrastructure/Features')
  13. const Modules = require('../../infrastructure/Modules')
  14. function getProjectLastUpdatedAt(projectId, callback) {
  15. _makeRequest(
  16. {
  17. path: `/project/${projectId}/last_updated_at`,
  18. method: 'GET',
  19. json: true,
  20. },
  21. projectId,
  22. 'project.redis.last_updated_at',
  23. (err, body) => {
  24. if (err || !body?.lastUpdatedAt) return callback(err, null)
  25. callback(null, new Date(body.lastUpdatedAt))
  26. }
  27. )
  28. }
  29. /**
  30. * @param {string} projectId
  31. */
  32. function flushProjectToMongo(projectId, callback) {
  33. _makeRequest(
  34. {
  35. path: `/project/${projectId}/flush`,
  36. method: 'POST',
  37. },
  38. projectId,
  39. 'flushing.mongo.project',
  40. callback
  41. )
  42. }
  43. function flushMultipleProjectsToMongo(projectIds, callback) {
  44. const jobs = projectIds.map(projectId => callback => {
  45. flushProjectToMongo(projectId, callback)
  46. })
  47. async.series(jobs, callback)
  48. }
  49. /**
  50. * @param {string} projectId
  51. */
  52. function flushProjectToMongoAndDelete(projectId, callback) {
  53. _makeRequest(
  54. {
  55. path: `/project/${projectId}`,
  56. method: 'DELETE',
  57. },
  58. projectId,
  59. 'flushing.mongo.project',
  60. callback
  61. )
  62. }
  63. /**
  64. * @param {string} projectId
  65. * @param {string} docId
  66. * @param {Callback} callback
  67. */
  68. function flushDocToMongo(projectId, docId, callback) {
  69. _makeRequest(
  70. {
  71. path: `/project/${projectId}/doc/${docId}/flush`,
  72. method: 'POST',
  73. },
  74. projectId,
  75. 'flushing.mongo.doc',
  76. callback
  77. )
  78. }
  79. function deleteDoc(projectId, docId, ignoreFlushErrors, callback) {
  80. if (typeof ignoreFlushErrors === 'function') {
  81. callback = ignoreFlushErrors
  82. ignoreFlushErrors = false
  83. }
  84. let path = `/project/${projectId}/doc/${docId}`
  85. if (ignoreFlushErrors) {
  86. path += '?ignore_flush_errors=true'
  87. }
  88. const method = 'DELETE'
  89. _makeRequest(
  90. {
  91. path,
  92. method,
  93. },
  94. projectId,
  95. 'delete.mongo.doc',
  96. callback
  97. )
  98. }
  99. function getComment(projectId, docId, commentId, callback) {
  100. _makeRequest(
  101. {
  102. path: `/project/${projectId}/doc/${docId}/comment/${commentId}`,
  103. json: true,
  104. },
  105. projectId,
  106. 'get-comment',
  107. function (error, comment) {
  108. if (error) {
  109. return callback(error)
  110. }
  111. callback(null, comment)
  112. }
  113. )
  114. }
  115. function getDocument(projectId, docId, fromVersion, callback) {
  116. _makeRequest(
  117. {
  118. path: `/project/${projectId}/doc/${docId}?fromVersion=${fromVersion}`,
  119. json: true,
  120. },
  121. projectId,
  122. 'get-document',
  123. function (error, doc) {
  124. if (error) {
  125. return callback(error)
  126. }
  127. callback(null, doc.lines, doc.version, doc.ranges, doc.ops)
  128. }
  129. )
  130. }
  131. /**
  132. * Get a document with its history ranges
  133. * @param {string} projectId
  134. * @param {string} docId
  135. * @param {Callback} callback
  136. */
  137. function getDocumentWithHistoryRanges(projectId, docId, callback) {
  138. _makeRequest(
  139. {
  140. path: `/project/${projectId}/doc/${docId}?historyRanges=true`,
  141. json: true,
  142. },
  143. projectId,
  144. 'get-document-with-history-ranges',
  145. function (error, doc) {
  146. if (error) {
  147. return callback(error)
  148. }
  149. callback(null, doc)
  150. }
  151. )
  152. }
  153. function setDocument(projectId, docId, userId, docLines, source, callback) {
  154. _makeRequest(
  155. {
  156. path: `/project/${projectId}/doc/${docId}`,
  157. method: 'POST',
  158. json: {
  159. lines: docLines,
  160. source,
  161. user_id: userId,
  162. },
  163. },
  164. projectId,
  165. 'set-document',
  166. callback
  167. )
  168. }
  169. function appendToDocument(projectId, docId, userId, lines, source, callback) {
  170. _makeRequest(
  171. {
  172. path: `/project/${projectId}/doc/${docId}/append`,
  173. method: 'POST',
  174. json: {
  175. lines,
  176. source,
  177. user_id: userId,
  178. },
  179. },
  180. projectId,
  181. 'append-to-document',
  182. callback
  183. )
  184. }
  185. function getProjectDocsIfMatch(projectId, projectStateHash, callback) {
  186. // If the project state hasn't changed, we can get all the latest
  187. // docs from redis via the docupdater. Otherwise we will need to
  188. // fall back to getting them from mongo.
  189. const timer = new metrics.Timer('get-project-docs')
  190. const url = `${settings.apis.documentupdater.url}/project/${projectId}/get_and_flush_if_old?state=${projectStateHash}`
  191. request.post(url, function (error, res, body) {
  192. timer.done()
  193. if (error) {
  194. OError.tag(error, 'error getting project docs from doc updater', {
  195. url,
  196. projectId,
  197. })
  198. return callback(error)
  199. }
  200. if (res.statusCode === 409) {
  201. // HTTP response code "409 Conflict"
  202. // Docupdater has checked the projectStateHash and found that
  203. // it has changed. This means that the docs currently in redis
  204. // aren't the only change to the project and the full set of
  205. // docs/files should be retreived from docstore/filestore
  206. // instead.
  207. callback()
  208. } else if (res.statusCode >= 200 && res.statusCode < 300) {
  209. let docs
  210. try {
  211. docs = JSON.parse(body)
  212. } catch (error1) {
  213. return callback(OError.tag(error1))
  214. }
  215. callback(null, docs)
  216. } else {
  217. callback(
  218. new OError(
  219. `doc updater returned a non-success status code: ${res.statusCode}`,
  220. {
  221. projectId,
  222. url,
  223. }
  224. )
  225. )
  226. }
  227. })
  228. }
  229. function clearProjectState(projectId, callback) {
  230. _makeRequest(
  231. {
  232. path: `/project/${projectId}/clearState`,
  233. method: 'POST',
  234. },
  235. projectId,
  236. 'clear-project-state',
  237. callback
  238. )
  239. }
  240. /**
  241. * @param {string} projectId
  242. * @param {string} docId
  243. * @param {string[]} changeIds
  244. * @param {Callback} callback
  245. */
  246. async function acceptChanges(projectId, docId, changeIds) {
  247. await _makeRequestAsync(
  248. {
  249. path: `/project/${projectId}/doc/${docId}/change/accept`,
  250. json: { change_ids: changeIds },
  251. method: 'POST',
  252. },
  253. projectId,
  254. 'accept-changes'
  255. )
  256. await Modules.promises.hooks.fire('acceptedChanges', projectId, docId)
  257. }
  258. /**
  259. * @param {string} projectId
  260. * @param {string} docId
  261. * @param {string[]} changeIds
  262. * @param {Callback} callback
  263. */
  264. function rejectChanges(projectId, docId, changeIds, userId, callback) {
  265. _makeRequest(
  266. {
  267. path: `/project/${projectId}/doc/${docId}/change/reject`,
  268. json: { change_ids: changeIds, user_id: userId },
  269. method: 'POST',
  270. },
  271. projectId,
  272. 'reject-changes',
  273. callback
  274. )
  275. }
  276. function resolveThread(projectId, docId, threadId, userId, callback) {
  277. _makeRequest(
  278. {
  279. path: `/project/${projectId}/doc/${docId}/comment/${threadId}/resolve`,
  280. method: 'POST',
  281. json: {
  282. user_id: userId,
  283. },
  284. },
  285. projectId,
  286. 'resolve-thread',
  287. callback
  288. )
  289. }
  290. function reopenThread(projectId, docId, threadId, userId, callback) {
  291. _makeRequest(
  292. {
  293. path: `/project/${projectId}/doc/${docId}/comment/${threadId}/reopen`,
  294. method: 'POST',
  295. json: {
  296. user_id: userId,
  297. },
  298. },
  299. projectId,
  300. 'reopen-thread',
  301. callback
  302. )
  303. }
  304. function deleteThread(projectId, docId, threadId, userId, callback) {
  305. _makeRequest(
  306. {
  307. path: `/project/${projectId}/doc/${docId}/comment/${threadId}`,
  308. method: 'DELETE',
  309. json: {
  310. user_id: userId,
  311. },
  312. },
  313. projectId,
  314. 'delete-thread',
  315. callback
  316. )
  317. }
  318. function resyncProjectHistory(
  319. projectId,
  320. projectHistoryId,
  321. docs,
  322. files,
  323. opts,
  324. callback
  325. ) {
  326. docs = docs.map(doc => ({
  327. doc: doc.doc._id,
  328. path: doc.path,
  329. }))
  330. const hasFilestore = Features.hasFeature('filestore')
  331. if (!hasFilestore) {
  332. // Files without a hash likely do not have a blob. Abort.
  333. for (const { file } of files) {
  334. if (!file.hash) {
  335. return callback(
  336. new OError('found file with missing hash', { projectId, file })
  337. )
  338. }
  339. }
  340. }
  341. files = files.map(file => ({
  342. file: file.file._id,
  343. path: file.path,
  344. url: hasFilestore
  345. ? FileStoreHandler._buildUrl(projectId, file.file._id)
  346. : undefined,
  347. _hash: file.file.hash,
  348. createdBlob: !hasFilestore,
  349. metadata: buildFileMetadataForHistory(file.file),
  350. }))
  351. const body = { docs, files, projectHistoryId }
  352. if (opts.historyRangesMigration) {
  353. body.historyRangesMigration = opts.historyRangesMigration
  354. }
  355. if (opts.resyncProjectStructureOnly) {
  356. body.resyncProjectStructureOnly = opts.resyncProjectStructureOnly
  357. }
  358. _makeRequest(
  359. {
  360. path: `/project/${projectId}/history/resync`,
  361. json: body,
  362. method: 'POST',
  363. timeout: 6 * 60 * 1000, // allow 6 minutes for resync
  364. },
  365. projectId,
  366. 'resync-project-history',
  367. callback
  368. )
  369. }
  370. /**
  371. * Block a project from being loaded in docupdater
  372. *
  373. * @param {string} projectId
  374. * @param {Callback} callback
  375. */
  376. function blockProject(projectId, callback) {
  377. _makeRequest(
  378. { path: `/project/${projectId}/block`, method: 'POST', json: true },
  379. projectId,
  380. 'block-project',
  381. (err, body) => {
  382. if (err) {
  383. return callback(err)
  384. }
  385. callback(null, body.blocked)
  386. }
  387. )
  388. }
  389. /**
  390. * Unblock a previously blocked project
  391. *
  392. * @param {string} projectId
  393. * @param {Callback} callback
  394. */
  395. function unblockProject(projectId, callback) {
  396. _makeRequest(
  397. { path: `/project/${projectId}/unblock`, method: 'POST', json: true },
  398. projectId,
  399. 'unblock-project',
  400. (err, body) => {
  401. if (err) {
  402. return callback(err)
  403. }
  404. callback(null, body.wasBlocked)
  405. }
  406. )
  407. }
  408. function updateProjectStructure(
  409. projectId,
  410. projectHistoryId,
  411. userId,
  412. changes,
  413. source,
  414. callback
  415. ) {
  416. if (
  417. settings.apis.project_history == null ||
  418. !settings.apis.project_history.sendProjectStructureOps
  419. ) {
  420. return callback()
  421. }
  422. ProjectGetter.getProjectWithoutLock(
  423. projectId,
  424. { overleaf: true },
  425. (err, project) => {
  426. if (err) {
  427. return callback(err)
  428. }
  429. const historyRangesSupport = _.get(
  430. project,
  431. 'overleaf.history.rangesSupportEnabled',
  432. false
  433. )
  434. const {
  435. deletes: docDeletes,
  436. adds: docAdds,
  437. renames: docRenames,
  438. } = _getUpdates(
  439. 'doc',
  440. changes.oldDocs,
  441. changes.newDocs,
  442. historyRangesSupport
  443. )
  444. const hasFilestore = Features.hasFeature('filestore')
  445. if (!hasFilestore) {
  446. for (const newEntity of changes.newFiles || []) {
  447. if (!newEntity.file.hash) {
  448. // Files without a hash likely do not have a blob. Abort.
  449. return callback(
  450. new OError('found file with missing hash', { newEntity })
  451. )
  452. }
  453. }
  454. }
  455. const {
  456. deletes: fileDeletes,
  457. adds: fileAdds,
  458. renames: fileRenames,
  459. } = _getUpdates(
  460. 'file',
  461. changes.oldFiles,
  462. changes.newFiles,
  463. historyRangesSupport
  464. )
  465. const updates = [].concat(
  466. docDeletes,
  467. fileDeletes,
  468. docAdds,
  469. fileAdds,
  470. docRenames,
  471. fileRenames
  472. )
  473. const projectVersion =
  474. changes && changes.newProject && changes.newProject.version
  475. if (updates.length < 1) {
  476. return callback()
  477. }
  478. if (projectVersion == null) {
  479. logger.warn(
  480. { projectId, changes, projectVersion },
  481. 'did not receive project version in changes'
  482. )
  483. return callback(new Error('did not receive project version in changes'))
  484. }
  485. _makeRequest(
  486. {
  487. path: `/project/${projectId}`,
  488. json: {
  489. updates,
  490. userId,
  491. version: projectVersion,
  492. projectHistoryId,
  493. source,
  494. },
  495. method: 'POST',
  496. },
  497. projectId,
  498. 'update-project-structure',
  499. callback
  500. )
  501. }
  502. )
  503. }
  504. function _makeRequest(options, projectId, metricsKey, callback) {
  505. const timer = new metrics.Timer(metricsKey)
  506. request(
  507. {
  508. url: `${settings.apis.documentupdater.url}${options.path}`,
  509. json: options.json,
  510. method: options.method || 'GET',
  511. timeout: options.timeout || 30 * 1000,
  512. },
  513. function (error, res, body) {
  514. timer.done()
  515. if (error) {
  516. logger.warn(
  517. { error, projectId },
  518. 'error making request to document updater'
  519. )
  520. callback(error)
  521. } else if (res.statusCode >= 200 && res.statusCode < 300) {
  522. callback(null, body)
  523. } else {
  524. error = new Error(
  525. `document updater returned a failure status code: ${res.statusCode}`
  526. )
  527. logger.warn(
  528. { error, projectId },
  529. `document updater returned failure status code: ${res.statusCode}`
  530. )
  531. callback(error)
  532. }
  533. }
  534. )
  535. }
  536. const _makeRequestAsync = promisify(_makeRequest)
  537. function _getUpdates(
  538. entityType,
  539. oldEntities,
  540. newEntities,
  541. historyRangesSupport
  542. ) {
  543. if (!oldEntities) {
  544. oldEntities = []
  545. }
  546. if (!newEntities) {
  547. newEntities = []
  548. }
  549. const deletes = []
  550. const adds = []
  551. const renames = []
  552. const oldEntitiesHash = _.keyBy(oldEntities, entity =>
  553. entity[entityType]._id.toString()
  554. )
  555. const newEntitiesHash = _.keyBy(newEntities, entity =>
  556. entity[entityType]._id.toString()
  557. )
  558. // Send deletes before adds (and renames) to keep a 1:1 mapping between
  559. // paths and ids
  560. //
  561. // When a file is replaced, we first delete the old file and then add the
  562. // new file. If the 'add' operation is sent to project history before the
  563. // 'delete' then we would have two files with the same path at that point
  564. // in time.
  565. for (const id in oldEntitiesHash) {
  566. const oldEntity = oldEntitiesHash[id]
  567. const newEntity = newEntitiesHash[id]
  568. if (newEntity == null) {
  569. // entity deleted
  570. deletes.push({
  571. type: `rename-${entityType}`,
  572. id,
  573. pathname: oldEntity.path,
  574. newPathname: '',
  575. })
  576. }
  577. }
  578. const hasFilestore = Features.hasFeature('filestore')
  579. for (const id in newEntitiesHash) {
  580. const newEntity = newEntitiesHash[id]
  581. const oldEntity = oldEntitiesHash[id]
  582. if (oldEntity == null) {
  583. // entity added
  584. adds.push({
  585. type: `add-${entityType}`,
  586. id,
  587. pathname: newEntity.path,
  588. docLines: newEntity.docLines,
  589. ranges: newEntity.ranges,
  590. historyRangesSupport,
  591. url: newEntity.file != null && hasFilestore ? newEntity.url : undefined,
  592. hash: newEntity.file != null ? newEntity.file.hash : undefined,
  593. metadata: buildFileMetadataForHistory(newEntity.file),
  594. createdBlob: (newEntity.createdBlob || !hasFilestore) ?? false,
  595. })
  596. } else if (newEntity.path !== oldEntity.path) {
  597. // entity renamed
  598. renames.push({
  599. type: `rename-${entityType}`,
  600. id,
  601. pathname: oldEntity.path,
  602. newPathname: newEntity.path,
  603. })
  604. }
  605. }
  606. return { deletes, adds, renames }
  607. }
  608. function buildFileMetadataForHistory(file) {
  609. if (!file?.linkedFileData) return undefined
  610. const metadata = {
  611. // Files do not have a created at timestamp in the history.
  612. // For cloned projects, the importedAt timestamp needs to remain untouched.
  613. // Record the timestamp in the metadata blob to keep everything self-contained.
  614. importedAt: file.created,
  615. ...file.linkedFileData,
  616. }
  617. if (metadata.provider === 'project_output_file') {
  618. // The build-id and clsi-server-id are only used for downloading file.
  619. // Omit them from history as they are not useful in the future.
  620. delete metadata.build_id
  621. delete metadata.clsiServerId
  622. }
  623. return metadata
  624. }
  625. module.exports = {
  626. flushProjectToMongo,
  627. flushMultipleProjectsToMongo,
  628. flushProjectToMongoAndDelete,
  629. flushDocToMongo,
  630. deleteDoc,
  631. getComment,
  632. getDocument,
  633. getProjectLastUpdatedAt,
  634. setDocument,
  635. appendToDocument,
  636. getProjectDocsIfMatch,
  637. clearProjectState,
  638. acceptChanges: callbackify(acceptChanges),
  639. rejectChanges,
  640. resolveThread,
  641. reopenThread,
  642. deleteThread,
  643. resyncProjectHistory,
  644. blockProject,
  645. unblockProject,
  646. updateProjectStructure,
  647. getDocumentWithHistoryRanges,
  648. promises: {
  649. flushProjectToMongo: promisify(flushProjectToMongo),
  650. flushMultipleProjectsToMongo: promisify(flushMultipleProjectsToMongo),
  651. flushProjectToMongoAndDelete: promisify(flushProjectToMongoAndDelete),
  652. flushDocToMongo: promisify(flushDocToMongo),
  653. deleteDoc: promisify(deleteDoc),
  654. getComment: promisify(getComment),
  655. getDocument: promisifyMultiResult(getDocument, [
  656. 'lines',
  657. 'version',
  658. 'ranges',
  659. 'ops',
  660. ]),
  661. setDocument: promisify(setDocument),
  662. getProjectDocsIfMatch: promisify(getProjectDocsIfMatch),
  663. getProjectLastUpdatedAt: promisify(getProjectLastUpdatedAt),
  664. clearProjectState: promisify(clearProjectState),
  665. acceptChanges,
  666. rejectChanges: promisify(rejectChanges),
  667. resolveThread: promisify(resolveThread),
  668. reopenThread: promisify(reopenThread),
  669. deleteThread: promisify(deleteThread),
  670. resyncProjectHistory: promisify(resyncProjectHistory),
  671. blockProject: promisify(blockProject),
  672. unblockProject: promisify(unblockProject),
  673. updateProjectStructure: promisify(updateProjectStructure),
  674. appendToDocument: promisify(appendToDocument),
  675. getDocumentWithHistoryRanges: promisify(getDocumentWithHistoryRanges),
  676. },
  677. }