UpdatesProcessor.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. import { promisify } from 'node:util'
  2. import logger from '@overleaf/logger'
  3. import async from 'async'
  4. import metrics from '@overleaf/metrics'
  5. import Settings from '@overleaf/settings'
  6. import OError from '@overleaf/o-error'
  7. import * as HistoryStoreManager from './HistoryStoreManager.js'
  8. import * as UpdateTranslator from './UpdateTranslator.js'
  9. import * as BlobManager from './BlobManager.js'
  10. import * as RedisManager from './RedisManager.js'
  11. import * as ErrorRecorder from './ErrorRecorder.js'
  12. import * as LockManager from './LockManager.js'
  13. import * as UpdateCompressor from './UpdateCompressor.js'
  14. import * as WebApiManager from './WebApiManager.js'
  15. import * as SyncManager from './SyncManager.js'
  16. import * as Versions from './Versions.js'
  17. import * as Errors from './Errors.js'
  18. import * as Metrics from './Metrics.js'
  19. import { Profiler } from './Profiler.js'
  20. const keys = Settings.redis.lock.key_schema
  21. export const REDIS_READ_BATCH_SIZE = 500
  22. /**
  23. * Container for functions that need to be mocked in tests
  24. *
  25. * TODO: Rewrite tests in terms of exported functions only
  26. */
  27. export const _mocks = {}
  28. export function getRawUpdates(projectId, batchSize, callback) {
  29. RedisManager.getRawUpdatesBatch(projectId, batchSize, (error, batch) => {
  30. if (error != null) {
  31. return callback(OError.tag(error))
  32. }
  33. let updates
  34. try {
  35. updates = RedisManager.parseDocUpdates(batch.rawUpdates)
  36. } catch (error) {
  37. return callback(OError.tag(error))
  38. }
  39. _getHistoryId(projectId, updates, (error, historyId) => {
  40. if (error != null) {
  41. return callback(OError.tag(error))
  42. }
  43. HistoryStoreManager.getMostRecentChunk(
  44. projectId,
  45. historyId,
  46. (error, chunk) => {
  47. if (error != null) {
  48. return callback(OError.tag(error))
  49. }
  50. callback(null, { project_id: projectId, chunk, updates })
  51. }
  52. )
  53. })
  54. })
  55. }
  56. // Trigger resync and start processing under lock to avoid other operations to
  57. // flush the resync updates.
  58. export function startResyncAndProcessUpdatesUnderLock(
  59. projectId,
  60. opts,
  61. callback
  62. ) {
  63. const startTimeMs = Date.now()
  64. LockManager.runWithLock(
  65. keys.projectHistoryLock({ project_id: projectId }),
  66. (extendLock, releaseLock) => {
  67. SyncManager.startResyncWithoutLock(projectId, opts, err => {
  68. if (err) return callback(OError.tag(err))
  69. extendLock(err => {
  70. if (err) return callback(OError.tag(err))
  71. _countAndProcessUpdates(
  72. projectId,
  73. extendLock,
  74. REDIS_READ_BATCH_SIZE,
  75. releaseLock
  76. )
  77. })
  78. })
  79. },
  80. (error, queueSize) => {
  81. if (error) {
  82. OError.tag(error)
  83. }
  84. ErrorRecorder.record(projectId, queueSize, error, callback)
  85. if (queueSize > 0) {
  86. const duration = (Date.now() - startTimeMs) / 1000
  87. Metrics.historyFlushDurationSeconds.observe(duration)
  88. Metrics.historyFlushQueueSize.observe(queueSize)
  89. }
  90. // clear the timestamp in the background if the queue is now empty
  91. RedisManager.clearDanglingFirstOpTimestamp(projectId, () => {})
  92. }
  93. )
  94. }
  95. // Process all updates for a project, only check project-level information once
  96. export function processUpdatesForProject(projectId, callback) {
  97. const startTimeMs = Date.now()
  98. LockManager.runWithLock(
  99. keys.projectHistoryLock({ project_id: projectId }),
  100. (extendLock, releaseLock) => {
  101. _countAndProcessUpdates(
  102. projectId,
  103. extendLock,
  104. REDIS_READ_BATCH_SIZE,
  105. releaseLock
  106. )
  107. },
  108. (error, queueSize) => {
  109. if (error) {
  110. OError.tag(error)
  111. }
  112. ErrorRecorder.record(projectId, queueSize, error, callback)
  113. if (queueSize > 0) {
  114. const duration = (Date.now() - startTimeMs) / 1000
  115. Metrics.historyFlushDurationSeconds.observe(duration)
  116. Metrics.historyFlushQueueSize.observe(queueSize)
  117. }
  118. // clear the timestamp in the background if the queue is now empty
  119. RedisManager.clearDanglingFirstOpTimestamp(projectId, () => {})
  120. }
  121. )
  122. }
  123. export function processUpdatesForProjectUsingBisect(
  124. projectId,
  125. amountToProcess,
  126. callback
  127. ) {
  128. LockManager.runWithLock(
  129. keys.projectHistoryLock({ project_id: projectId }),
  130. (extendLock, releaseLock) => {
  131. _countAndProcessUpdates(
  132. projectId,
  133. extendLock,
  134. amountToProcess,
  135. releaseLock
  136. )
  137. },
  138. (error, queueSize) => {
  139. if (amountToProcess === 0 || queueSize === 0) {
  140. // no further processing possible
  141. if (error != null) {
  142. ErrorRecorder.record(
  143. projectId,
  144. queueSize,
  145. OError.tag(error),
  146. callback
  147. )
  148. } else {
  149. callback()
  150. }
  151. } else {
  152. if (error != null) {
  153. // decrease the batch size when we hit an error
  154. processUpdatesForProjectUsingBisect(
  155. projectId,
  156. Math.floor(amountToProcess / 2),
  157. callback
  158. )
  159. } else {
  160. // otherwise continue processing with the same batch size
  161. processUpdatesForProjectUsingBisect(
  162. projectId,
  163. amountToProcess,
  164. callback
  165. )
  166. }
  167. }
  168. }
  169. )
  170. }
  171. export function processSingleUpdateForProject(projectId, callback) {
  172. LockManager.runWithLock(
  173. keys.projectHistoryLock({ project_id: projectId }),
  174. (
  175. extendLock,
  176. releaseLock // set the batch size to 1 for single-stepping
  177. ) => {
  178. _countAndProcessUpdates(projectId, extendLock, 1, releaseLock)
  179. },
  180. (
  181. error,
  182. queueSize // no need to clear the flush marker when single stepping
  183. ) => {
  184. // it will be cleared up on the next background flush if
  185. // the queue is empty
  186. ErrorRecorder.record(projectId, queueSize, error, callback)
  187. }
  188. )
  189. }
  190. _mocks._countAndProcessUpdates = (
  191. projectId,
  192. extendLock,
  193. batchSize,
  194. callback
  195. ) => {
  196. RedisManager.countUnprocessedUpdates(projectId, (error, queueSize) => {
  197. if (error != null) {
  198. return callback(OError.tag(error))
  199. }
  200. if (queueSize > 0) {
  201. logger.debug({ projectId, queueSize }, 'processing uncompressed updates')
  202. RedisManager.getUpdatesInBatches(
  203. projectId,
  204. batchSize,
  205. (updates, cb) => {
  206. _processUpdatesBatch(projectId, updates, extendLock, cb)
  207. },
  208. error => {
  209. // Unconventional callback signature. The caller needs the queue size
  210. // even when an error is thrown in order to record the queue size in
  211. // the projectHistoryFailures collection. We'll have to find another
  212. // way to achieve this when we promisify.
  213. callback(error, queueSize)
  214. }
  215. )
  216. } else {
  217. logger.debug({ projectId }, 'no updates to process')
  218. callback(null, queueSize)
  219. }
  220. })
  221. }
  222. function _countAndProcessUpdates(...args) {
  223. _mocks._countAndProcessUpdates(...args)
  224. }
  225. function _processUpdatesBatch(projectId, updates, extendLock, callback) {
  226. // If the project doesn't have a history then we can bail out here
  227. _getHistoryId(projectId, updates, (error, historyId) => {
  228. if (error != null) {
  229. return callback(OError.tag(error))
  230. }
  231. if (historyId == null) {
  232. logger.debug(
  233. { projectId },
  234. 'discarding updates as project does not use history'
  235. )
  236. return callback()
  237. }
  238. _processUpdates(projectId, historyId, updates, extendLock, error => {
  239. if (error != null) {
  240. return callback(OError.tag(error))
  241. }
  242. callback()
  243. })
  244. })
  245. }
  246. export function _getHistoryId(projectId, updates, callback) {
  247. let idFromUpdates = null
  248. // check that all updates have the same history id
  249. for (const update of updates) {
  250. if (update.projectHistoryId != null) {
  251. if (idFromUpdates == null) {
  252. idFromUpdates = update.projectHistoryId.toString()
  253. } else if (idFromUpdates !== update.projectHistoryId.toString()) {
  254. metrics.inc('updates.batches.project-history-id.inconsistent-update')
  255. logger.warn(
  256. {
  257. projectId,
  258. updates,
  259. idFromUpdates,
  260. currentId: update.projectHistoryId,
  261. },
  262. 'inconsistent project history id between updates'
  263. )
  264. return callback(
  265. new OError('inconsistent project history id between updates')
  266. )
  267. }
  268. }
  269. }
  270. WebApiManager.getHistoryId(projectId, (error, idFromWeb) => {
  271. if (error != null && idFromUpdates != null) {
  272. // present only on updates
  273. // 404s from web are an error
  274. metrics.inc('updates.batches.project-history-id.from-updates')
  275. return callback(null, idFromUpdates)
  276. } else if (error != null) {
  277. return callback(OError.tag(error))
  278. }
  279. if (idFromWeb == null && idFromUpdates == null) {
  280. // present on neither web nor updates
  281. callback(null, null)
  282. } else if (idFromWeb != null && idFromUpdates == null) {
  283. // present only on web
  284. metrics.inc('updates.batches.project-history-id.from-web')
  285. callback(null, idFromWeb)
  286. } else if (idFromWeb == null && idFromUpdates != null) {
  287. // present only on updates
  288. metrics.inc('updates.batches.project-history-id.from-updates')
  289. callback(null, idFromUpdates)
  290. } else if (idFromWeb.toString() !== idFromUpdates.toString()) {
  291. // inconsistent between web and updates
  292. metrics.inc('updates.batches.project-history-id.inconsistent-with-web')
  293. logger.warn(
  294. {
  295. projectId,
  296. idFromWeb,
  297. idFromUpdates,
  298. updates,
  299. },
  300. 'inconsistent project history id between updates and web'
  301. )
  302. callback(
  303. new OError('inconsistent project history id between updates and web')
  304. )
  305. } else {
  306. // the same on web and updates
  307. metrics.inc('updates.batches.project-history-id.from-updates')
  308. callback(null, idFromWeb)
  309. }
  310. })
  311. }
  312. function _handleOpsOutOfOrderError(projectId, projectHistoryId, err, ...rest) {
  313. const adjustedLength = Math.max(rest.length, 1)
  314. const results = rest.slice(0, adjustedLength - 1)
  315. const callback = rest[adjustedLength - 1]
  316. ErrorRecorder.getFailureRecord(projectId, (error, failureRecord) => {
  317. if (error != null) {
  318. return callback(error)
  319. }
  320. // Bypass ops-out-of-order errors in the stored chunk when in forceDebug mode
  321. if (failureRecord != null && failureRecord.forceDebug === true) {
  322. logger.warn(
  323. { projectId, projectHistoryId },
  324. 'ops out of order in chunk, forced continue'
  325. )
  326. callback(null, ...results) // return results without error
  327. } else {
  328. logger.warn(
  329. { projectId, projectHistoryId },
  330. 'ops out of order in chunk, returning error'
  331. )
  332. callback(err, ...results)
  333. }
  334. })
  335. }
  336. function _getMostRecentVersionWithDebug(projectId, projectHistoryId, callback) {
  337. HistoryStoreManager.getMostRecentVersion(
  338. projectId,
  339. projectHistoryId,
  340. (err, ...results) => {
  341. if (err instanceof Errors.OpsOutOfOrderError) {
  342. _handleOpsOutOfOrderError(
  343. projectId,
  344. projectHistoryId,
  345. err,
  346. ...results,
  347. callback
  348. )
  349. } else {
  350. callback(err, ...results)
  351. }
  352. }
  353. )
  354. }
  355. export function _processUpdates(
  356. projectId,
  357. projectHistoryId,
  358. updates,
  359. extendLock,
  360. callback
  361. ) {
  362. const profile = new Profiler('_processUpdates', {
  363. project_id: projectId,
  364. projectHistoryId,
  365. })
  366. // skip updates first if we're in a sync, we might not need to do anything else
  367. SyncManager.skipUpdatesDuringSync(
  368. projectId,
  369. updates,
  370. (error, filteredUpdates, newSyncState) => {
  371. profile.log('skipUpdatesDuringSync')
  372. if (error != null) {
  373. return callback(error)
  374. }
  375. if (filteredUpdates.length === 0) {
  376. // return early if there are no updates to apply
  377. return SyncManager.setResyncState(projectId, newSyncState, callback)
  378. }
  379. // only make request to history service if we have actual updates to process
  380. _getMostRecentVersionWithDebug(
  381. projectId,
  382. projectHistoryId,
  383. (
  384. error,
  385. baseVersion,
  386. projectStructureAndDocVersions,
  387. _lastChange,
  388. mostRecentChunk
  389. ) => {
  390. if (projectStructureAndDocVersions == null) {
  391. projectStructureAndDocVersions = { project: null, docs: {} }
  392. }
  393. profile.log('getMostRecentVersion')
  394. if (error != null) {
  395. return callback(error)
  396. }
  397. async.waterfall(
  398. [
  399. cb => {
  400. cb = profile.wrap('expandSyncUpdates', cb)
  401. SyncManager.expandSyncUpdates(
  402. projectId,
  403. projectHistoryId,
  404. mostRecentChunk,
  405. filteredUpdates,
  406. extendLock,
  407. cb
  408. )
  409. },
  410. (expandedUpdates, cb) => {
  411. let unappliedUpdates
  412. try {
  413. unappliedUpdates = _skipAlreadyAppliedUpdates(
  414. projectId,
  415. expandedUpdates,
  416. projectStructureAndDocVersions
  417. )
  418. } catch (err) {
  419. return cb(err)
  420. }
  421. profile.log('skipAlreadyAppliedUpdates')
  422. const compressedUpdates =
  423. UpdateCompressor.compressRawUpdates(unappliedUpdates)
  424. const timeTaken = profile
  425. .log('compressRawUpdates')
  426. .getTimeDelta()
  427. if (timeTaken >= 1000) {
  428. logger.debug(
  429. { projectId, updates: unappliedUpdates, timeTaken },
  430. 'slow compression of raw updates'
  431. )
  432. }
  433. cb = profile.wrap('createBlobs', cb)
  434. BlobManager.createBlobsForUpdates(
  435. projectId,
  436. projectHistoryId,
  437. compressedUpdates,
  438. extendLock,
  439. cb
  440. )
  441. },
  442. (updatesWithBlobs, cb) => {
  443. let changes
  444. try {
  445. changes = UpdateTranslator.convertToChanges(
  446. projectId,
  447. updatesWithBlobs
  448. ).map(change => change.toRaw())
  449. } catch (err) {
  450. return cb(err)
  451. } finally {
  452. profile.log('convertToChanges')
  453. }
  454. cb(null, changes)
  455. },
  456. (changes, cb) => {
  457. let change
  458. const numChanges = changes.length
  459. const byteLength = Buffer.byteLength(
  460. JSON.stringify(changes),
  461. 'utf8'
  462. )
  463. let numOperations = 0
  464. for (change of changes) {
  465. if (change.operations != null) {
  466. numOperations += change.operations.length
  467. }
  468. }
  469. metrics.timing('history-store.request.changes', numChanges, 1)
  470. metrics.timing('history-store.request.bytes', byteLength, 1)
  471. metrics.timing(
  472. 'history-store.request.operations',
  473. numOperations,
  474. 1
  475. )
  476. // thresholds taken from write_latex/main/lib/history_exporter.rb
  477. if (numChanges > 1000) {
  478. metrics.inc('history-store.request.exceeds-threshold.changes')
  479. }
  480. if (byteLength > Math.pow(1024, 2)) {
  481. metrics.inc('history-store.request.exceeds-threshold.bytes')
  482. const changeLengths = changes.map(change =>
  483. Buffer.byteLength(JSON.stringify(change), 'utf8')
  484. )
  485. logger.warn(
  486. { projectId, byteLength, changeLengths },
  487. 'change size exceeds limit'
  488. )
  489. }
  490. cb = profile.wrap('sendChanges', cb)
  491. // this is usually the longest request, so extend the lock before starting it
  492. extendLock(error => {
  493. if (error != null) {
  494. return cb(error)
  495. }
  496. if (changes.length === 0) {
  497. return cb()
  498. } // avoid unnecessary requests to history service
  499. HistoryStoreManager.sendChanges(
  500. projectId,
  501. projectHistoryId,
  502. changes,
  503. baseVersion,
  504. cb
  505. )
  506. })
  507. },
  508. cb => {
  509. cb = profile.wrap('setResyncState', cb)
  510. SyncManager.setResyncState(projectId, newSyncState, cb)
  511. },
  512. ],
  513. error => {
  514. profile.end()
  515. callback(error)
  516. }
  517. )
  518. }
  519. )
  520. }
  521. )
  522. }
  523. _mocks._skipAlreadyAppliedUpdates = (
  524. projectId,
  525. updates,
  526. projectStructureAndDocVersions
  527. ) => {
  528. function alreadySeenProjectVersion(previousProjectStructureVersion, update) {
  529. return (
  530. UpdateTranslator.isProjectStructureUpdate(update) &&
  531. previousProjectStructureVersion != null &&
  532. update.version != null &&
  533. Versions.gte(previousProjectStructureVersion, update.version)
  534. )
  535. }
  536. function alreadySeenDocVersion(previousDocVersions, update) {
  537. if (UpdateTranslator.isTextUpdate(update) && update.v != null) {
  538. const docId = update.doc
  539. return (
  540. previousDocVersions[docId] != null &&
  541. previousDocVersions[docId].v != null &&
  542. Versions.gte(previousDocVersions[docId].v, update.v)
  543. )
  544. } else {
  545. return false
  546. }
  547. }
  548. // check that the incoming updates are in the correct order (we do not
  549. // want to send out of order updates to the history service)
  550. let incomingProjectStructureVersion = null
  551. const incomingDocVersions = {}
  552. for (const update of updates) {
  553. if (alreadySeenProjectVersion(incomingProjectStructureVersion, update)) {
  554. logger.warn(
  555. { projectId, update, incomingProjectStructureVersion },
  556. 'incoming project structure updates are out of order'
  557. )
  558. throw new Errors.OpsOutOfOrderError(
  559. 'project structure version out of order on incoming updates'
  560. )
  561. } else if (alreadySeenDocVersion(incomingDocVersions, update)) {
  562. logger.warn(
  563. { projectId, update, incomingDocVersions },
  564. 'incoming doc updates are out of order'
  565. )
  566. throw new Errors.OpsOutOfOrderError(
  567. 'doc version out of order on incoming updates'
  568. )
  569. }
  570. // update the current project structure and doc versions
  571. if (UpdateTranslator.isProjectStructureUpdate(update)) {
  572. incomingProjectStructureVersion = update.version
  573. } else if (UpdateTranslator.isTextUpdate(update)) {
  574. incomingDocVersions[update.doc] = { v: update.v }
  575. }
  576. }
  577. // discard updates already applied
  578. const updatesToApply = []
  579. const previousProjectStructureVersion = projectStructureAndDocVersions.project
  580. const previousDocVersions = projectStructureAndDocVersions.docs
  581. if (projectStructureAndDocVersions != null) {
  582. const updateProjectVersions = []
  583. for (const update of updates) {
  584. if (update != null && update.version != null) {
  585. updateProjectVersions.push(update.version)
  586. }
  587. }
  588. logger.debug(
  589. { projectId, projectStructureAndDocVersions, updateProjectVersions },
  590. 'comparing updates with existing project versions'
  591. )
  592. }
  593. for (const update of updates) {
  594. if (alreadySeenProjectVersion(previousProjectStructureVersion, update)) {
  595. metrics.inc('updates.discarded_project_structure_version')
  596. logger.debug(
  597. { projectId, update, previousProjectStructureVersion },
  598. 'discarding previously applied project structure update'
  599. )
  600. continue
  601. }
  602. if (alreadySeenDocVersion(previousDocVersions, update)) {
  603. metrics.inc('updates.discarded_doc_version')
  604. logger.debug(
  605. { projectId, update, previousDocVersions },
  606. 'discarding previously applied doc update'
  607. )
  608. continue
  609. }
  610. // remove non-BMP characters from resync updates that have bypassed the normal docupdater flow
  611. _sanitizeUpdate(update)
  612. // if all checks above are ok then accept the update
  613. updatesToApply.push(update)
  614. }
  615. return updatesToApply
  616. }
  617. export function _skipAlreadyAppliedUpdates(...args) {
  618. return _mocks._skipAlreadyAppliedUpdates(...args)
  619. }
  620. function _sanitizeUpdate(update) {
  621. // adapted from docupdater's UpdateManager, we should clean these in docupdater
  622. // too but we already have queues with this problem so we will handle it here
  623. // too for robustness.
  624. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  625. const removeBadChars = str => str.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  626. // clean up any bad chars in resync diffs
  627. if (update.op) {
  628. for (const op of update.op) {
  629. if (op.i != null) {
  630. op.i = removeBadChars(op.i)
  631. }
  632. }
  633. }
  634. // clean up any bad chars in resync new docs
  635. if (update.docLines != null) {
  636. update.docLines = removeBadChars(update.docLines)
  637. }
  638. return update
  639. }
  640. export const promises = {
  641. /** @type {(projectId: string) => Promise<number>} */
  642. processUpdatesForProject: promisify(processUpdatesForProject),
  643. /** @type {(projectId: string, opts: any) => Promise<number>} */
  644. startResyncAndProcessUpdatesUnderLock: promisify(
  645. startResyncAndProcessUpdatesUnderLock
  646. ),
  647. }