UpdatesProcessor.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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, callback)
  525. }
  526. // only make request to history service if we have actual updates to process
  527. _getMostRecentVersionWithDebug(
  528. projectId,
  529. projectHistoryId,
  530. (
  531. error,
  532. baseVersion,
  533. projectStructureAndDocVersions,
  534. _lastChange,
  535. mostRecentChunk
  536. ) => {
  537. if (projectStructureAndDocVersions == null) {
  538. projectStructureAndDocVersions = { project: null, docs: {} }
  539. }
  540. profile.log('getMostRecentVersion')
  541. if (error != null) {
  542. return callback(error)
  543. }
  544. let resyncNeeded = false
  545. async.waterfall(
  546. [
  547. cb => {
  548. cb = profile.wrap('expandSyncUpdates', cb)
  549. SyncManager.expandSyncUpdates(
  550. projectId,
  551. projectHistoryId,
  552. mostRecentChunk,
  553. filteredUpdates,
  554. extendLock,
  555. cb
  556. )
  557. },
  558. (expandedUpdates, cb) => {
  559. let unappliedUpdates
  560. try {
  561. unappliedUpdates = _skipAlreadyAppliedUpdates(
  562. projectId,
  563. expandedUpdates,
  564. projectStructureAndDocVersions
  565. )
  566. } catch (err) {
  567. return cb(err)
  568. }
  569. profile.log('skipAlreadyAppliedUpdates')
  570. const compressedUpdates =
  571. UpdateCompressor.compressRawUpdates(unappliedUpdates)
  572. const timeTaken = profile
  573. .log('compressRawUpdates')
  574. .getTimeDelta()
  575. if (timeTaken >= 1000) {
  576. logger.debug(
  577. { projectId, updates: unappliedUpdates, timeTaken },
  578. 'slow compression of raw updates'
  579. )
  580. }
  581. cb = profile.wrap('createBlobs', cb)
  582. BlobManager.createBlobsForUpdates(
  583. projectId,
  584. projectHistoryId,
  585. compressedUpdates,
  586. extendLock,
  587. cb
  588. )
  589. },
  590. (updatesWithBlobs, cb) => {
  591. let changes
  592. try {
  593. changes = UpdateTranslator.convertToChanges(
  594. projectId,
  595. updatesWithBlobs
  596. ).map(change => change.toRaw())
  597. } catch (err) {
  598. return cb(err)
  599. } finally {
  600. profile.log('convertToChanges')
  601. }
  602. cb(null, changes)
  603. },
  604. (changes, cb) => {
  605. let change
  606. const numChanges = changes.length
  607. const byteLength = Buffer.byteLength(
  608. JSON.stringify(changes),
  609. 'utf8'
  610. )
  611. let numOperations = 0
  612. for (change of changes) {
  613. if (change.operations != null) {
  614. numOperations += change.operations.length
  615. }
  616. }
  617. metrics.timing('history-store.request.changes', numChanges, 1)
  618. metrics.timing('history-store.request.bytes', byteLength, 1)
  619. metrics.timing(
  620. 'history-store.request.operations',
  621. numOperations,
  622. 1
  623. )
  624. // thresholds taken from write_latex/main/lib/history_exporter.rb
  625. if (numChanges > 1000) {
  626. metrics.inc('history-store.request.exceeds-threshold.changes')
  627. }
  628. if (byteLength > Math.pow(1024, 2)) {
  629. metrics.inc('history-store.request.exceeds-threshold.bytes')
  630. const changeLengths = changes.map(change =>
  631. Buffer.byteLength(JSON.stringify(change), 'utf8')
  632. )
  633. logger.warn(
  634. { projectId, byteLength, changeLengths },
  635. 'change size exceeds limit'
  636. )
  637. }
  638. cb = profile.wrap('sendChanges', cb)
  639. // this is usually the longest request, so extend the lock before starting it
  640. extendLock(error => {
  641. if (error != null) {
  642. return cb(error)
  643. }
  644. if (changes.length === 0) {
  645. return cb()
  646. } // avoid unnecessary requests to history service
  647. HistoryStoreManager.sendChanges(
  648. projectId,
  649. projectHistoryId,
  650. changes,
  651. baseVersion,
  652. (err, response) => {
  653. if (err) {
  654. return cb(err)
  655. }
  656. resyncNeeded = response.resyncNeeded
  657. cb()
  658. }
  659. )
  660. })
  661. },
  662. cb => {
  663. cb = profile.wrap('setResyncState', cb)
  664. SyncManager.setResyncState(projectId, newSyncState, cb)
  665. },
  666. ],
  667. error => {
  668. profile.end()
  669. if (error) {
  670. callback(error)
  671. } else {
  672. callback(null, { resyncNeeded })
  673. }
  674. }
  675. )
  676. }
  677. )
  678. }
  679. )
  680. }
  681. _mocks._skipAlreadyAppliedUpdates = (
  682. projectId,
  683. updates,
  684. projectStructureAndDocVersions
  685. ) => {
  686. function alreadySeenProjectVersion(previousProjectStructureVersion, update) {
  687. return (
  688. UpdateTranslator.isProjectStructureUpdate(update) &&
  689. previousProjectStructureVersion != null &&
  690. update.version != null &&
  691. Versions.gte(previousProjectStructureVersion, update.version)
  692. )
  693. }
  694. function alreadySeenDocVersion(previousDocVersions, update) {
  695. if (UpdateTranslator.isTextUpdate(update) && update.v != null) {
  696. const docId = update.doc
  697. return (
  698. previousDocVersions[docId] != null &&
  699. previousDocVersions[docId].v != null &&
  700. Versions.gte(previousDocVersions[docId].v, update.v)
  701. )
  702. } else {
  703. return false
  704. }
  705. }
  706. // check that the incoming updates are in the correct order (we do not
  707. // want to send out of order updates to the history service)
  708. let incomingProjectStructureVersion = null
  709. const incomingDocVersions = {}
  710. for (const update of updates) {
  711. if (alreadySeenProjectVersion(incomingProjectStructureVersion, update)) {
  712. logger.warn(
  713. { projectId, update, incomingProjectStructureVersion },
  714. 'incoming project structure updates are out of order'
  715. )
  716. throw new Errors.OpsOutOfOrderError(
  717. 'project structure version out of order on incoming updates'
  718. )
  719. } else if (alreadySeenDocVersion(incomingDocVersions, update)) {
  720. logger.warn(
  721. { projectId, update, incomingDocVersions },
  722. 'incoming doc updates are out of order'
  723. )
  724. throw new Errors.OpsOutOfOrderError(
  725. 'doc version out of order on incoming updates'
  726. )
  727. }
  728. // update the current project structure and doc versions
  729. if (UpdateTranslator.isProjectStructureUpdate(update)) {
  730. incomingProjectStructureVersion = update.version
  731. } else if (UpdateTranslator.isTextUpdate(update)) {
  732. incomingDocVersions[update.doc] = { v: update.v }
  733. }
  734. }
  735. // discard updates already applied
  736. const updatesToApply = []
  737. const previousProjectStructureVersion = projectStructureAndDocVersions.project
  738. const previousDocVersions = projectStructureAndDocVersions.docs
  739. if (projectStructureAndDocVersions != null) {
  740. const updateProjectVersions = []
  741. for (const update of updates) {
  742. if (update != null && update.version != null) {
  743. updateProjectVersions.push(update.version)
  744. }
  745. }
  746. logger.debug(
  747. { projectId, projectStructureAndDocVersions, updateProjectVersions },
  748. 'comparing updates with existing project versions'
  749. )
  750. }
  751. for (const update of updates) {
  752. if (alreadySeenProjectVersion(previousProjectStructureVersion, update)) {
  753. metrics.inc('updates.discarded_project_structure_version')
  754. logger.debug(
  755. { projectId, update, previousProjectStructureVersion },
  756. 'discarding previously applied project structure update'
  757. )
  758. continue
  759. }
  760. if (alreadySeenDocVersion(previousDocVersions, update)) {
  761. metrics.inc('updates.discarded_doc_version')
  762. logger.debug(
  763. { projectId, update, previousDocVersions },
  764. 'discarding previously applied doc update'
  765. )
  766. continue
  767. }
  768. // remove non-BMP characters from resync updates that have bypassed the normal docupdater flow
  769. _sanitizeUpdate(update)
  770. // if all checks above are ok then accept the update
  771. updatesToApply.push(update)
  772. }
  773. return updatesToApply
  774. }
  775. export function _skipAlreadyAppliedUpdates(...args) {
  776. return _mocks._skipAlreadyAppliedUpdates(...args)
  777. }
  778. function _sanitizeUpdate(update) {
  779. // adapted from docupdater's UpdateManager, we should clean these in docupdater
  780. // too but we already have queues with this problem so we will handle it here
  781. // too for robustness.
  782. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  783. const removeBadChars = str => str.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  784. // clean up any bad chars in resync diffs
  785. if (update.op) {
  786. for (const op of update.op) {
  787. if (op.i != null) {
  788. op.i = removeBadChars(op.i)
  789. }
  790. }
  791. }
  792. // clean up any bad chars in resync new docs
  793. if (update.docLines != null) {
  794. update.docLines = removeBadChars(update.docLines)
  795. }
  796. return update
  797. }
  798. export const promises = {
  799. /** @type {(projectId: string) => Promise<number>} */
  800. processUpdatesForProject: promisify(processUpdatesForProject),
  801. /** @type {(projectId: string, opts: any) => Promise<number>} */
  802. startResyncAndProcessUpdatesUnderLock: promisify(
  803. startResyncAndProcessUpdatesUnderLock
  804. ),
  805. }