UpdatesProcessor.js 26 KB

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