HttpController.js 23 KB

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