HttpController.js 14 KB

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