HttpController.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 healthCheck(req, res) {
  219. HealthChecker.check(err => {
  220. if (err != null) {
  221. logger.err({ err }, 'error performing health check')
  222. res.sendStatus(500)
  223. } else {
  224. res.sendStatus(200)
  225. }
  226. })
  227. }
  228. export function checkLock(req, res) {
  229. HealthChecker.checkLock(err => {
  230. if (err != null) {
  231. logger.err({ err }, 'error performing lock check')
  232. res.sendStatus(500)
  233. } else {
  234. res.sendStatus(200)
  235. }
  236. })
  237. }
  238. export function resyncProject(req, res, next) {
  239. const projectId = req.params.project_id
  240. const options = {}
  241. if (req.body.origin) {
  242. options.origin = req.body.origin
  243. }
  244. if (req.query.force || req.body.force) {
  245. // this will delete the queue and clear the sync state
  246. // use if the project is completely broken
  247. SyncManager.startHardResync(projectId, options, error => {
  248. if (error != null) {
  249. return next(error)
  250. }
  251. // flush the sync operations
  252. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  253. if (error != null) {
  254. return next(error)
  255. }
  256. res.sendStatus(204)
  257. })
  258. })
  259. } else {
  260. SyncManager.startResync(projectId, options, error => {
  261. if (error != null) {
  262. return next(error)
  263. }
  264. // flush the sync operations
  265. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  266. if (error != null) {
  267. return next(error)
  268. }
  269. res.sendStatus(204)
  270. })
  271. })
  272. }
  273. }
  274. export function forceDebugProject(req, res, next) {
  275. const projectId = req.params.project_id
  276. // set the debug flag to true unless we see ?clear=true
  277. const state = !req.query.clear
  278. ErrorRecorder.setForceDebug(projectId, state, error => {
  279. if (error != null) {
  280. return next(error)
  281. }
  282. // display the failure record to help debugging
  283. ErrorRecorder.getFailureRecord(projectId, (error, result) => {
  284. if (error != null) {
  285. return next(error)
  286. }
  287. res.send(result)
  288. })
  289. })
  290. }
  291. export function getFailures(req, res, next) {
  292. ErrorRecorder.getFailures((error, result) => {
  293. if (error != null) {
  294. return next(error)
  295. }
  296. res.send({ failures: result })
  297. })
  298. }
  299. export function getQueueCounts(req, res, next) {
  300. RedisManager.getProjectIdsWithHistoryOpsCount((err, queuedProjectsCount) => {
  301. if (err != null) {
  302. return next(err)
  303. }
  304. res.send({ queuedProjects: queuedProjectsCount })
  305. })
  306. }
  307. export function getLabels(req, res, next) {
  308. const projectId = req.params.project_id
  309. HistoryApiManager.shouldUseProjectHistory(
  310. projectId,
  311. (error, shouldUseProjectHistory) => {
  312. if (error != null) {
  313. return next(error)
  314. }
  315. if (shouldUseProjectHistory) {
  316. LabelsManager.getLabels(projectId, (error, labels) => {
  317. if (error != null) {
  318. return next(error)
  319. }
  320. res.json(labels)
  321. })
  322. } else {
  323. res.sendStatus(409)
  324. }
  325. }
  326. )
  327. }
  328. export function createLabel(req, res, next) {
  329. const { project_id: projectId, user_id: userId } = req.params
  330. const {
  331. version,
  332. comment,
  333. created_at: createdAt,
  334. validate_exists: validateExists,
  335. } = req.body
  336. HistoryApiManager.shouldUseProjectHistory(
  337. projectId,
  338. (error, shouldUseProjectHistory) => {
  339. if (error != null) {
  340. return next(error)
  341. }
  342. if (shouldUseProjectHistory) {
  343. LabelsManager.createLabel(
  344. projectId,
  345. userId,
  346. version,
  347. comment,
  348. createdAt,
  349. validateExists,
  350. (error, label) => {
  351. if (error != null) {
  352. return next(error)
  353. }
  354. res.json(label)
  355. }
  356. )
  357. } else {
  358. logger.error(
  359. {
  360. projectId,
  361. userId,
  362. version,
  363. comment,
  364. createdAt,
  365. validateExists,
  366. },
  367. 'not using v2 history'
  368. )
  369. res.sendStatus(409)
  370. }
  371. }
  372. )
  373. }
  374. /**
  375. * This will delete a label if it is owned by the current user. If you wish to
  376. * delete a label regardless of the current user, then use `deleteLabel` instead.
  377. */
  378. export function deleteLabelForUser(req, res, next) {
  379. const {
  380. project_id: projectId,
  381. user_id: userId,
  382. label_id: labelId,
  383. } = req.params
  384. LabelsManager.deleteLabelForUser(projectId, userId, labelId, error => {
  385. if (error != null) {
  386. return next(error)
  387. }
  388. res.sendStatus(204)
  389. })
  390. }
  391. export function deleteLabel(req, res, next) {
  392. const { project_id: projectId, label_id: labelId } = req.params
  393. LabelsManager.deleteLabel(projectId, labelId, error => {
  394. if (error != null) {
  395. return next(error)
  396. }
  397. res.sendStatus(204)
  398. })
  399. }
  400. export function retryFailures(req, res, next) {
  401. const { failureType, timeout, limit, callbackUrl } = req.query
  402. if (callbackUrl) {
  403. // send response but run in background when callbackUrl provided
  404. res.send({ retryStatus: 'running retryFailures in background' })
  405. }
  406. RetryManager.retryFailures(
  407. { failureType, timeout, limit },
  408. (error, result) => {
  409. if (callbackUrl) {
  410. // if present, notify the callbackUrl on success
  411. if (!error) {
  412. // Needs Node 12
  413. // const callbackHeaders = Object.fromEntries(Object.entries(req.headers || {}).filter(([k,v]) => k.match(/^X-CALLBACK-/i)))
  414. const callbackHeaders = {}
  415. for (const key of Object.getOwnPropertyNames(
  416. req.headers || {}
  417. ).filter(key => key.match(/^X-CALLBACK-/i))) {
  418. const found = key.match(/^X-CALLBACK-(.*)/i)
  419. callbackHeaders[found[1]] = req.headers[key]
  420. }
  421. request({ url: callbackUrl, headers: callbackHeaders })
  422. }
  423. } else {
  424. if (error != null) {
  425. return next(error)
  426. }
  427. res.send({ retryStatus: result })
  428. }
  429. }
  430. )
  431. }
  432. export function transferLabels(req, res, next) {
  433. const { from_user: fromUser, to_user: toUser } = req.params
  434. LabelsManager.transferLabels(fromUser, toUser, error => {
  435. if (error != null) {
  436. return next(error)
  437. }
  438. res.sendStatus(204)
  439. })
  440. }
  441. export function deleteProject(req, res, next) {
  442. const { project_id: projectId } = req.params
  443. // clear the timestamp before clearing the queue,
  444. // because the queue location is used in the migration
  445. RedisManager.clearFirstOpTimestamp(projectId, err => {
  446. if (err) {
  447. return next(err)
  448. }
  449. RedisManager.clearCachedHistoryId(projectId, err => {
  450. if (err) {
  451. return next(err)
  452. }
  453. RedisManager.destroyDocUpdatesQueue(projectId, err => {
  454. if (err) {
  455. return next(err)
  456. }
  457. SyncManager.clearResyncState(projectId, err => {
  458. if (err) {
  459. return next(err)
  460. }
  461. // The third parameter to the following call is the error. Calling it
  462. // with null will remove any failure record for this project.
  463. ErrorRecorder.record(projectId, 0, null, err => {
  464. if (err) {
  465. return next(err)
  466. }
  467. res.sendStatus(204)
  468. })
  469. })
  470. })
  471. })
  472. })
  473. }