HttpController.js 13 KB

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