UpdatesProcessor.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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. return callback(
  256. new OError('inconsistent project history id between updates', {
  257. projectId,
  258. idFromUpdates,
  259. currentId: update.projectHistoryId,
  260. })
  261. )
  262. }
  263. }
  264. }
  265. WebApiManager.getHistoryId(projectId, (error, idFromWeb) => {
  266. if (error != null && idFromUpdates != null) {
  267. // present only on updates
  268. // 404s from web are an error
  269. metrics.inc('updates.batches.project-history-id.from-updates')
  270. return callback(null, idFromUpdates)
  271. } else if (error != null) {
  272. return callback(OError.tag(error))
  273. }
  274. if (idFromWeb == null && idFromUpdates == null) {
  275. // present on neither web nor updates
  276. callback(null, null)
  277. } else if (idFromWeb != null && idFromUpdates == null) {
  278. // present only on web
  279. metrics.inc('updates.batches.project-history-id.from-web')
  280. callback(null, idFromWeb)
  281. } else if (idFromWeb == null && idFromUpdates != null) {
  282. // present only on updates
  283. metrics.inc('updates.batches.project-history-id.from-updates')
  284. callback(null, idFromUpdates)
  285. } else if (idFromWeb.toString() !== idFromUpdates.toString()) {
  286. // inconsistent between web and updates
  287. metrics.inc('updates.batches.project-history-id.inconsistent-with-web')
  288. logger.warn(
  289. {
  290. projectId,
  291. idFromWeb,
  292. idFromUpdates,
  293. updates,
  294. },
  295. 'inconsistent project history id between updates and web'
  296. )
  297. callback(
  298. new OError('inconsistent project history id between updates and web')
  299. )
  300. } else {
  301. // the same on web and updates
  302. metrics.inc('updates.batches.project-history-id.from-updates')
  303. callback(null, idFromWeb)
  304. }
  305. })
  306. }
  307. function _handleOpsOutOfOrderError(projectId, projectHistoryId, err, ...rest) {
  308. const adjustedLength = Math.max(rest.length, 1)
  309. const results = rest.slice(0, adjustedLength - 1)
  310. const callback = rest[adjustedLength - 1]
  311. ErrorRecorder.getFailureRecord(projectId, (error, failureRecord) => {
  312. if (error != null) {
  313. return callback(error)
  314. }
  315. // Bypass ops-out-of-order errors in the stored chunk when in forceDebug mode
  316. if (failureRecord != null && failureRecord.forceDebug === true) {
  317. logger.warn(
  318. { err, projectId, projectHistoryId },
  319. 'ops out of order in chunk, forced continue'
  320. )
  321. callback(null, ...results) // return results without error
  322. } else {
  323. callback(err, ...results)
  324. }
  325. })
  326. }
  327. function _getMostRecentVersionWithDebug(projectId, projectHistoryId, callback) {
  328. HistoryStoreManager.getMostRecentVersion(
  329. projectId,
  330. projectHistoryId,
  331. (err, ...results) => {
  332. if (err instanceof Errors.OpsOutOfOrderError) {
  333. _handleOpsOutOfOrderError(
  334. projectId,
  335. projectHistoryId,
  336. err,
  337. ...results,
  338. callback
  339. )
  340. } else {
  341. callback(err, ...results)
  342. }
  343. }
  344. )
  345. }
  346. export function _processUpdates(
  347. projectId,
  348. projectHistoryId,
  349. updates,
  350. extendLock,
  351. callback
  352. ) {
  353. const profile = new Profiler('_processUpdates', {
  354. project_id: projectId,
  355. projectHistoryId,
  356. })
  357. // skip updates first if we're in a sync, we might not need to do anything else
  358. SyncManager.skipUpdatesDuringSync(
  359. projectId,
  360. updates,
  361. (error, filteredUpdates, newSyncState) => {
  362. profile.log('skipUpdatesDuringSync')
  363. if (error != null) {
  364. return callback(error)
  365. }
  366. if (filteredUpdates.length === 0) {
  367. // return early if there are no updates to apply
  368. return SyncManager.setResyncState(projectId, newSyncState, callback)
  369. }
  370. // only make request to history service if we have actual updates to process
  371. _getMostRecentVersionWithDebug(
  372. projectId,
  373. projectHistoryId,
  374. (
  375. error,
  376. baseVersion,
  377. projectStructureAndDocVersions,
  378. _lastChange,
  379. mostRecentChunk
  380. ) => {
  381. if (projectStructureAndDocVersions == null) {
  382. projectStructureAndDocVersions = { project: null, docs: {} }
  383. }
  384. profile.log('getMostRecentVersion')
  385. if (error != null) {
  386. return callback(error)
  387. }
  388. async.waterfall(
  389. [
  390. cb => {
  391. cb = profile.wrap('expandSyncUpdates', cb)
  392. SyncManager.expandSyncUpdates(
  393. projectId,
  394. projectHistoryId,
  395. mostRecentChunk,
  396. filteredUpdates,
  397. extendLock,
  398. cb
  399. )
  400. },
  401. (expandedUpdates, cb) => {
  402. let unappliedUpdates
  403. try {
  404. unappliedUpdates = _skipAlreadyAppliedUpdates(
  405. projectId,
  406. expandedUpdates,
  407. projectStructureAndDocVersions
  408. )
  409. } catch (err) {
  410. return cb(err)
  411. }
  412. profile.log('skipAlreadyAppliedUpdates')
  413. const compressedUpdates =
  414. UpdateCompressor.compressRawUpdates(unappliedUpdates)
  415. const timeTaken = profile
  416. .log('compressRawUpdates')
  417. .getTimeDelta()
  418. if (timeTaken >= 1000) {
  419. logger.debug(
  420. { projectId, updates: unappliedUpdates, timeTaken },
  421. 'slow compression of raw updates'
  422. )
  423. }
  424. cb = profile.wrap('createBlobs', cb)
  425. BlobManager.createBlobsForUpdates(
  426. projectId,
  427. projectHistoryId,
  428. compressedUpdates,
  429. extendLock,
  430. cb
  431. )
  432. },
  433. (updatesWithBlobs, cb) => {
  434. let changes
  435. try {
  436. changes = UpdateTranslator.convertToChanges(
  437. projectId,
  438. updatesWithBlobs
  439. ).map(change => change.toRaw())
  440. } catch (err) {
  441. return cb(err)
  442. } finally {
  443. profile.log('convertToChanges')
  444. }
  445. cb(null, changes)
  446. },
  447. (changes, cb) => {
  448. let change
  449. const numChanges = changes.length
  450. const byteLength = Buffer.byteLength(
  451. JSON.stringify(changes),
  452. 'utf8'
  453. )
  454. let numOperations = 0
  455. for (change of changes) {
  456. if (change.operations != null) {
  457. numOperations += change.operations.length
  458. }
  459. }
  460. metrics.timing('history-store.request.changes', numChanges, 1)
  461. metrics.timing('history-store.request.bytes', byteLength, 1)
  462. metrics.timing(
  463. 'history-store.request.operations',
  464. numOperations,
  465. 1
  466. )
  467. // thresholds taken from write_latex/main/lib/history_exporter.rb
  468. if (numChanges > 1000) {
  469. metrics.inc('history-store.request.exceeds-threshold.changes')
  470. }
  471. if (byteLength > Math.pow(1024, 2)) {
  472. metrics.inc('history-store.request.exceeds-threshold.bytes')
  473. const changeLengths = changes.map(change =>
  474. Buffer.byteLength(JSON.stringify(change), 'utf8')
  475. )
  476. logger.warn(
  477. { projectId, byteLength, changeLengths },
  478. 'change size exceeds limit'
  479. )
  480. }
  481. cb = profile.wrap('sendChanges', cb)
  482. // this is usually the longest request, so extend the lock before starting it
  483. extendLock(error => {
  484. if (error != null) {
  485. return cb(error)
  486. }
  487. if (changes.length === 0) {
  488. return cb()
  489. } // avoid unnecessary requests to history service
  490. HistoryStoreManager.sendChanges(
  491. projectId,
  492. projectHistoryId,
  493. changes,
  494. baseVersion,
  495. cb
  496. )
  497. })
  498. },
  499. cb => {
  500. cb = profile.wrap('setResyncState', cb)
  501. SyncManager.setResyncState(projectId, newSyncState, cb)
  502. },
  503. ],
  504. error => {
  505. profile.end()
  506. callback(error)
  507. }
  508. )
  509. }
  510. )
  511. }
  512. )
  513. }
  514. _mocks._skipAlreadyAppliedUpdates = (
  515. projectId,
  516. updates,
  517. projectStructureAndDocVersions
  518. ) => {
  519. function alreadySeenProjectVersion(previousProjectStructureVersion, update) {
  520. return (
  521. UpdateTranslator.isProjectStructureUpdate(update) &&
  522. previousProjectStructureVersion != null &&
  523. update.version != null &&
  524. Versions.gte(previousProjectStructureVersion, update.version)
  525. )
  526. }
  527. function alreadySeenDocVersion(previousDocVersions, update) {
  528. if (UpdateTranslator.isTextUpdate(update) && update.v != null) {
  529. const docId = update.doc
  530. return (
  531. previousDocVersions[docId] != null &&
  532. previousDocVersions[docId].v != null &&
  533. Versions.gte(previousDocVersions[docId].v, update.v)
  534. )
  535. } else {
  536. return false
  537. }
  538. }
  539. // check that the incoming updates are in the correct order (we do not
  540. // want to send out of order updates to the history service)
  541. let incomingProjectStructureVersion = null
  542. const incomingDocVersions = {}
  543. for (const update of updates) {
  544. if (alreadySeenProjectVersion(incomingProjectStructureVersion, update)) {
  545. logger.warn(
  546. { projectId, update, incomingProjectStructureVersion },
  547. 'incoming project structure updates are out of order'
  548. )
  549. throw new Errors.OpsOutOfOrderError(
  550. 'project structure version out of order on incoming updates'
  551. )
  552. } else if (alreadySeenDocVersion(incomingDocVersions, update)) {
  553. logger.warn(
  554. { projectId, update, incomingDocVersions },
  555. 'incoming doc updates are out of order'
  556. )
  557. throw new Errors.OpsOutOfOrderError(
  558. 'doc version out of order on incoming updates'
  559. )
  560. }
  561. // update the current project structure and doc versions
  562. if (UpdateTranslator.isProjectStructureUpdate(update)) {
  563. incomingProjectStructureVersion = update.version
  564. } else if (UpdateTranslator.isTextUpdate(update)) {
  565. incomingDocVersions[update.doc] = { v: update.v }
  566. }
  567. }
  568. // discard updates already applied
  569. const updatesToApply = []
  570. const previousProjectStructureVersion = projectStructureAndDocVersions.project
  571. const previousDocVersions = projectStructureAndDocVersions.docs
  572. if (projectStructureAndDocVersions != null) {
  573. const updateProjectVersions = []
  574. for (const update of updates) {
  575. if (update != null && update.version != null) {
  576. updateProjectVersions.push(update.version)
  577. }
  578. }
  579. logger.debug(
  580. { projectId, projectStructureAndDocVersions, updateProjectVersions },
  581. 'comparing updates with existing project versions'
  582. )
  583. }
  584. for (const update of updates) {
  585. if (alreadySeenProjectVersion(previousProjectStructureVersion, update)) {
  586. metrics.inc('updates.discarded_project_structure_version')
  587. logger.debug(
  588. { projectId, update, previousProjectStructureVersion },
  589. 'discarding previously applied project structure update'
  590. )
  591. continue
  592. }
  593. if (alreadySeenDocVersion(previousDocVersions, update)) {
  594. metrics.inc('updates.discarded_doc_version')
  595. logger.debug(
  596. { projectId, update, previousDocVersions },
  597. 'discarding previously applied doc update'
  598. )
  599. continue
  600. }
  601. // remove non-BMP characters from resync updates that have bypassed the normal docupdater flow
  602. _sanitizeUpdate(update)
  603. // if all checks above are ok then accept the update
  604. updatesToApply.push(update)
  605. }
  606. return updatesToApply
  607. }
  608. export function _skipAlreadyAppliedUpdates(...args) {
  609. return _mocks._skipAlreadyAppliedUpdates(...args)
  610. }
  611. function _sanitizeUpdate(update) {
  612. // adapted from docupdater's UpdateManager, we should clean these in docupdater
  613. // too but we already have queues with this problem so we will handle it here
  614. // too for robustness.
  615. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  616. const removeBadChars = str => str.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  617. // clean up any bad chars in resync diffs
  618. if (update.op) {
  619. for (const op of update.op) {
  620. if (op.i != null) {
  621. op.i = removeBadChars(op.i)
  622. }
  623. }
  624. }
  625. // clean up any bad chars in resync new docs
  626. if (update.docLines != null) {
  627. update.docLines = removeBadChars(update.docLines)
  628. }
  629. return update
  630. }
  631. export const promises = {
  632. /** @type {(projectId: string) => Promise<number>} */
  633. processUpdatesForProject: promisify(processUpdatesForProject),
  634. /** @type {(projectId: string, opts: any) => Promise<number>} */
  635. startResyncAndProcessUpdatesUnderLock: promisify(
  636. startResyncAndProcessUpdatesUnderLock
  637. ),
  638. }