HttpController.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. import logger from '@overleaf/logger'
  2. import OError from '@overleaf/o-error'
  3. import request from 'request'
  4. import * as UpdatesProcessor from './UpdatesProcessor.js'
  5. import * as SummarizedUpdatesManager from './SummarizedUpdatesManager.js'
  6. import * as DiffManager from './DiffManager.js'
  7. import * as HistoryStoreManager from './HistoryStoreManager.js'
  8. import * as WebApiManager from './WebApiManager.js'
  9. import * as SnapshotManager from './SnapshotManager.js'
  10. import * as HealthChecker from './HealthChecker.js'
  11. import * as SyncManager from './SyncManager.js'
  12. import * as ErrorRecorder from './ErrorRecorder.js'
  13. import * as RedisManager from './RedisManager.js'
  14. import * as LabelsManager from './LabelsManager.js'
  15. import * as HistoryApiManager from './HistoryApiManager.js'
  16. import * as RetryManager from './RetryManager.js'
  17. import * as FlushManager from './FlushManager.js'
  18. import { pipeline } from 'stream'
  19. const ONE_DAY_IN_SECONDS = 24 * 60 * 60
  20. export function getProjectBlob(req, res, next) {
  21. const historyId = req.params.history_id
  22. const blobHash = req.params.hash
  23. HistoryStoreManager.getProjectBlobStream(
  24. historyId,
  25. blobHash,
  26. (err, stream) => {
  27. if (err != null) {
  28. return next(OError.tag(err))
  29. }
  30. res.setHeader('Cache-Control', `private, max-age=${ONE_DAY_IN_SECONDS}`)
  31. pipeline(stream, res, err => {
  32. if (err) next(err)
  33. // res.end() is already called via 'end' event by pipeline.
  34. })
  35. }
  36. )
  37. }
  38. export function initializeProject(req, res, next) {
  39. const { historyId } = req.body
  40. HistoryStoreManager.initializeProject(historyId, (error, id) => {
  41. if (error != null) {
  42. return next(OError.tag(error))
  43. }
  44. res.json({ project: { id } })
  45. })
  46. }
  47. export function flushProject(req, res, next) {
  48. const projectId = req.params.project_id
  49. if (req.query.debug) {
  50. logger.debug(
  51. { projectId },
  52. 'compressing project history in single-step mode'
  53. )
  54. UpdatesProcessor.processSingleUpdateForProject(projectId, error => {
  55. if (error != null) {
  56. return next(OError.tag(error))
  57. }
  58. res.sendStatus(204)
  59. })
  60. } else if (req.query.bisect) {
  61. logger.debug({ projectId }, 'compressing project history in bisect mode')
  62. UpdatesProcessor.processUpdatesForProjectUsingBisect(
  63. projectId,
  64. UpdatesProcessor.REDIS_READ_BATCH_SIZE,
  65. error => {
  66. if (error != null) {
  67. return next(OError.tag(error))
  68. }
  69. res.sendStatus(204)
  70. }
  71. )
  72. } else {
  73. logger.debug({ projectId }, 'compressing project history')
  74. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  75. if (error != null) {
  76. return next(OError.tag(error))
  77. }
  78. res.sendStatus(204)
  79. })
  80. }
  81. }
  82. export function dumpProject(req, res, next) {
  83. const projectId = req.params.project_id
  84. const batchSize = req.query.count || UpdatesProcessor.REDIS_READ_BATCH_SIZE
  85. logger.debug({ projectId }, 'retrieving raw updates')
  86. UpdatesProcessor.getRawUpdates(projectId, batchSize, (error, rawUpdates) => {
  87. if (error != null) {
  88. return next(OError.tag(error))
  89. }
  90. res.json(rawUpdates)
  91. })
  92. }
  93. export function flushOld(req, res, next) {
  94. const { maxAge, queueDelay, limit, timeout, background } = req.query
  95. const options = { maxAge, queueDelay, limit, timeout, background }
  96. FlushManager.flushOldOps(options, (error, results) => {
  97. if (error != null) {
  98. return next(OError.tag(error))
  99. }
  100. res.send(results)
  101. })
  102. }
  103. export function getDiff(req, res, next) {
  104. const projectId = req.params.project_id
  105. const { pathname, from, to } = req.query
  106. if (pathname == null) {
  107. return res.sendStatus(400)
  108. }
  109. logger.debug({ projectId, pathname, from, to }, 'getting diff')
  110. DiffManager.getDiff(projectId, pathname, from, to, (error, diff) => {
  111. if (error != null) {
  112. return next(OError.tag(error))
  113. }
  114. res.json({ diff })
  115. })
  116. }
  117. export function getFileTreeDiff(req, res, next) {
  118. const projectId = req.params.project_id
  119. const { to, from } = req.query
  120. DiffManager.getFileTreeDiff(projectId, from, to, (error, diff) => {
  121. if (error != null) {
  122. return next(OError.tag(error))
  123. }
  124. res.json({ diff })
  125. })
  126. }
  127. export function getUpdates(req, res, next) {
  128. const projectId = req.params.project_id
  129. const { before, min_count: minCount } = req.query
  130. SummarizedUpdatesManager.getSummarizedProjectUpdates(
  131. projectId,
  132. { before, min_count: minCount },
  133. (error, updates, nextBeforeTimestamp) => {
  134. if (error != null) {
  135. return next(OError.tag(error))
  136. }
  137. for (const update of updates) {
  138. // Sets don't JSONify, so convert to arrays
  139. update.pathnames = Array.from(update.pathnames || []).sort()
  140. }
  141. res.json({
  142. updates,
  143. nextBeforeTimestamp,
  144. })
  145. }
  146. )
  147. }
  148. export function latestVersion(req, res, next) {
  149. const projectId = req.params.project_id
  150. logger.debug({ projectId }, 'compressing project history and getting version')
  151. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  152. if (error != null) {
  153. return next(OError.tag(error))
  154. }
  155. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  156. if (error != null) {
  157. return next(OError.tag(error))
  158. }
  159. HistoryStoreManager.getMostRecentVersion(
  160. projectId,
  161. historyId,
  162. (error, version, projectStructureAndDocVersions, lastChange) => {
  163. if (error != null) {
  164. return next(OError.tag(error))
  165. }
  166. res.json({
  167. version,
  168. timestamp: lastChange != null ? lastChange.timestamp : undefined,
  169. v2Authors: lastChange != null ? lastChange.v2Authors : undefined,
  170. })
  171. }
  172. )
  173. })
  174. })
  175. }
  176. export function getFileSnapshot(req, res, next) {
  177. const { project_id: projectId, version, pathname } = req.params
  178. SnapshotManager.getFileSnapshotStream(
  179. projectId,
  180. version,
  181. pathname,
  182. (error, stream) => {
  183. if (error != null) {
  184. return next(OError.tag(error))
  185. }
  186. pipeline(stream, res, err => {
  187. if (err) next(err)
  188. // res.end() is already called via 'end' event by pipeline.
  189. })
  190. }
  191. )
  192. }
  193. export function getRangesSnapshot(req, res, next) {
  194. const { project_id: projectId, version, pathname } = req.params
  195. SnapshotManager.getRangesSnapshot(
  196. projectId,
  197. version,
  198. pathname,
  199. (err, ranges) => {
  200. if (err) {
  201. return next(OError.tag(err))
  202. }
  203. res.json(ranges)
  204. }
  205. )
  206. }
  207. export function getFileMetadataSnapshot(req, res, next) {
  208. const { project_id: projectId, version, pathname } = req.params
  209. SnapshotManager.getFileMetadataSnapshot(
  210. projectId,
  211. version,
  212. pathname,
  213. (err, data) => {
  214. if (err) {
  215. return next(OError.tag(err))
  216. }
  217. res.json(data)
  218. }
  219. )
  220. }
  221. export function getMostRecentChunk(req, res, next) {
  222. const { project_id: projectId } = req.params
  223. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  224. if (error) return next(OError.tag(error))
  225. HistoryStoreManager.getMostRecentChunk(
  226. projectId,
  227. historyId,
  228. (err, data) => {
  229. if (err) return next(OError.tag(err))
  230. res.json(data)
  231. }
  232. )
  233. })
  234. }
  235. export function getLatestSnapshot(req, res, next) {
  236. const { project_id: projectId } = req.params
  237. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  238. if (error) return next(OError.tag(error))
  239. SnapshotManager.getLatestSnapshot(
  240. projectId,
  241. historyId,
  242. (error, details) => {
  243. if (error != null) {
  244. return next(error)
  245. }
  246. const { snapshot, version } = details
  247. res.json({ snapshot: snapshot.toRaw(), version })
  248. }
  249. )
  250. })
  251. }
  252. export function getChangesSince(req, res, next) {
  253. const { project_id: projectId } = req.params
  254. const { since } = req.query
  255. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  256. if (error) return next(OError.tag(error))
  257. SnapshotManager.getChangesSince(
  258. projectId,
  259. historyId,
  260. since,
  261. (error, changes) => {
  262. if (error != null) {
  263. return next(error)
  264. }
  265. res.json(changes.map(c => c.toRaw()))
  266. }
  267. )
  268. })
  269. }
  270. export function getChangesInChunkSince(req, res, next) {
  271. const { project_id: projectId } = req.params
  272. const { since } = req.query
  273. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  274. if (error) return next(OError.tag(error))
  275. SnapshotManager.getChangesInChunkSince(
  276. projectId,
  277. historyId,
  278. since,
  279. (error, details) => {
  280. if (error != null) {
  281. return next(error)
  282. }
  283. const { latestStartVersion, changes } = details
  284. res.json({
  285. latestStartVersion,
  286. changes: changes.map(c => c.toRaw()),
  287. })
  288. }
  289. )
  290. })
  291. }
  292. export function getProjectSnapshot(req, res, next) {
  293. const { project_id: projectId, version } = req.params
  294. SnapshotManager.getProjectSnapshot(
  295. projectId,
  296. version,
  297. (error, snapshotData) => {
  298. if (error != null) {
  299. return next(error)
  300. }
  301. res.json(snapshotData)
  302. }
  303. )
  304. }
  305. export function getPathsAtVersion(req, res, next) {
  306. const { project_id: projectId, version } = req.params
  307. SnapshotManager.getPathsAtVersion(projectId, version, (error, result) => {
  308. if (error != null) {
  309. return next(error)
  310. }
  311. res.json(result)
  312. })
  313. }
  314. export function healthCheck(req, res) {
  315. HealthChecker.check(err => {
  316. if (err != null) {
  317. logger.err({ err }, 'error performing health check')
  318. res.sendStatus(500)
  319. } else {
  320. res.sendStatus(200)
  321. }
  322. })
  323. }
  324. export function checkLock(req, res) {
  325. HealthChecker.checkLock(err => {
  326. if (err != null) {
  327. logger.err({ err }, 'error performing lock check')
  328. res.sendStatus(500)
  329. } else {
  330. res.sendStatus(200)
  331. }
  332. })
  333. }
  334. export function resyncProject(req, res, next) {
  335. const projectId = req.params.project_id
  336. const options = {}
  337. if (req.body.origin) {
  338. options.origin = req.body.origin
  339. }
  340. if (req.body.historyRangesMigration) {
  341. options.historyRangesMigration = req.body.historyRangesMigration
  342. }
  343. if (req.query.force || req.body.force) {
  344. // this will delete the queue and clear the sync state
  345. // use if the project is completely broken
  346. SyncManager.startHardResync(projectId, options, error => {
  347. if (error != null) {
  348. return next(error)
  349. }
  350. // flush the sync operations
  351. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  352. if (error != null) {
  353. return next(error)
  354. }
  355. res.sendStatus(204)
  356. })
  357. })
  358. } else {
  359. SyncManager.startResync(projectId, options, error => {
  360. if (error != null) {
  361. return next(error)
  362. }
  363. // flush the sync operations
  364. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  365. if (error != null) {
  366. return next(error)
  367. }
  368. res.sendStatus(204)
  369. })
  370. })
  371. }
  372. }
  373. export function forceDebugProject(req, res, next) {
  374. const projectId = req.params.project_id
  375. // set the debug flag to true unless we see ?clear=true
  376. const state = !req.query.clear
  377. ErrorRecorder.setForceDebug(projectId, state, error => {
  378. if (error != null) {
  379. return next(error)
  380. }
  381. // display the failure record to help debugging
  382. ErrorRecorder.getFailureRecord(projectId, (error, result) => {
  383. if (error != null) {
  384. return next(error)
  385. }
  386. res.send(result)
  387. })
  388. })
  389. }
  390. export function getFailures(req, res, next) {
  391. ErrorRecorder.getFailures((error, result) => {
  392. if (error != null) {
  393. return next(error)
  394. }
  395. res.send({ failures: result })
  396. })
  397. }
  398. export function getQueueCounts(req, res, next) {
  399. RedisManager.getProjectIdsWithHistoryOpsCount((err, queuedProjectsCount) => {
  400. if (err != null) {
  401. return next(err)
  402. }
  403. res.send({ queuedProjects: queuedProjectsCount })
  404. })
  405. }
  406. export function getLabels(req, res, next) {
  407. const projectId = req.params.project_id
  408. HistoryApiManager.shouldUseProjectHistory(
  409. projectId,
  410. (error, shouldUseProjectHistory) => {
  411. if (error != null) {
  412. return next(error)
  413. }
  414. if (shouldUseProjectHistory) {
  415. LabelsManager.getLabels(projectId, (error, labels) => {
  416. if (error != null) {
  417. return next(error)
  418. }
  419. res.json(labels)
  420. })
  421. } else {
  422. res.sendStatus(409)
  423. }
  424. }
  425. )
  426. }
  427. export function createLabel(req, res, next) {
  428. const { project_id: projectId, user_id: userIdParam } = req.params
  429. const {
  430. version,
  431. comment,
  432. user_id: userIdBody,
  433. created_at: createdAt,
  434. validate_exists: validateExists,
  435. } = req.body
  436. // Temporarily looking up both params and body while rolling out changes
  437. // in the router path - https://github.com/overleaf/internal/pull/20200
  438. const userId = userIdParam || userIdBody
  439. HistoryApiManager.shouldUseProjectHistory(
  440. projectId,
  441. (error, shouldUseProjectHistory) => {
  442. if (error != null) {
  443. return next(error)
  444. }
  445. if (shouldUseProjectHistory) {
  446. LabelsManager.createLabel(
  447. projectId,
  448. userId,
  449. version,
  450. comment,
  451. createdAt,
  452. validateExists,
  453. (error, label) => {
  454. if (error != null) {
  455. return next(error)
  456. }
  457. res.json(label)
  458. }
  459. )
  460. } else {
  461. logger.error(
  462. {
  463. projectId,
  464. userId,
  465. version,
  466. comment,
  467. createdAt,
  468. validateExists,
  469. },
  470. 'not using v2 history'
  471. )
  472. res.sendStatus(409)
  473. }
  474. }
  475. )
  476. }
  477. /**
  478. * This will delete a label if it is owned by the current user. If you wish to
  479. * delete a label regardless of the current user, then use `deleteLabel` instead.
  480. */
  481. export function deleteLabelForUser(req, res, next) {
  482. const {
  483. project_id: projectId,
  484. user_id: userId,
  485. label_id: labelId,
  486. } = req.params
  487. LabelsManager.deleteLabelForUser(projectId, userId, labelId, error => {
  488. if (error != null) {
  489. return next(error)
  490. }
  491. res.sendStatus(204)
  492. })
  493. }
  494. export function deleteLabel(req, res, next) {
  495. const { project_id: projectId, label_id: labelId } = req.params
  496. LabelsManager.deleteLabel(projectId, labelId, error => {
  497. if (error != null) {
  498. return next(error)
  499. }
  500. res.sendStatus(204)
  501. })
  502. }
  503. export function retryFailures(req, res, next) {
  504. const { failureType, timeout, limit, callbackUrl } = req.query
  505. if (callbackUrl) {
  506. // send response but run in background when callbackUrl provided
  507. res.send({ retryStatus: 'running retryFailures in background' })
  508. }
  509. RetryManager.retryFailures(
  510. { failureType, timeout, limit },
  511. (error, result) => {
  512. if (callbackUrl) {
  513. // if present, notify the callbackUrl on success
  514. if (!error) {
  515. // Needs Node 12
  516. // const callbackHeaders = Object.fromEntries(Object.entries(req.headers || {}).filter(([k,v]) => k.match(/^X-CALLBACK-/i)))
  517. const callbackHeaders = {}
  518. for (const key of Object.getOwnPropertyNames(
  519. req.headers || {}
  520. ).filter(key => key.match(/^X-CALLBACK-/i))) {
  521. const found = key.match(/^X-CALLBACK-(.*)/i)
  522. callbackHeaders[found[1]] = req.headers[key]
  523. }
  524. request({ url: callbackUrl, headers: callbackHeaders })
  525. }
  526. } else {
  527. if (error != null) {
  528. return next(error)
  529. }
  530. res.send({ retryStatus: result })
  531. }
  532. }
  533. )
  534. }
  535. export function transferLabels(req, res, next) {
  536. const { from_user: fromUser, to_user: toUser } = req.params
  537. LabelsManager.transferLabels(fromUser, toUser, error => {
  538. if (error != null) {
  539. return next(error)
  540. }
  541. res.sendStatus(204)
  542. })
  543. }
  544. export function deleteProject(req, res, next) {
  545. const { project_id: projectId } = req.params
  546. // clear the timestamp before clearing the queue,
  547. // because the queue location is used in the migration
  548. RedisManager.clearFirstOpTimestamp(projectId, err => {
  549. if (err) {
  550. return next(err)
  551. }
  552. RedisManager.clearCachedHistoryId(projectId, err => {
  553. if (err) {
  554. return next(err)
  555. }
  556. RedisManager.destroyDocUpdatesQueue(projectId, err => {
  557. if (err) {
  558. return next(err)
  559. }
  560. SyncManager.clearResyncState(projectId, err => {
  561. if (err) {
  562. return next(err)
  563. }
  564. // The third parameter to the following call is the error. Calling it
  565. // with null will remove any failure record for this project.
  566. ErrorRecorder.record(projectId, 0, null, err => {
  567. if (err) {
  568. return next(err)
  569. }
  570. res.sendStatus(204)
  571. })
  572. })
  573. })
  574. })
  575. })
  576. }