HttpController.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. import logger from '@overleaf/logger'
  2. import OError from '@overleaf/o-error'
  3. import * as UpdatesProcessor from './UpdatesProcessor.js'
  4. import * as SummarizedUpdatesManager from './SummarizedUpdatesManager.js'
  5. import * as DiffManager from './DiffManager.js'
  6. import * as HistoryStoreManager from './HistoryStoreManager.js'
  7. import * as WebApiManager from './WebApiManager.js'
  8. import * as SnapshotManager from './SnapshotManager.js'
  9. import * as HealthChecker from './HealthChecker.js'
  10. import * as SyncManager from './SyncManager.js'
  11. import * as ErrorRecorder from './ErrorRecorder.js'
  12. import * as RedisManager from './RedisManager.js'
  13. import * as LabelsManager from './LabelsManager.js'
  14. import * as HistoryApiManager from './HistoryApiManager.js'
  15. import * as RetryManager from './RetryManager.js'
  16. import * as FlushManager from './FlushManager.js'
  17. import Stream, { pipeline } from 'node:stream'
  18. import { fetchNothing, RequestFailedError } from '@overleaf/fetch-utils'
  19. import { z, zz, parseReq } from '@overleaf/validation-tools'
  20. import { IncrementalResponse } from '@overleaf/stream-utils'
  21. const ONE_DAY_IN_SECONDS = 24 * 60 * 60
  22. const cloneProjectSchema = z.object({
  23. body: z.object({
  24. targetProjectId: z.string(),
  25. }),
  26. params: z.object({
  27. project_id: z.string(),
  28. }),
  29. })
  30. export function cloneProject(req, res) {
  31. const {
  32. params: { project_id: sourceProjectId },
  33. body: { targetProjectId },
  34. } = parseReq(req, cloneProjectSchema)
  35. const incrResp = new IncrementalResponse({
  36. res,
  37. timeout: 10 * 60_000 - 5_000,
  38. logger,
  39. label: 'clone history in project-history',
  40. info: { targetProjectId, sourceProjectId },
  41. })
  42. incrResp.sendUpdate('best effort history flush: pending')
  43. UpdatesProcessor.processUpdatesForProject(sourceProjectId, err => {
  44. if (err) {
  45. logger.warn(
  46. { err, sourceProjectId },
  47. 'failed to flush during history clone'
  48. )
  49. incrResp.sendUpdate(
  50. 'best effort history flush: failed, a resync will be required'
  51. )
  52. } else {
  53. incrResp.sendUpdate('best effort history flush: done')
  54. }
  55. WebApiManager.getHistoryId(targetProjectId, (err, targetHistoryId) => {
  56. if (err) return incrResp.fail(OError.tag(err, 'get target historyId'))
  57. WebApiManager.getHistoryId(sourceProjectId, (err, sourceHistoryId) => {
  58. if (err) return incrResp.fail(OError.tag(err, 'get source historyId'))
  59. incrResp.sendUpdate('cloning full project history data: pending')
  60. HistoryStoreManager.cloneProject(
  61. sourceHistoryId.toString(),
  62. targetHistoryId.toString(),
  63. incrResp.signal(),
  64. (err, stream) => {
  65. if (err) {
  66. incrResp.fail(OError.tag(err, 'clone history-v1 data'))
  67. return
  68. }
  69. // aborted. pipeline() would throw.
  70. if (res.destroyed) {
  71. stream.destroy()
  72. incrResp.fail(new Error('request aborted'))
  73. return
  74. }
  75. // The stream.pipeline callback API does not support options.
  76. Stream.promises.pipeline(stream, res, { end: false }).then(
  77. () => {
  78. incrResp.sendUpdate('clone labels: pending')
  79. LabelsManager.cloneLabels(
  80. sourceProjectId,
  81. targetProjectId,
  82. err => {
  83. if (err) {
  84. incrResp.fail(OError.tag(err, 'clone labels'))
  85. return
  86. }
  87. incrResp.sendUpdate('clone labels: done')
  88. incrResp.sendUpdate('clone resync state: pending')
  89. SyncManager.cloneResyncState(
  90. sourceProjectId,
  91. targetProjectId,
  92. err => {
  93. if (err) {
  94. incrResp.fail(OError.tag(err, 'clone resync state'))
  95. return
  96. }
  97. incrResp.sendUpdate('clone resync state: done')
  98. incrResp.sendUpdate('clone failure record: pending')
  99. ErrorRecorder.cloneFailure(
  100. sourceProjectId,
  101. targetProjectId,
  102. err => {
  103. if (err) {
  104. incrResp.fail(OError.tag(err, 'clone failure'))
  105. return
  106. }
  107. incrResp.sendUpdate('clone failure record: done')
  108. incrResp.sendUpdate('done')
  109. incrResp.end()
  110. }
  111. )
  112. }
  113. )
  114. }
  115. )
  116. },
  117. err => {
  118. incrResp.fail(OError.tag(err, 'stream history-v1 response'))
  119. }
  120. )
  121. }
  122. )
  123. })
  124. })
  125. })
  126. }
  127. const getProjectBlobSchema = z.object({
  128. params: z.object({
  129. history_id: zz.objectId().or(z.coerce.number()),
  130. hash: z.string(),
  131. }),
  132. })
  133. export function getProjectBlob(req, res, next) {
  134. const { params } = parseReq(req, getProjectBlobSchema)
  135. const historyId = params.history_id
  136. const blobHash = params.hash
  137. HistoryStoreManager.getProjectBlobStream(
  138. historyId,
  139. blobHash,
  140. (err, stream) => {
  141. if (err != null) {
  142. if (err instanceof RequestFailedError && err.response.status === 404) {
  143. return res.status(404).end()
  144. }
  145. return next(OError.tag(err))
  146. }
  147. res.setHeader('Cache-Control', `private, max-age=${ONE_DAY_IN_SECONDS}`)
  148. pipeline(stream, res, err => {
  149. if (err) next(err)
  150. // res.end() is already called via 'end' event by pipeline.
  151. })
  152. }
  153. )
  154. }
  155. export function initializeProject(req, res, next) {
  156. const { historyId } = req.body
  157. HistoryStoreManager.initializeProject(historyId, (error, id) => {
  158. if (error != null) {
  159. return next(OError.tag(error))
  160. }
  161. res.json({ project: { id } })
  162. })
  163. }
  164. const flushProjectSchema = z.object({
  165. params: z.object({
  166. project_id: zz.objectId().or(z.coerce.number()),
  167. }),
  168. query: z.object({
  169. debug: z.stringbool().default(false),
  170. bisect: z.stringbool().default(false),
  171. }),
  172. })
  173. export function flushProject(req, res, next) {
  174. const { query, params } = parseReq(req, flushProjectSchema)
  175. const projectId = params.project_id
  176. if (query.debug) {
  177. logger.debug(
  178. { projectId },
  179. 'compressing project history in single-step mode'
  180. )
  181. UpdatesProcessor.processSingleUpdateForProject(projectId, error => {
  182. if (error != null) {
  183. return next(OError.tag(error))
  184. }
  185. res.sendStatus(204)
  186. })
  187. } else if (query.bisect) {
  188. logger.debug({ projectId }, 'compressing project history in bisect mode')
  189. UpdatesProcessor.processUpdatesForProjectUsingBisect(
  190. projectId,
  191. UpdatesProcessor.REDIS_READ_BATCH_SIZE,
  192. error => {
  193. if (error != null) {
  194. return next(OError.tag(error))
  195. }
  196. res.sendStatus(204)
  197. }
  198. )
  199. } else {
  200. logger.debug({ projectId }, 'compressing project history')
  201. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  202. if (error != null) {
  203. return next(OError.tag(error))
  204. }
  205. res.sendStatus(204)
  206. })
  207. }
  208. }
  209. const dumpProjectSchema = z.object({
  210. params: z.object({
  211. project_id: zz.objectId().or(z.coerce.number()),
  212. }),
  213. query: z.object({
  214. count: z.coerce.number().int().optional(),
  215. }),
  216. })
  217. export function dumpProject(req, res, next) {
  218. const { query, params } = parseReq(req, dumpProjectSchema)
  219. const projectId = params.project_id
  220. const batchSize = query.count || UpdatesProcessor.REDIS_READ_BATCH_SIZE
  221. logger.debug({ projectId }, 'retrieving raw updates')
  222. UpdatesProcessor.getRawUpdates(projectId, batchSize, (error, rawUpdates) => {
  223. if (error != null) {
  224. return next(OError.tag(error))
  225. }
  226. res.json(rawUpdates)
  227. })
  228. }
  229. const flushOldSchema = z.object({
  230. query: z.object({
  231. // flush projects with queued ops older than this
  232. maxAge: z.coerce
  233. .number()
  234. .int()
  235. .default(6 * 3600),
  236. // pause this amount of time between checking queues
  237. queueDelay: z.coerce.number().int().default(100),
  238. // maximum number of queues to check
  239. limit: z.coerce.number().int().default(1000),
  240. // maximum amount of time allowed
  241. timeout: z.coerce
  242. .number()
  243. .int()
  244. .default(60 * 1000),
  245. // whether to run in the background
  246. background: z.stringbool().default(false),
  247. }),
  248. })
  249. export function flushOld(req, res, next) {
  250. const { query } = parseReq(req, flushOldSchema)
  251. const { maxAge, queueDelay, limit, timeout, background } = query
  252. const options = { maxAge, queueDelay, limit, timeout, background }
  253. FlushManager.flushOldOps(options, (error, results) => {
  254. if (error != null) {
  255. return next(OError.tag(error))
  256. }
  257. res.send(results)
  258. })
  259. }
  260. const getDiffSchema = z.object({
  261. params: z.object({
  262. project_id: zz.objectId().or(z.coerce.number()),
  263. }),
  264. query: z.object({
  265. pathname: z.string(),
  266. from: z.coerce.number().int(),
  267. to: z.coerce.number().int(),
  268. }),
  269. })
  270. export function getDiff(req, res, next) {
  271. const { query, params } = parseReq(req, getDiffSchema)
  272. const { pathname, from, to } = query
  273. const projectId = params.project_id
  274. logger.debug({ projectId, pathname, from, to }, 'getting diff')
  275. DiffManager.getDiff(projectId, pathname, from, to, (error, diff) => {
  276. if (error != null) {
  277. return next(OError.tag(error))
  278. }
  279. res.json({ diff })
  280. })
  281. }
  282. const getFileTreeDiffSchema = z.object({
  283. params: z.object({
  284. project_id: zz.objectId().or(z.coerce.number()),
  285. }),
  286. query: z.object({
  287. from: z.coerce.number().int(),
  288. to: z.coerce.number().int(),
  289. }),
  290. })
  291. export function getFileTreeDiff(req, res, next) {
  292. const { query, params } = parseReq(req, getFileTreeDiffSchema)
  293. const { from, to } = query
  294. const projectId = params.project_id
  295. DiffManager.getFileTreeDiff(projectId, from, to, (error, diff) => {
  296. if (error != null) {
  297. return next(OError.tag(error))
  298. }
  299. res.json({ diff })
  300. })
  301. }
  302. const getUpdatesSchema = z.object({
  303. params: z.object({
  304. project_id: zz.objectId().or(z.coerce.number()),
  305. }),
  306. query: z.object({
  307. before: z.coerce.number().int().optional(),
  308. min_count: z.coerce.number().int().optional(),
  309. }),
  310. })
  311. export function getUpdates(req, res, next) {
  312. const { query, params } = parseReq(req, getUpdatesSchema)
  313. const projectId = params.project_id
  314. const { before, min_count: minCount } = query
  315. SummarizedUpdatesManager.getSummarizedProjectUpdates(
  316. projectId,
  317. { before, min_count: minCount },
  318. (error, updates, nextBeforeTimestamp) => {
  319. if (error != null) {
  320. return next(OError.tag(error))
  321. }
  322. for (const update of updates) {
  323. // Sets don't JSONify, so convert to arrays
  324. update.pathnames = Array.from(update.pathnames || []).sort()
  325. }
  326. res.json({
  327. updates,
  328. nextBeforeTimestamp,
  329. })
  330. }
  331. )
  332. }
  333. const getResyncPendingSchema = z.object({
  334. params: z.object({
  335. project_id: zz.objectId(),
  336. }),
  337. })
  338. export function getResyncPending(req, res, next) {
  339. const {
  340. params: { project_id: projectId },
  341. } = parseReq(req, getResyncPendingSchema)
  342. SyncManager.getResyncState(projectId, (err, state) => {
  343. if (err) return next(err)
  344. res.json({
  345. resyncPending: state.isSyncOngoing(),
  346. syncStuck: state.isSyncStuck(),
  347. })
  348. })
  349. }
  350. const getDebugInfoSchema = z.object({
  351. params: z.object({
  352. project_id: zz.objectId(),
  353. }),
  354. })
  355. export function getDebugInfo(req, res, next) {
  356. const {
  357. params: { project_id: projectId },
  358. } = parseReq(req, getDebugInfoSchema)
  359. SyncManager.getResyncState(projectId, (err, state) => {
  360. if (err) return next(err)
  361. ErrorRecorder.getFailureRecord(projectId, (err, failureRecord) => {
  362. if (err) return next(err)
  363. res.json({
  364. failureRecord,
  365. syncState: {
  366. resyncPending: state.isSyncOngoing(),
  367. resyncCount: state.resyncCount,
  368. resyncPendingSince: state.resyncPendingSince,
  369. lastUpdated: state.lastUpdated,
  370. history: state.history,
  371. ...state.toRaw(),
  372. },
  373. })
  374. })
  375. })
  376. }
  377. const latestVersionSchema = z.object({
  378. params: z.object({
  379. project_id: zz.objectId().or(z.coerce.number()),
  380. }),
  381. })
  382. export function latestVersion(req, res, next) {
  383. const { params } = parseReq(req, latestVersionSchema)
  384. const projectId = params.project_id
  385. logger.debug({ projectId }, 'compressing project history and getting version')
  386. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  387. if (error != null) {
  388. return next(OError.tag(error))
  389. }
  390. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  391. if (error != null) {
  392. return next(OError.tag(error))
  393. }
  394. HistoryStoreManager.getMostRecentVersion(
  395. projectId,
  396. historyId,
  397. (error, version, projectStructureAndDocVersions, lastChange) => {
  398. if (error != null) {
  399. return next(OError.tag(error))
  400. }
  401. res.json({
  402. version,
  403. timestamp: lastChange != null ? lastChange.timestamp : undefined,
  404. v2Authors: lastChange != null ? lastChange.v2Authors : undefined,
  405. })
  406. }
  407. )
  408. })
  409. })
  410. }
  411. const getFileSnapshotSchema = z.object({
  412. params: z.object({
  413. project_id: zz.objectId().or(z.coerce.number()),
  414. version: z.coerce.number().int(),
  415. pathname: z.string(),
  416. }),
  417. })
  418. export function getFileSnapshot(req, res, next) {
  419. const { params } = parseReq(req, getFileSnapshotSchema)
  420. const { project_id: projectId, version, pathname } = params
  421. SnapshotManager.getFileSnapshotStream(
  422. projectId,
  423. version,
  424. pathname,
  425. (error, stream) => {
  426. if (error != null) {
  427. return next(OError.tag(error))
  428. }
  429. pipeline(stream, res, err => {
  430. if (err) next(err)
  431. // res.end() is already called via 'end' event by pipeline.
  432. })
  433. }
  434. )
  435. }
  436. const getRangesSnapshotSchema = z.object({
  437. params: z.object({
  438. project_id: zz.objectId().or(z.coerce.number()),
  439. version: z.coerce.number().int(),
  440. pathname: z.string(),
  441. }),
  442. })
  443. export function getRangesSnapshot(req, res, next) {
  444. const { params } = parseReq(req, getRangesSnapshotSchema)
  445. const { project_id: projectId, version, pathname } = params
  446. SnapshotManager.getRangesSnapshot(
  447. projectId,
  448. version,
  449. pathname,
  450. (err, ranges) => {
  451. if (err) {
  452. return next(OError.tag(err))
  453. }
  454. res.json(ranges)
  455. }
  456. )
  457. }
  458. const getFileMetadataSnapshotSchema = z.object({
  459. params: z.object({
  460. project_id: zz.objectId().or(z.coerce.number()),
  461. version: z.coerce.number().int(),
  462. pathname: z.string(),
  463. }),
  464. })
  465. export function getFileMetadataSnapshot(req, res, next) {
  466. const { params } = parseReq(req, getFileMetadataSnapshotSchema)
  467. const { project_id: projectId, version, pathname } = params
  468. SnapshotManager.getFileMetadataSnapshot(
  469. projectId,
  470. version,
  471. pathname,
  472. (err, data) => {
  473. if (err) {
  474. return next(OError.tag(err))
  475. }
  476. res.json(data)
  477. }
  478. )
  479. }
  480. const getLatestSnapshotSchema = z.object({
  481. params: z.object({
  482. project_id: zz.objectId().or(z.coerce.number()),
  483. }),
  484. })
  485. export function getLatestSnapshot(req, res, next) {
  486. const { params } = parseReq(req, getLatestSnapshotSchema)
  487. const { project_id: projectId } = params
  488. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  489. if (error) return next(OError.tag(error))
  490. SnapshotManager.getLatestSnapshot(
  491. projectId,
  492. historyId,
  493. (error, details) => {
  494. if (error != null) {
  495. return next(error)
  496. }
  497. const { snapshot, version } = details
  498. res.json({ snapshot: snapshot.toRaw(), version })
  499. }
  500. )
  501. })
  502. }
  503. const getChangesInChunkSinceSchema = z.object({
  504. params: z.object({
  505. project_id: zz.objectId().or(z.coerce.number()),
  506. }),
  507. query: z.object({
  508. since: z.coerce.number().int().min(0),
  509. }),
  510. })
  511. export function getChangesInChunkSince(req, res, next) {
  512. const { query, params } = parseReq(req, getChangesInChunkSinceSchema)
  513. const { project_id: projectId } = params
  514. const { since } = query
  515. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  516. if (error) return next(OError.tag(error))
  517. SnapshotManager.getChangesInChunkSince(
  518. projectId,
  519. historyId,
  520. since,
  521. (error, details) => {
  522. if (error != null) {
  523. return next(error)
  524. }
  525. const { latestStartVersion, changes } = details
  526. res.json({
  527. latestStartVersion,
  528. changes: changes.map(c => c.toRaw()),
  529. })
  530. }
  531. )
  532. })
  533. }
  534. const getProjectSnapshotSchema = z.object({
  535. params: z.object({
  536. project_id: zz.objectId().or(z.coerce.number()),
  537. version: z.coerce.number().int(),
  538. }),
  539. })
  540. export function getProjectSnapshot(req, res, next) {
  541. const { params } = parseReq(req, getProjectSnapshotSchema)
  542. const { project_id: projectId, version } = params
  543. SnapshotManager.getProjectSnapshot(
  544. projectId,
  545. version,
  546. (error, snapshotData) => {
  547. if (error != null) {
  548. return next(error)
  549. }
  550. res.json(snapshotData)
  551. }
  552. )
  553. }
  554. const getPathsAtVersionSchema = z.object({
  555. params: z.object({
  556. project_id: zz.objectId().or(z.coerce.number()),
  557. version: z.coerce.number().int(),
  558. }),
  559. })
  560. export function getPathsAtVersion(req, res, next) {
  561. const { params } = parseReq(req, getPathsAtVersionSchema)
  562. const { project_id: projectId, version } = params
  563. SnapshotManager.getPathsAtVersion(projectId, version, (error, result) => {
  564. if (error != null) {
  565. return next(error)
  566. }
  567. res.json(result)
  568. })
  569. }
  570. export function healthCheck(req, res) {
  571. HealthChecker.check(err => {
  572. if (err != null) {
  573. logger.err({ err }, 'error performing health check')
  574. res.sendStatus(500)
  575. } else {
  576. res.sendStatus(200)
  577. }
  578. })
  579. }
  580. export function checkLock(req, res) {
  581. HealthChecker.checkLock(err => {
  582. if (err != null) {
  583. logger.err({ err }, 'error performing lock check')
  584. res.sendStatus(500)
  585. } else {
  586. res.sendStatus(200)
  587. }
  588. })
  589. }
  590. const resyncProjectSchema = z.object({
  591. params: z.object({
  592. project_id: zz.objectId().or(z.coerce.number()),
  593. }),
  594. query: z.object({
  595. force: z.stringbool().default(false),
  596. }),
  597. body: z.object({
  598. force: z.boolean().default(false),
  599. origin: z
  600. .object({
  601. kind: z.string(),
  602. })
  603. .optional(),
  604. historyRangesMigration: z.enum(['forwards', 'backwards']).optional(),
  605. }),
  606. })
  607. export function resyncProject(req, res, next) {
  608. const { query, params, body } = parseReq(req, resyncProjectSchema)
  609. const projectId = params.project_id
  610. const options = {}
  611. if (body.origin) {
  612. options.origin = body.origin
  613. }
  614. if (body.historyRangesMigration) {
  615. options.historyRangesMigration = body.historyRangesMigration
  616. }
  617. if (query.force || body.force) {
  618. // this will delete the queue and clear the sync state
  619. // use if the project is completely broken
  620. SyncManager.startHardResync(projectId, options, error => {
  621. if (error != null) {
  622. return next(error)
  623. }
  624. // flush the sync operations
  625. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  626. if (error != null) {
  627. return next(error)
  628. }
  629. res.sendStatus(204)
  630. })
  631. })
  632. } else {
  633. SyncManager.startResync(projectId, options, error => {
  634. if (error != null) {
  635. return next(error)
  636. }
  637. // flush the sync operations
  638. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  639. if (error != null) {
  640. return next(error)
  641. }
  642. res.sendStatus(204)
  643. })
  644. })
  645. }
  646. }
  647. const forceDebugProjectSchema = z.object({
  648. params: z.object({
  649. project_id: zz.objectId().or(z.coerce.number()),
  650. }),
  651. query: z.object({
  652. clear: z.stringbool().default(false),
  653. }),
  654. })
  655. export function forceDebugProject(req, res, next) {
  656. const { query, params } = parseReq(req, forceDebugProjectSchema)
  657. const projectId = params.project_id
  658. // set the debug flag to true unless we see ?clear=true
  659. const state = !query.clear
  660. ErrorRecorder.setForceDebug(projectId, state, error => {
  661. if (error != null) {
  662. return next(error)
  663. }
  664. // display the failure record to help debugging
  665. ErrorRecorder.getFailureRecord(projectId, (error, result) => {
  666. if (error != null) {
  667. return next(error)
  668. }
  669. res.send(result)
  670. })
  671. })
  672. }
  673. export function getFailures(req, res, next) {
  674. ErrorRecorder.getFailures((error, result) => {
  675. if (error != null) {
  676. return next(error)
  677. }
  678. res.send({ failures: result })
  679. })
  680. }
  681. export function getFailuresFull(req, res, next) {
  682. ErrorRecorder.getFailuresFull((error, result) => {
  683. if (error) return next(error)
  684. res.send(result)
  685. })
  686. }
  687. export function getQueueCounts(req, res, next) {
  688. RedisManager.getProjectIdsWithHistoryOpsCount((err, queuedProjectsCount) => {
  689. if (err != null) {
  690. return next(err)
  691. }
  692. res.send({ queuedProjects: queuedProjectsCount })
  693. })
  694. }
  695. const getLabelsSchema = z.object({
  696. params: z.object({
  697. project_id: zz.objectId().or(z.coerce.number()),
  698. }),
  699. })
  700. export function getLabels(req, res, next) {
  701. const { params } = parseReq(req, getLabelsSchema)
  702. const projectId = params.project_id
  703. HistoryApiManager.shouldUseProjectHistory(
  704. projectId,
  705. (error, shouldUseProjectHistory) => {
  706. if (error != null) {
  707. return next(error)
  708. }
  709. if (shouldUseProjectHistory) {
  710. LabelsManager.getLabels(projectId, (error, labels) => {
  711. if (error != null) {
  712. return next(error)
  713. }
  714. res.json(labels)
  715. })
  716. } else {
  717. res.sendStatus(409)
  718. }
  719. }
  720. )
  721. }
  722. const createLabelSchema = z.object({
  723. params: z.object({
  724. project_id: zz.objectId().or(z.coerce.number()),
  725. user_id: zz.objectId().optional(),
  726. }),
  727. body: z.object({
  728. version: z.number().int(),
  729. comment: z.string(),
  730. created_at: z.string().optional(),
  731. validate_exists: z.boolean().default(true),
  732. user_id: zz.objectId().nullable().optional(),
  733. }),
  734. })
  735. export function createLabel(req, res, next) {
  736. const { params, body } = parseReq(req, createLabelSchema)
  737. const { project_id: projectId, user_id: userIdParam } = params
  738. const {
  739. version,
  740. comment,
  741. user_id: userIdBody,
  742. created_at: createdAt,
  743. validate_exists: validateExists,
  744. } = body
  745. // Temporarily looking up both params and body while rolling out changes
  746. // in the router path - https://github.com/overleaf/internal/pull/20200
  747. const userId = userIdParam || userIdBody
  748. HistoryApiManager.shouldUseProjectHistory(
  749. projectId,
  750. (error, shouldUseProjectHistory) => {
  751. if (error != null) {
  752. return next(error)
  753. }
  754. if (shouldUseProjectHistory) {
  755. LabelsManager.createLabel(
  756. projectId,
  757. userId,
  758. version,
  759. comment,
  760. createdAt,
  761. validateExists,
  762. (error, label) => {
  763. if (error != null) {
  764. return next(error)
  765. }
  766. res.json(label)
  767. }
  768. )
  769. } else {
  770. logger.error(
  771. {
  772. projectId,
  773. userId,
  774. version,
  775. comment,
  776. createdAt,
  777. validateExists,
  778. },
  779. 'not using v2 history'
  780. )
  781. res.sendStatus(409)
  782. }
  783. }
  784. )
  785. }
  786. /**
  787. * This will delete a label if it is owned by the current user. If you wish to
  788. * delete a label regardless of the current user, then use `deleteLabel` instead.
  789. */
  790. const deleteLabelForUserSchema = z.object({
  791. params: z.object({
  792. project_id: zz.objectId().or(z.coerce.number()),
  793. user_id: zz.objectId(),
  794. label_id: zz.objectId(),
  795. }),
  796. })
  797. export function deleteLabelForUser(req, res, next) {
  798. const { params } = parseReq(req, deleteLabelForUserSchema)
  799. const { project_id: projectId, user_id: userId, label_id: labelId } = params
  800. LabelsManager.deleteLabelForUser(projectId, userId, labelId, error => {
  801. if (error != null) {
  802. return next(error)
  803. }
  804. res.sendStatus(204)
  805. })
  806. }
  807. const deleteLabelSchema = z.object({
  808. params: z.object({
  809. project_id: zz.objectId().or(z.coerce.number()),
  810. label_id: zz.objectId(),
  811. }),
  812. })
  813. export function deleteLabel(req, res, next) {
  814. const { params } = parseReq(req, deleteLabelSchema)
  815. const { project_id: projectId, label_id: labelId } = params
  816. LabelsManager.deleteLabel(projectId, labelId, error => {
  817. if (error != null) {
  818. return next(error)
  819. }
  820. res.sendStatus(204)
  821. })
  822. }
  823. const retryFailuresSchema = z.object({
  824. query: z.object({
  825. failureType: z.enum(['soft', 'hard']).optional(),
  826. // bail out after this time limit
  827. timeout: z.coerce.number().int().default(300),
  828. // maximum number of projects to check
  829. limit: z.coerce.number().int().default(100),
  830. callbackUrl: z.string().optional(),
  831. }),
  832. })
  833. export function retryFailures(req, res, next) {
  834. const { query } = parseReq(req, retryFailuresSchema)
  835. const { failureType, timeout, limit, callbackUrl } = query
  836. if (callbackUrl) {
  837. // send response but run in background when callbackUrl provided
  838. res.send({ retryStatus: 'running retryFailures in background' })
  839. }
  840. RetryManager.retryFailures(
  841. { failureType, timeout, limit },
  842. (error, result) => {
  843. if (callbackUrl) {
  844. // if present, notify the callbackUrl on success
  845. if (!error) {
  846. // Needs Node 12
  847. // const callbackHeaders = Object.fromEntries(Object.entries(req.headers || {}).filter(([k,v]) => k.match(/^X-CALLBACK-/i)))
  848. const callbackHeaders = {}
  849. for (const key of Object.getOwnPropertyNames(
  850. req.headers || {}
  851. ).filter(key => key.match(/^X-CALLBACK-/i))) {
  852. const found = key.match(/^X-CALLBACK-(.*)/i)
  853. callbackHeaders[found[1]] = req.headers[key]
  854. }
  855. fetchNothing(callbackUrl, { headers: callbackHeaders }).catch(err => {
  856. logger.warn({ err }, 'failed to ping callback url')
  857. })
  858. }
  859. } else {
  860. if (error != null) {
  861. return next(error)
  862. }
  863. res.send({ retryStatus: result })
  864. }
  865. }
  866. )
  867. }
  868. const transferLabelsSchema = z.object({
  869. params: z.object({
  870. from_user: zz.objectId(),
  871. to_user: zz.objectId(),
  872. }),
  873. })
  874. export function transferLabels(req, res, next) {
  875. const { params } = parseReq(req, transferLabelsSchema)
  876. const { from_user: fromUser, to_user: toUser } = params
  877. LabelsManager.transferLabels(fromUser, toUser, error => {
  878. if (error != null) {
  879. return next(error)
  880. }
  881. res.sendStatus(204)
  882. })
  883. }
  884. const deleteProjectSchema = z.object({
  885. params: z.object({
  886. project_id: zz.objectId().or(z.coerce.number()),
  887. }),
  888. })
  889. export function deleteProject(req, res, next) {
  890. const { params } = parseReq(req, deleteProjectSchema)
  891. const { project_id: projectId } = params
  892. // clear the timestamp before clearing the queue,
  893. // because the queue location is used in the migration
  894. RedisManager.clearFirstOpTimestamp(projectId, err => {
  895. if (err) {
  896. return next(err)
  897. }
  898. RedisManager.clearCachedHistoryId(projectId, err => {
  899. if (err) {
  900. return next(err)
  901. }
  902. RedisManager.destroyDocUpdatesQueue(projectId, err => {
  903. if (err) {
  904. return next(err)
  905. }
  906. SyncManager.clearResyncState(projectId, err => {
  907. if (err) {
  908. return next(err)
  909. }
  910. ErrorRecorder.clearError(projectId, err => {
  911. if (err) {
  912. return next(err)
  913. }
  914. res.sendStatus(204)
  915. })
  916. })
  917. })
  918. })
  919. })
  920. }