HttpController.js 13 KB

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