HttpController.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. recoverCorruptedFiles: z.stringbool().default(false),
  597. }),
  598. body: z.object({
  599. force: z.boolean().default(false),
  600. recoverCorruptedFiles: z.boolean().default(false),
  601. origin: z
  602. .object({
  603. kind: z.string(),
  604. })
  605. .optional(),
  606. historyRangesMigration: z.enum(['forwards', 'backwards']).optional(),
  607. }),
  608. })
  609. export function resyncProject(req, res, next) {
  610. const { query, params, body } = parseReq(req, resyncProjectSchema)
  611. const projectId = params.project_id
  612. const options = {}
  613. if (body.origin) {
  614. options.origin = body.origin
  615. }
  616. if (body.historyRangesMigration) {
  617. options.historyRangesMigration = body.historyRangesMigration
  618. }
  619. if (query.force || body.force) {
  620. if (query.recoverCorruptedFiles || body.recoverCorruptedFiles) {
  621. options.recoverCorruptedFiles = true
  622. }
  623. // this will delete the queue and clear the sync state
  624. // use if the project is completely broken
  625. SyncManager.startHardResync(projectId, options, error => {
  626. if (error != null) {
  627. return next(error)
  628. }
  629. // flush the sync operations
  630. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  631. if (error != null) {
  632. return next(error)
  633. }
  634. res.sendStatus(204)
  635. })
  636. })
  637. } else {
  638. SyncManager.startResync(projectId, options, error => {
  639. if (error != null) {
  640. return next(error)
  641. }
  642. // flush the sync operations
  643. UpdatesProcessor.processUpdatesForProject(projectId, error => {
  644. if (error != null) {
  645. return next(error)
  646. }
  647. res.sendStatus(204)
  648. })
  649. })
  650. }
  651. }
  652. const forceDebugProjectSchema = z.object({
  653. params: z.object({
  654. project_id: zz.objectId().or(z.coerce.number()),
  655. }),
  656. query: z.object({
  657. clear: z.stringbool().default(false),
  658. }),
  659. })
  660. export function forceDebugProject(req, res, next) {
  661. const { query, params } = parseReq(req, forceDebugProjectSchema)
  662. const projectId = params.project_id
  663. // set the debug flag to true unless we see ?clear=true
  664. const state = !query.clear
  665. ErrorRecorder.setForceDebug(projectId, state, error => {
  666. if (error != null) {
  667. return next(error)
  668. }
  669. // display the failure record to help debugging
  670. ErrorRecorder.getFailureRecord(projectId, (error, result) => {
  671. if (error != null) {
  672. return next(error)
  673. }
  674. res.send(result)
  675. })
  676. })
  677. }
  678. export function getFailures(req, res, next) {
  679. ErrorRecorder.getFailures((error, result) => {
  680. if (error != null) {
  681. return next(error)
  682. }
  683. res.send({ failures: result })
  684. })
  685. }
  686. export function getFailuresFull(req, res, next) {
  687. ErrorRecorder.getFailuresFull((error, result) => {
  688. if (error) return next(error)
  689. res.send(result)
  690. })
  691. }
  692. export function getQueueCounts(req, res, next) {
  693. RedisManager.getProjectIdsWithHistoryOpsCount((err, queuedProjectsCount) => {
  694. if (err != null) {
  695. return next(err)
  696. }
  697. res.send({ queuedProjects: queuedProjectsCount })
  698. })
  699. }
  700. const getLabelsSchema = z.object({
  701. params: z.object({
  702. project_id: zz.objectId().or(z.coerce.number()),
  703. }),
  704. })
  705. export function getLabels(req, res, next) {
  706. const { params } = parseReq(req, getLabelsSchema)
  707. const projectId = params.project_id
  708. HistoryApiManager.shouldUseProjectHistory(
  709. projectId,
  710. (error, shouldUseProjectHistory) => {
  711. if (error != null) {
  712. return next(error)
  713. }
  714. if (shouldUseProjectHistory) {
  715. LabelsManager.getLabels(projectId, (error, labels) => {
  716. if (error != null) {
  717. return next(error)
  718. }
  719. res.json(labels)
  720. })
  721. } else {
  722. res.sendStatus(409)
  723. }
  724. }
  725. )
  726. }
  727. const createLabelSchema = z.object({
  728. params: z.object({
  729. project_id: zz.objectId().or(z.coerce.number()),
  730. user_id: zz.objectId().optional(),
  731. }),
  732. body: z.object({
  733. version: z.number().int(),
  734. comment: z.string(),
  735. created_at: z.string().optional(),
  736. validate_exists: z.boolean().default(true),
  737. user_id: zz.objectId().nullable().optional(),
  738. }),
  739. })
  740. export function createLabel(req, res, next) {
  741. const { params, body } = parseReq(req, createLabelSchema)
  742. const { project_id: projectId, user_id: userIdParam } = params
  743. const {
  744. version,
  745. comment,
  746. user_id: userIdBody,
  747. created_at: createdAt,
  748. validate_exists: validateExists,
  749. } = body
  750. // Temporarily looking up both params and body while rolling out changes
  751. // in the router path - https://github.com/overleaf/internal/pull/20200
  752. const userId = userIdParam || userIdBody
  753. HistoryApiManager.shouldUseProjectHistory(
  754. projectId,
  755. (error, shouldUseProjectHistory) => {
  756. if (error != null) {
  757. return next(error)
  758. }
  759. if (shouldUseProjectHistory) {
  760. LabelsManager.createLabel(
  761. projectId,
  762. userId,
  763. version,
  764. comment,
  765. createdAt,
  766. validateExists,
  767. (error, label) => {
  768. if (error != null) {
  769. return next(error)
  770. }
  771. res.json(label)
  772. }
  773. )
  774. } else {
  775. logger.error(
  776. {
  777. projectId,
  778. userId,
  779. version,
  780. comment,
  781. createdAt,
  782. validateExists,
  783. },
  784. 'not using v2 history'
  785. )
  786. res.sendStatus(409)
  787. }
  788. }
  789. )
  790. }
  791. /**
  792. * This will delete a label if it is owned by the current user. If you wish to
  793. * delete a label regardless of the current user, then use `deleteLabel` instead.
  794. */
  795. const deleteLabelForUserSchema = z.object({
  796. params: z.object({
  797. project_id: zz.objectId().or(z.coerce.number()),
  798. user_id: zz.objectId(),
  799. label_id: zz.objectId(),
  800. }),
  801. })
  802. export function deleteLabelForUser(req, res, next) {
  803. const { params } = parseReq(req, deleteLabelForUserSchema)
  804. const { project_id: projectId, user_id: userId, label_id: labelId } = params
  805. LabelsManager.deleteLabelForUser(projectId, userId, labelId, error => {
  806. if (error != null) {
  807. return next(error)
  808. }
  809. res.sendStatus(204)
  810. })
  811. }
  812. const deleteLabelSchema = z.object({
  813. params: z.object({
  814. project_id: zz.objectId().or(z.coerce.number()),
  815. label_id: zz.objectId(),
  816. }),
  817. })
  818. export function deleteLabel(req, res, next) {
  819. const { params } = parseReq(req, deleteLabelSchema)
  820. const { project_id: projectId, label_id: labelId } = params
  821. LabelsManager.deleteLabel(projectId, labelId, error => {
  822. if (error != null) {
  823. return next(error)
  824. }
  825. res.sendStatus(204)
  826. })
  827. }
  828. const retryFailuresSchema = z.object({
  829. query: z.object({
  830. failureType: z.enum(['soft', 'hard']).optional(),
  831. // bail out after this time limit
  832. timeout: z.coerce.number().int().default(300),
  833. // maximum number of projects to check
  834. limit: z.coerce.number().int().default(100),
  835. callbackUrl: z.string().optional(),
  836. }),
  837. })
  838. export function retryFailures(req, res, next) {
  839. const { query } = parseReq(req, retryFailuresSchema)
  840. const { failureType, timeout, limit, callbackUrl } = query
  841. if (callbackUrl) {
  842. // send response but run in background when callbackUrl provided
  843. res.send({ retryStatus: 'running retryFailures in background' })
  844. }
  845. RetryManager.retryFailures(
  846. { failureType, timeout, limit },
  847. (error, result) => {
  848. if (callbackUrl) {
  849. // if present, notify the callbackUrl on success
  850. if (!error) {
  851. // Needs Node 12
  852. // const callbackHeaders = Object.fromEntries(Object.entries(req.headers || {}).filter(([k,v]) => k.match(/^X-CALLBACK-/i)))
  853. const callbackHeaders = {}
  854. for (const key of Object.getOwnPropertyNames(
  855. req.headers || {}
  856. ).filter(key => key.match(/^X-CALLBACK-/i))) {
  857. const found = key.match(/^X-CALLBACK-(.*)/i)
  858. callbackHeaders[found[1]] = req.headers[key]
  859. }
  860. fetchNothing(callbackUrl, { headers: callbackHeaders }).catch(err => {
  861. logger.warn({ err }, 'failed to ping callback url')
  862. })
  863. }
  864. } else {
  865. if (error != null) {
  866. return next(error)
  867. }
  868. res.send({ retryStatus: result })
  869. }
  870. }
  871. )
  872. }
  873. const transferLabelsSchema = z.object({
  874. params: z.object({
  875. from_user: zz.objectId(),
  876. to_user: zz.objectId(),
  877. }),
  878. })
  879. export function transferLabels(req, res, next) {
  880. const { params } = parseReq(req, transferLabelsSchema)
  881. const { from_user: fromUser, to_user: toUser } = params
  882. LabelsManager.transferLabels(fromUser, toUser, error => {
  883. if (error != null) {
  884. return next(error)
  885. }
  886. res.sendStatus(204)
  887. })
  888. }
  889. const deleteProjectSchema = z.object({
  890. params: z.object({
  891. project_id: zz.objectId().or(z.coerce.number()),
  892. }),
  893. })
  894. export function deleteProject(req, res, next) {
  895. const { params } = parseReq(req, deleteProjectSchema)
  896. const { project_id: projectId } = params
  897. // clear the timestamp before clearing the queue,
  898. // because the queue location is used in the migration
  899. RedisManager.clearFirstOpTimestamp(projectId, err => {
  900. if (err) {
  901. return next(err)
  902. }
  903. RedisManager.clearCachedHistoryId(projectId, err => {
  904. if (err) {
  905. return next(err)
  906. }
  907. RedisManager.destroyDocUpdatesQueue(projectId, err => {
  908. if (err) {
  909. return next(err)
  910. }
  911. SyncManager.clearResyncState(projectId, err => {
  912. if (err) {
  913. return next(err)
  914. }
  915. ErrorRecorder.clearError(projectId, err => {
  916. if (err) {
  917. return next(err)
  918. }
  919. res.sendStatus(204)
  920. })
  921. })
  922. })
  923. })
  924. })
  925. }