HttpController.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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 getDebugInfoSchema = z.object({
  245. params: z.object({
  246. project_id: zz.objectId(),
  247. }),
  248. })
  249. export function getDebugInfo(req, res, next) {
  250. const {
  251. params: { project_id: projectId },
  252. } = parseReq(req, getDebugInfoSchema)
  253. SyncManager.getResyncState(projectId, (err, state) => {
  254. if (err) return next(err)
  255. ErrorRecorder.getFailureRecord(projectId, (err, failureRecord) => {
  256. if (err) return next(err)
  257. res.json({
  258. failureRecord,
  259. syncState: {
  260. resyncPending: state.isSyncOngoing(),
  261. resyncCount: state.resyncCount,
  262. resyncPendingSince: state.resyncPendingSince,
  263. lastUpdated: state.lastUpdated,
  264. history: state.history,
  265. ...state.toRaw(),
  266. },
  267. })
  268. })
  269. })
  270. }
  271. const latestVersionSchema = z.object({
  272. params: z.object({
  273. project_id: zz.objectId().or(z.coerce.number()),
  274. }),
  275. })
  276. export function latestVersion(req, res, next) {
  277. const { params } = parseReq(req, latestVersionSchema)
  278. const projectId = params.project_id
  279. logger.debug({ projectId }, 'compressing project history and getting version')
  280. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  281. if (error != null) {
  282. return next(OError.tag(error))
  283. }
  284. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  285. if (error != null) {
  286. return next(OError.tag(error))
  287. }
  288. HistoryStoreManager.getMostRecentVersion(
  289. projectId,
  290. historyId,
  291. (error, version, projectStructureAndDocVersions, lastChange) => {
  292. if (error != null) {
  293. return next(OError.tag(error))
  294. }
  295. res.json({
  296. version,
  297. timestamp: lastChange != null ? lastChange.timestamp : undefined,
  298. v2Authors: lastChange != null ? lastChange.v2Authors : undefined,
  299. })
  300. }
  301. )
  302. })
  303. })
  304. }
  305. const getFileSnapshotSchema = z.object({
  306. params: z.object({
  307. project_id: zz.objectId().or(z.coerce.number()),
  308. version: z.coerce.number().int(),
  309. pathname: z.string(),
  310. }),
  311. })
  312. export function getFileSnapshot(req, res, next) {
  313. const { params } = parseReq(req, getFileSnapshotSchema)
  314. const { project_id: projectId, version, pathname } = params
  315. SnapshotManager.getFileSnapshotStream(
  316. projectId,
  317. version,
  318. pathname,
  319. (error, stream) => {
  320. if (error != null) {
  321. return next(OError.tag(error))
  322. }
  323. pipeline(stream, res, err => {
  324. if (err) next(err)
  325. // res.end() is already called via 'end' event by pipeline.
  326. })
  327. }
  328. )
  329. }
  330. const getRangesSnapshotSchema = z.object({
  331. params: z.object({
  332. project_id: zz.objectId().or(z.coerce.number()),
  333. version: z.coerce.number().int(),
  334. pathname: z.string(),
  335. }),
  336. })
  337. export function getRangesSnapshot(req, res, next) {
  338. const { params } = parseReq(req, getRangesSnapshotSchema)
  339. const { project_id: projectId, version, pathname } = params
  340. SnapshotManager.getRangesSnapshot(
  341. projectId,
  342. version,
  343. pathname,
  344. (err, ranges) => {
  345. if (err) {
  346. return next(OError.tag(err))
  347. }
  348. res.json(ranges)
  349. }
  350. )
  351. }
  352. const getFileMetadataSnapshotSchema = z.object({
  353. params: z.object({
  354. project_id: zz.objectId().or(z.coerce.number()),
  355. version: z.coerce.number().int(),
  356. pathname: z.string(),
  357. }),
  358. })
  359. export function getFileMetadataSnapshot(req, res, next) {
  360. const { params } = parseReq(req, getFileMetadataSnapshotSchema)
  361. const { project_id: projectId, version, pathname } = params
  362. SnapshotManager.getFileMetadataSnapshot(
  363. projectId,
  364. version,
  365. pathname,
  366. (err, data) => {
  367. if (err) {
  368. return next(OError.tag(err))
  369. }
  370. res.json(data)
  371. }
  372. )
  373. }
  374. const getLatestSnapshotSchema = z.object({
  375. params: z.object({
  376. project_id: zz.objectId().or(z.coerce.number()),
  377. }),
  378. })
  379. export function getLatestSnapshot(req, res, next) {
  380. const { params } = parseReq(req, getLatestSnapshotSchema)
  381. const { project_id: projectId } = params
  382. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  383. if (error) return next(OError.tag(error))
  384. SnapshotManager.getLatestSnapshot(
  385. projectId,
  386. historyId,
  387. (error, details) => {
  388. if (error != null) {
  389. return next(error)
  390. }
  391. const { snapshot, version } = details
  392. res.json({ snapshot: snapshot.toRaw(), version })
  393. }
  394. )
  395. })
  396. }
  397. const getChangesInChunkSinceSchema = z.object({
  398. params: z.object({
  399. project_id: zz.objectId().or(z.coerce.number()),
  400. }),
  401. query: z.object({
  402. since: z.coerce.number().int().min(0),
  403. }),
  404. })
  405. export function getChangesInChunkSince(req, res, next) {
  406. const { query, params } = parseReq(req, getChangesInChunkSinceSchema)
  407. const { project_id: projectId } = params
  408. const { since } = query
  409. WebApiManager.getHistoryId(projectId, (error, historyId) => {
  410. if (error) return next(OError.tag(error))
  411. SnapshotManager.getChangesInChunkSince(
  412. projectId,
  413. historyId,
  414. since,
  415. (error, details) => {
  416. if (error != null) {
  417. return next(error)
  418. }
  419. const { latestStartVersion, changes } = details
  420. res.json({
  421. latestStartVersion,
  422. changes: changes.map(c => c.toRaw()),
  423. })
  424. }
  425. )
  426. })
  427. }
  428. const getProjectSnapshotSchema = z.object({
  429. params: z.object({
  430. project_id: zz.objectId().or(z.coerce.number()),
  431. version: z.coerce.number().int(),
  432. }),
  433. })
  434. export function getProjectSnapshot(req, res, next) {
  435. const { params } = parseReq(req, getProjectSnapshotSchema)
  436. const { project_id: projectId, version } = params
  437. SnapshotManager.getProjectSnapshot(
  438. projectId,
  439. version,
  440. (error, snapshotData) => {
  441. if (error != null) {
  442. return next(error)
  443. }
  444. res.json(snapshotData)
  445. }
  446. )
  447. }
  448. const getPathsAtVersionSchema = z.object({
  449. params: z.object({
  450. project_id: zz.objectId().or(z.coerce.number()),
  451. version: z.coerce.number().int(),
  452. }),
  453. })
  454. export function getPathsAtVersion(req, res, next) {
  455. const { params } = parseReq(req, getPathsAtVersionSchema)
  456. const { project_id: projectId, version } = params
  457. SnapshotManager.getPathsAtVersion(projectId, version, (error, result) => {
  458. if (error != null) {
  459. return next(error)
  460. }
  461. res.json(result)
  462. })
  463. }
  464. export function healthCheck(req, res) {
  465. HealthChecker.check(err => {
  466. if (err != null) {
  467. logger.err({ err }, 'error performing health check')
  468. res.sendStatus(500)
  469. } else {
  470. res.sendStatus(200)
  471. }
  472. })
  473. }
  474. export function checkLock(req, res) {
  475. HealthChecker.checkLock(err => {
  476. if (err != null) {
  477. logger.err({ err }, 'error performing lock check')
  478. res.sendStatus(500)
  479. } else {
  480. res.sendStatus(200)
  481. }
  482. })
  483. }
  484. const resyncProjectSchema = z.object({
  485. params: z.object({
  486. project_id: zz.objectId().or(z.coerce.number()),
  487. }),
  488. query: z.object({
  489. force: z.stringbool().default(false),
  490. }),
  491. body: z.object({
  492. force: z.boolean().default(false),
  493. origin: z
  494. .object({
  495. kind: z.string(),
  496. })
  497. .optional(),
  498. historyRangesMigration: z.enum(['forwards', 'backwards']).optional(),
  499. }),
  500. })
  501. export function resyncProject(req, res, next) {
  502. const { query, params, body } = parseReq(req, resyncProjectSchema)
  503. const projectId = params.project_id
  504. const options = {}
  505. if (body.origin) {
  506. options.origin = body.origin
  507. }
  508. if (body.historyRangesMigration) {
  509. options.historyRangesMigration = body.historyRangesMigration
  510. }
  511. if (query.force || body.force) {
  512. // this will delete the queue and clear the sync state
  513. // use if the project is completely broken
  514. SyncManager.startHardResync(projectId, options, error => {
  515. if (error != null) {
  516. return next(error)
  517. }
  518. // flush the sync operations
  519. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  520. if (error != null) {
  521. return next(error)
  522. }
  523. res.sendStatus(204)
  524. })
  525. })
  526. } else {
  527. SyncManager.startResync(projectId, options, error => {
  528. if (error != null) {
  529. return next(error)
  530. }
  531. // flush the sync operations
  532. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  533. if (error != null) {
  534. return next(error)
  535. }
  536. res.sendStatus(204)
  537. })
  538. })
  539. }
  540. }
  541. const forceDebugProjectSchema = z.object({
  542. params: z.object({
  543. project_id: zz.objectId().or(z.coerce.number()),
  544. }),
  545. query: z.object({
  546. clear: z.stringbool().default(false),
  547. }),
  548. })
  549. export function forceDebugProject(req, res, next) {
  550. const { query, params } = parseReq(req, forceDebugProjectSchema)
  551. const projectId = params.project_id
  552. // set the debug flag to true unless we see ?clear=true
  553. const state = !query.clear
  554. ErrorRecorder.setForceDebug(projectId, state, error => {
  555. if (error != null) {
  556. return next(error)
  557. }
  558. // display the failure record to help debugging
  559. ErrorRecorder.getFailureRecord(projectId, (error, result) => {
  560. if (error != null) {
  561. return next(error)
  562. }
  563. res.send(result)
  564. })
  565. })
  566. }
  567. export function getFailures(req, res, next) {
  568. ErrorRecorder.getFailures((error, result) => {
  569. if (error != null) {
  570. return next(error)
  571. }
  572. res.send({ failures: result })
  573. })
  574. }
  575. export function getQueueCounts(req, res, next) {
  576. RedisManager.getProjectIdsWithHistoryOpsCount((err, queuedProjectsCount) => {
  577. if (err != null) {
  578. return next(err)
  579. }
  580. res.send({ queuedProjects: queuedProjectsCount })
  581. })
  582. }
  583. const getLabelsSchema = z.object({
  584. params: z.object({
  585. project_id: zz.objectId().or(z.coerce.number()),
  586. }),
  587. })
  588. export function getLabels(req, res, next) {
  589. const { params } = parseReq(req, getLabelsSchema)
  590. const projectId = params.project_id
  591. HistoryApiManager.shouldUseProjectHistory(
  592. projectId,
  593. (error, shouldUseProjectHistory) => {
  594. if (error != null) {
  595. return next(error)
  596. }
  597. if (shouldUseProjectHistory) {
  598. LabelsManager.getLabels(projectId, (error, labels) => {
  599. if (error != null) {
  600. return next(error)
  601. }
  602. res.json(labels)
  603. })
  604. } else {
  605. res.sendStatus(409)
  606. }
  607. }
  608. )
  609. }
  610. const createLabelSchema = z.object({
  611. params: z.object({
  612. project_id: zz.objectId().or(z.coerce.number()),
  613. user_id: zz.objectId().optional(),
  614. }),
  615. body: z.object({
  616. version: z.number().int(),
  617. comment: z.string(),
  618. created_at: z.string().optional(),
  619. validate_exists: z.boolean().default(true),
  620. user_id: zz.objectId().nullable().optional(),
  621. }),
  622. })
  623. export function createLabel(req, res, next) {
  624. const { params, body } = parseReq(req, createLabelSchema)
  625. const { project_id: projectId, user_id: userIdParam } = params
  626. const {
  627. version,
  628. comment,
  629. user_id: userIdBody,
  630. created_at: createdAt,
  631. validate_exists: validateExists,
  632. } = body
  633. // Temporarily looking up both params and body while rolling out changes
  634. // in the router path - https://github.com/overleaf/internal/pull/20200
  635. const userId = userIdParam || userIdBody
  636. HistoryApiManager.shouldUseProjectHistory(
  637. projectId,
  638. (error, shouldUseProjectHistory) => {
  639. if (error != null) {
  640. return next(error)
  641. }
  642. if (shouldUseProjectHistory) {
  643. LabelsManager.createLabel(
  644. projectId,
  645. userId,
  646. version,
  647. comment,
  648. createdAt,
  649. validateExists,
  650. (error, label) => {
  651. if (error != null) {
  652. return next(error)
  653. }
  654. res.json(label)
  655. }
  656. )
  657. } else {
  658. logger.error(
  659. {
  660. projectId,
  661. userId,
  662. version,
  663. comment,
  664. createdAt,
  665. validateExists,
  666. },
  667. 'not using v2 history'
  668. )
  669. res.sendStatus(409)
  670. }
  671. }
  672. )
  673. }
  674. /**
  675. * This will delete a label if it is owned by the current user. If you wish to
  676. * delete a label regardless of the current user, then use `deleteLabel` instead.
  677. */
  678. const deleteLabelForUserSchema = z.object({
  679. params: z.object({
  680. project_id: zz.objectId().or(z.coerce.number()),
  681. user_id: zz.objectId(),
  682. label_id: zz.objectId(),
  683. }),
  684. })
  685. export function deleteLabelForUser(req, res, next) {
  686. const { params } = parseReq(req, deleteLabelForUserSchema)
  687. const { project_id: projectId, user_id: userId, label_id: labelId } = params
  688. LabelsManager.deleteLabelForUser(projectId, userId, labelId, error => {
  689. if (error != null) {
  690. return next(error)
  691. }
  692. res.sendStatus(204)
  693. })
  694. }
  695. const deleteLabelSchema = z.object({
  696. params: z.object({
  697. project_id: zz.objectId().or(z.coerce.number()),
  698. label_id: zz.objectId(),
  699. }),
  700. })
  701. export function deleteLabel(req, res, next) {
  702. const { params } = parseReq(req, deleteLabelSchema)
  703. const { project_id: projectId, label_id: labelId } = params
  704. LabelsManager.deleteLabel(projectId, labelId, error => {
  705. if (error != null) {
  706. return next(error)
  707. }
  708. res.sendStatus(204)
  709. })
  710. }
  711. const retryFailuresSchema = z.object({
  712. query: z.object({
  713. failureType: z.enum(['soft', 'hard']).optional(),
  714. // bail out after this time limit
  715. timeout: z.coerce.number().int().default(300),
  716. // maximum number of projects to check
  717. limit: z.coerce.number().int().default(100),
  718. callbackUrl: z.string().optional(),
  719. }),
  720. })
  721. export function retryFailures(req, res, next) {
  722. const { query } = parseReq(req, retryFailuresSchema)
  723. const { failureType, timeout, limit, callbackUrl } = query
  724. if (callbackUrl) {
  725. // send response but run in background when callbackUrl provided
  726. res.send({ retryStatus: 'running retryFailures in background' })
  727. }
  728. RetryManager.retryFailures(
  729. { failureType, timeout, limit },
  730. (error, result) => {
  731. if (callbackUrl) {
  732. // if present, notify the callbackUrl on success
  733. if (!error) {
  734. // Needs Node 12
  735. // const callbackHeaders = Object.fromEntries(Object.entries(req.headers || {}).filter(([k,v]) => k.match(/^X-CALLBACK-/i)))
  736. const callbackHeaders = {}
  737. for (const key of Object.getOwnPropertyNames(
  738. req.headers || {}
  739. ).filter(key => key.match(/^X-CALLBACK-/i))) {
  740. const found = key.match(/^X-CALLBACK-(.*)/i)
  741. callbackHeaders[found[1]] = req.headers[key]
  742. }
  743. request({ url: callbackUrl, headers: callbackHeaders })
  744. }
  745. } else {
  746. if (error != null) {
  747. return next(error)
  748. }
  749. res.send({ retryStatus: result })
  750. }
  751. }
  752. )
  753. }
  754. const transferLabelsSchema = z.object({
  755. params: z.object({
  756. from_user: zz.objectId(),
  757. to_user: zz.objectId(),
  758. }),
  759. })
  760. export function transferLabels(req, res, next) {
  761. const { params } = parseReq(req, transferLabelsSchema)
  762. const { from_user: fromUser, to_user: toUser } = params
  763. LabelsManager.transferLabels(fromUser, toUser, error => {
  764. if (error != null) {
  765. return next(error)
  766. }
  767. res.sendStatus(204)
  768. })
  769. }
  770. const deleteProjectSchema = z.object({
  771. params: z.object({
  772. project_id: zz.objectId().or(z.coerce.number()),
  773. }),
  774. })
  775. export function deleteProject(req, res, next) {
  776. const { params } = parseReq(req, deleteProjectSchema)
  777. const { project_id: projectId } = params
  778. // clear the timestamp before clearing the queue,
  779. // because the queue location is used in the migration
  780. RedisManager.clearFirstOpTimestamp(projectId, err => {
  781. if (err) {
  782. return next(err)
  783. }
  784. RedisManager.clearCachedHistoryId(projectId, err => {
  785. if (err) {
  786. return next(err)
  787. }
  788. RedisManager.destroyDocUpdatesQueue(projectId, err => {
  789. if (err) {
  790. return next(err)
  791. }
  792. SyncManager.clearResyncState(projectId, err => {
  793. if (err) {
  794. return next(err)
  795. }
  796. ErrorRecorder.clearError(projectId, err => {
  797. if (err) {
  798. return next(err)
  799. }
  800. res.sendStatus(204)
  801. })
  802. })
  803. })
  804. })
  805. })
  806. }