DocumentUpdaterHandler.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. import OError from '@overleaf/o-error'
  2. import settings from '@overleaf/settings'
  3. import {
  4. fetchJson,
  5. fetchNothing,
  6. fetchString,
  7. RequestFailedError,
  8. } from '@overleaf/fetch-utils'
  9. import _ from 'lodash'
  10. import logger from '@overleaf/logger'
  11. import { callbackifyAll } from '@overleaf/promise-utils'
  12. import ProjectGetter from '../Project/ProjectGetter.mjs'
  13. import Modules from '../../infrastructure/Modules.mjs'
  14. const REQUEST_TIMEOUT_MS = 30 * 1000
  15. const RESYNC_TIMEOUT_MS = 6 * 60 * 1000
  16. const BASE_URL = settings.apis.documentupdater.url
  17. async function getProjectLastUpdatedAt(projectId) {
  18. const body = await fetchJson(
  19. `${BASE_URL}/project/${projectId}/last_updated_at`,
  20. { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }
  21. )
  22. return body.lastUpdatedAt != null ? new Date(body.lastUpdatedAt) : null
  23. }
  24. async function getProjectRanges(projectId) {
  25. const { docs } = await fetchJson(`${BASE_URL}/project/${projectId}/ranges`, {
  26. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  27. })
  28. return docs
  29. }
  30. /**
  31. * @param {string} projectId
  32. */
  33. async function flushProjectToMongo(projectId) {
  34. await fetchNothing(`${BASE_URL}/project/${projectId}/flush`, {
  35. method: 'POST',
  36. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  37. })
  38. }
  39. async function flushMultipleProjectsToMongo(projectIds) {
  40. for (const projectId of projectIds) {
  41. await flushProjectToMongo(projectId)
  42. }
  43. }
  44. /**
  45. * @param {string} projectId
  46. */
  47. async function flushProjectToMongoAndDelete(projectId) {
  48. await fetchNothing(`${BASE_URL}/project/${projectId}`, {
  49. method: 'DELETE',
  50. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  51. })
  52. }
  53. /**
  54. * @param {string} projectId
  55. * @param {string} docId
  56. */
  57. async function flushDocToMongo(projectId, docId) {
  58. await fetchNothing(`${BASE_URL}/project/${projectId}/doc/${docId}/flush`, {
  59. method: 'POST',
  60. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  61. })
  62. }
  63. async function deleteDoc(projectId, docId, ignoreFlushErrors = false) {
  64. const url = new URL(`${BASE_URL}/project/${projectId}/doc/${docId}`)
  65. if (ignoreFlushErrors) {
  66. url.searchParams.set('ignore_flush_errors', 'true')
  67. }
  68. await fetchNothing(url, {
  69. method: 'DELETE',
  70. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  71. })
  72. }
  73. async function getComment(projectId, docId, commentId) {
  74. const comment = await fetchJson(
  75. `${BASE_URL}/project/${projectId}/doc/${docId}/comment/${commentId}`,
  76. { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }
  77. )
  78. return comment
  79. }
  80. async function getDocument(projectId, docId, fromVersion) {
  81. const url = new URL(`${BASE_URL}/project/${projectId}/doc/${docId}`)
  82. url.searchParams.set('fromVersion', fromVersion)
  83. const doc = await fetchJson(url, {
  84. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  85. })
  86. return {
  87. lines: doc.lines,
  88. version: doc.version,
  89. ranges: doc.ranges,
  90. ops: doc.ops,
  91. }
  92. }
  93. /**
  94. * Get a document with its history ranges
  95. * @param {string} projectId
  96. * @param {string} docId
  97. */
  98. async function getDocumentWithHistoryRanges(projectId, docId) {
  99. const doc = await fetchJson(
  100. `${BASE_URL}/project/${projectId}/doc/${docId}?historyRanges=true`,
  101. { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }
  102. )
  103. return doc
  104. }
  105. async function setDocument(projectId, docId, userId, docLines, source) {
  106. const maybeJson = await fetchString(
  107. `${BASE_URL}/project/${projectId}/doc/${docId}`,
  108. {
  109. method: 'POST',
  110. json: {
  111. lines: docLines,
  112. source,
  113. user_id: userId,
  114. },
  115. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  116. }
  117. )
  118. // The set document endpoint sometimes returns json and sometimes just an
  119. // empty response
  120. try {
  121. const { rev, modified } = JSON.parse(maybeJson)
  122. return { rev, modified }
  123. } catch (err) {
  124. return undefined
  125. }
  126. }
  127. async function appendToDocument(projectId, docId, userId, lines, source) {
  128. const maybeJson = await fetchString(
  129. `${BASE_URL}/project/${projectId}/doc/${docId}/append`,
  130. {
  131. method: 'POST',
  132. json: {
  133. lines,
  134. source,
  135. user_id: userId,
  136. },
  137. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  138. }
  139. )
  140. // The append to document endpoint sometimes returns json and sometimes just an
  141. // empty response
  142. try {
  143. const { rev, modified } = JSON.parse(maybeJson)
  144. return { rev, modified }
  145. } catch (err) {
  146. return undefined
  147. }
  148. }
  149. async function getProjectDocsIfMatch(projectId, projectStateHash) {
  150. // If the project state hasn't changed, we can get all the latest
  151. // docs from redis via the docupdater. Otherwise we will need to
  152. // fall back to getting them from mongo.
  153. const url = new URL(`${BASE_URL}/project/${projectId}/get_and_flush_if_old`)
  154. url.searchParams.set('state', projectStateHash)
  155. let docs
  156. try {
  157. docs = await fetchJson(url, {
  158. method: 'POST',
  159. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  160. })
  161. } catch (err) {
  162. if (err instanceof RequestFailedError && err.response.status === 409) {
  163. // HTTP response code "409 Conflict"
  164. // Docupdater has checked the projectStateHash and found that
  165. // it has changed. This means that the docs currently in redis
  166. // aren't the only change to the project and the full set of
  167. // docs/files should be retreived from docstore/filestore
  168. // instead.
  169. return undefined
  170. } else {
  171. throw err
  172. }
  173. }
  174. return docs
  175. }
  176. async function clearProjectState(projectId) {
  177. await fetchNothing(`${BASE_URL}/project/${projectId}/clearState`, {
  178. method: 'POST',
  179. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  180. })
  181. }
  182. /**
  183. * @param {string} projectId
  184. * @param {string} docId
  185. * @param {string[]} changeIds
  186. */
  187. async function acceptChanges(projectId, docId, changeIds, userId) {
  188. await fetchNothing(
  189. `${BASE_URL}/project/${projectId}/doc/${docId}/change/accept`,
  190. {
  191. method: 'POST',
  192. json: { change_ids: changeIds },
  193. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  194. }
  195. )
  196. await Modules.promises.hooks.fire('changesAccepted', projectId, docId, userId)
  197. }
  198. /**
  199. * @param {string} projectId
  200. * @param {string} docId
  201. * @param {string[]} changeIds
  202. */
  203. async function rejectChanges(projectId, docId, changeIds, userId) {
  204. const { rejectedChangeIds } = await fetchJson(
  205. `${BASE_URL}/project/${projectId}/doc/${docId}/change/reject`,
  206. {
  207. method: 'POST',
  208. json: { change_ids: changeIds, user_id: userId },
  209. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  210. }
  211. )
  212. return { rejectedChangeIds }
  213. }
  214. /**
  215. * @param {string} projectId
  216. * @param {string} docId
  217. * @param {string} threadId
  218. * @param {string} userId
  219. */
  220. async function resolveThread(projectId, docId, threadId, userId) {
  221. await fetchNothing(
  222. `${BASE_URL}/project/${projectId}/doc/${docId}/comment/${threadId}/resolve`,
  223. {
  224. method: 'POST',
  225. json: { user_id: userId },
  226. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  227. }
  228. )
  229. }
  230. /**
  231. * @param {string} projectId
  232. * @param {string} docId
  233. * @param {string} threadId
  234. * @param {string} userId
  235. */
  236. async function reopenThread(projectId, docId, threadId, userId) {
  237. await fetchNothing(
  238. `${BASE_URL}/project/${projectId}/doc/${docId}/comment/${threadId}/reopen`,
  239. {
  240. method: 'POST',
  241. json: { user_id: userId },
  242. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  243. }
  244. )
  245. }
  246. async function deleteThread(projectId, docId, threadId, userId) {
  247. await fetchNothing(
  248. `${BASE_URL}/project/${projectId}/doc/${docId}/comment/${threadId}`,
  249. {
  250. method: 'DELETE',
  251. json: { user_id: userId },
  252. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  253. }
  254. )
  255. }
  256. async function resyncProjectHistory(
  257. projectId,
  258. projectHistoryId,
  259. docs,
  260. files,
  261. opts
  262. ) {
  263. docs = docs.map(doc => ({
  264. doc: doc.doc._id,
  265. path: doc.path,
  266. }))
  267. // Files without a hash likely do not have a blob. Abort.
  268. for (const { file } of files) {
  269. if (!file.hash) {
  270. throw new OError('found file with missing hash', { projectId, file })
  271. }
  272. }
  273. files = files.map(file => ({
  274. file: file.file._id,
  275. path: file.path,
  276. _hash: file.file.hash,
  277. createdBlob: true,
  278. metadata: buildFileMetadataForHistory(file.file),
  279. }))
  280. const body = { docs, files, projectHistoryId }
  281. if (opts.historyRangesMigration) {
  282. body.historyRangesMigration = opts.historyRangesMigration
  283. }
  284. if (opts.resyncProjectStructureOnly) {
  285. body.resyncProjectStructureOnly = opts.resyncProjectStructureOnly
  286. }
  287. await fetchNothing(`${BASE_URL}/project/${projectId}/history/resync`, {
  288. json: body,
  289. method: 'POST',
  290. signal: AbortSignal.timeout(RESYNC_TIMEOUT_MS), // allow 6 minutes for resync
  291. })
  292. }
  293. /**
  294. * Block a project from being loaded in docupdater
  295. *
  296. * @param {string} projectId
  297. */
  298. async function blockProject(projectId) {
  299. const body = await fetchJson(`${BASE_URL}/project/${projectId}/block`, {
  300. method: 'POST',
  301. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  302. })
  303. return body.blocked
  304. }
  305. /**
  306. * Unblock a previously blocked project
  307. *
  308. * @param {string} projectId
  309. */
  310. async function unblockProject(projectId) {
  311. const body = await fetchJson(`${BASE_URL}/project/${projectId}/unblock`, {
  312. method: 'POST',
  313. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  314. })
  315. return body.wasBlocked
  316. }
  317. async function updateProjectStructure(
  318. projectId,
  319. projectHistoryId,
  320. userId,
  321. changes,
  322. source
  323. ) {
  324. if (
  325. settings.apis.project_history == null ||
  326. !settings.apis.project_history.sendProjectStructureOps
  327. ) {
  328. return
  329. }
  330. const project = await ProjectGetter.promises.getProjectWithoutLock(
  331. projectId,
  332. { overleaf: true }
  333. )
  334. const historyRangesSupport = _.get(
  335. project,
  336. 'overleaf.history.rangesSupportEnabled',
  337. false
  338. )
  339. const {
  340. deletes: docDeletes,
  341. adds: docAdds,
  342. renames: docRenames,
  343. } = _getUpdates('doc', changes.oldDocs, changes.newDocs, historyRangesSupport)
  344. for (const newEntity of changes.newFiles || []) {
  345. if (!newEntity.file.hash) {
  346. // Files without a hash likely do not have a blob. Abort.
  347. throw new OError('found file with missing hash', { newEntity })
  348. }
  349. }
  350. const {
  351. deletes: fileDeletes,
  352. adds: fileAdds,
  353. renames: fileRenames,
  354. } = _getUpdates(
  355. 'file',
  356. changes.oldFiles,
  357. changes.newFiles,
  358. historyRangesSupport
  359. )
  360. const updates = [].concat(
  361. docDeletes,
  362. fileDeletes,
  363. docAdds,
  364. fileAdds,
  365. docRenames,
  366. fileRenames
  367. )
  368. const projectVersion =
  369. changes && changes.newProject && changes.newProject.version
  370. if (updates.length < 1) {
  371. return
  372. }
  373. if (projectVersion == null) {
  374. logger.warn(
  375. { projectId, changes, projectVersion },
  376. 'did not receive project version in changes'
  377. )
  378. throw new Error('did not receive project version in changes')
  379. }
  380. await fetchNothing(`${BASE_URL}/project/${projectId}`, {
  381. method: 'POST',
  382. json: {
  383. updates,
  384. userId,
  385. version: projectVersion,
  386. projectHistoryId,
  387. source,
  388. },
  389. signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
  390. })
  391. }
  392. function _getUpdates(
  393. entityType,
  394. oldEntities,
  395. newEntities,
  396. historyRangesSupport
  397. ) {
  398. if (!oldEntities) {
  399. oldEntities = []
  400. }
  401. if (!newEntities) {
  402. newEntities = []
  403. }
  404. const deletes = []
  405. const adds = []
  406. const renames = []
  407. const oldEntitiesHash = _.keyBy(oldEntities, entity =>
  408. entity[entityType]._id.toString()
  409. )
  410. const newEntitiesHash = _.keyBy(newEntities, entity =>
  411. entity[entityType]._id.toString()
  412. )
  413. // Send deletes before adds (and renames) to keep a 1:1 mapping between
  414. // paths and ids
  415. //
  416. // When a file is replaced, we first delete the old file and then add the
  417. // new file. If the 'add' operation is sent to project history before the
  418. // 'delete' then we would have two files with the same path at that point
  419. // in time.
  420. for (const id in oldEntitiesHash) {
  421. const oldEntity = oldEntitiesHash[id]
  422. const newEntity = newEntitiesHash[id]
  423. if (newEntity == null) {
  424. // entity deleted
  425. deletes.push({
  426. type: `rename-${entityType}`,
  427. id,
  428. pathname: oldEntity.path,
  429. newPathname: '',
  430. })
  431. }
  432. }
  433. for (const id in newEntitiesHash) {
  434. const newEntity = newEntitiesHash[id]
  435. const oldEntity = oldEntitiesHash[id]
  436. if (oldEntity == null) {
  437. // entity added
  438. adds.push({
  439. type: `add-${entityType}`,
  440. id,
  441. pathname: newEntity.path,
  442. docLines: newEntity.docLines,
  443. ranges: newEntity.ranges,
  444. historyRangesSupport,
  445. hash: newEntity.file?.hash,
  446. metadata: buildFileMetadataForHistory(newEntity.file),
  447. createdBlob: true,
  448. })
  449. } else if (newEntity.path !== oldEntity.path) {
  450. // entity renamed
  451. renames.push({
  452. type: `rename-${entityType}`,
  453. id,
  454. pathname: oldEntity.path,
  455. newPathname: newEntity.path,
  456. })
  457. }
  458. }
  459. return { deletes, adds, renames }
  460. }
  461. function buildFileMetadataForHistory(file) {
  462. if (!file?.linkedFileData) return undefined
  463. const metadata = {
  464. // Files do not have a created at timestamp in the history.
  465. // For cloned projects, the importedAt timestamp needs to remain untouched.
  466. // Record the timestamp in the metadata blob to keep everything self-contained.
  467. importedAt: file.created,
  468. ...file.linkedFileData,
  469. }
  470. if (metadata.provider === 'project_output_file') {
  471. // The build-id and clsi-server-id are only used for downloading file.
  472. // Omit them from history as they are not useful in the future.
  473. delete metadata.build_id
  474. delete metadata.clsiServerId
  475. }
  476. return metadata
  477. }
  478. const DocumentUpdaterHandler = {
  479. flushProjectToMongo,
  480. flushMultipleProjectsToMongo,
  481. flushProjectToMongoAndDelete,
  482. flushDocToMongo,
  483. deleteDoc,
  484. getComment,
  485. getDocument,
  486. getProjectLastUpdatedAt,
  487. getProjectRanges,
  488. setDocument,
  489. appendToDocument,
  490. getProjectDocsIfMatch,
  491. clearProjectState,
  492. acceptChanges,
  493. rejectChanges,
  494. resolveThread,
  495. reopenThread,
  496. deleteThread,
  497. resyncProjectHistory,
  498. blockProject,
  499. unblockProject,
  500. updateProjectStructure,
  501. getDocumentWithHistoryRanges,
  502. }
  503. export default {
  504. ...callbackifyAll(DocumentUpdaterHandler, {
  505. multiResult: {
  506. getDocument: ['lines', 'version', 'ranges', 'ops'],
  507. },
  508. }),
  509. promises: DocumentUpdaterHandler,
  510. }