UpdatesProcessor.js 25 KB

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