HttpController.js 14 KB

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