UpdatesProcessor.js 20 KB

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