UpdatesProcessor.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import { promisify } from '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 { Profiler } from './Profiler.js'
  19. const keys = Settings.redis.lock.key_schema
  20. const PROJECT_HISTORY = {
  21. ENABLED: 'enabled',
  22. NOT_ENABLED: 'not-enabled',
  23. }
  24. export const REDIS_READ_BATCH_SIZE = 500
  25. /**
  26. * Container for functions that need to be mocked in tests
  27. *
  28. * TODO: Rewrite tests in terms of exported functions only
  29. */
  30. export const _mocks = {}
  31. export function getRawUpdates(projectId, batchSize, callback) {
  32. RedisManager.getOldestDocUpdates(
  33. projectId,
  34. batchSize,
  35. (error, rawUpdates) => {
  36. if (error != null) {
  37. return callback(OError.tag(error))
  38. }
  39. RedisManager.parseDocUpdates(rawUpdates, (error, updates) => {
  40. if (error != null) {
  41. return callback(OError.tag(error))
  42. }
  43. _getHistoryId(projectId, updates, (error, historyId) => {
  44. if (error != null) {
  45. return callback(OError.tag(error))
  46. }
  47. HistoryStoreManager.getMostRecentChunk(
  48. projectId,
  49. historyId,
  50. (error, chunk) => {
  51. if (error != null) {
  52. return callback(OError.tag(error))
  53. }
  54. callback(null, { project_id: projectId, chunk, updates })
  55. }
  56. )
  57. })
  58. })
  59. }
  60. )
  61. }
  62. // Process all updates for a project, only check project-level information once
  63. export function processUpdatesForProject(projectId, callback) {
  64. LockManager.runWithLock(
  65. keys.projectHistoryLock({ project_id: projectId }),
  66. (extendLock, releaseLock) => {
  67. _countAndProcessUpdates(
  68. projectId,
  69. extendLock,
  70. REDIS_READ_BATCH_SIZE,
  71. releaseLock
  72. )
  73. },
  74. (error, queueSize) => {
  75. if (error) {
  76. OError.tag(error)
  77. }
  78. ErrorRecorder.record(projectId, queueSize, error, callback)
  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, isProjectHistoryEnabled) => {
  170. // We can error before it is known whether project history is enabled
  171. // for the project, so this key has 3 values.
  172. const enabled = isProjectHistoryEnabled || 'unknown'
  173. // This metrics key tries to convet that processing is not atomic.
  174. // Some updates may have been processed even if there was an error.
  175. const success = error != null ? 'with-error' : 'without-error'
  176. metrics.gauge(`updates.${enabled}.${success}`, queueSize)
  177. metrics.count(`updates.${enabled}.${success}`, queueSize)
  178. callback(error, queueSize)
  179. }
  180. )
  181. } else {
  182. logger.debug({ projectId }, 'no updates to process')
  183. callback(null, queueSize)
  184. }
  185. })
  186. }
  187. function _countAndProcessUpdates(...args) {
  188. _mocks._countAndProcessUpdates(...args)
  189. }
  190. function _processUpdatesBatch(projectId, updates, extendLock, callback) {
  191. // If the project doesn't have a history then we can bail out here
  192. _getHistoryId(projectId, updates, (error, historyId) => {
  193. if (error != null) {
  194. return callback(OError.tag(error))
  195. }
  196. if (historyId == null) {
  197. logger.debug(
  198. { projectId },
  199. 'discarding updates as project does not use history'
  200. )
  201. return callback(null, PROJECT_HISTORY.NOT_ENABLED)
  202. }
  203. _processUpdates(projectId, historyId, updates, extendLock, error => {
  204. if (error != null) {
  205. return callback(OError.tag(error), PROJECT_HISTORY.ENABLED)
  206. }
  207. callback(null, PROJECT_HISTORY.ENABLED)
  208. })
  209. })
  210. }
  211. export function _getHistoryId(projectId, updates, callback) {
  212. let idFromUpdates = null
  213. // check that all updates have the same history id
  214. for (const update of updates) {
  215. if (update.projectHistoryId != null) {
  216. if (idFromUpdates == null) {
  217. idFromUpdates = update.projectHistoryId.toString()
  218. } else if (idFromUpdates !== update.projectHistoryId.toString()) {
  219. metrics.inc('updates.batches.project-history-id.inconsistent-update')
  220. logger.warn(
  221. {
  222. projectId,
  223. updates,
  224. idFromUpdates,
  225. currentId: update.projectHistoryId,
  226. },
  227. 'inconsistent project history id between updates'
  228. )
  229. return callback(
  230. new OError('inconsistent project history id between updates')
  231. )
  232. }
  233. }
  234. }
  235. WebApiManager.getHistoryId(projectId, (error, idFromWeb, cached) => {
  236. if (error != null && idFromUpdates != null) {
  237. // present only on updates
  238. // 404s from web are an error
  239. metrics.inc('updates.batches.project-history-id.from-updates')
  240. return callback(null, idFromUpdates)
  241. } else if (error != null) {
  242. return callback(OError.tag(error))
  243. }
  244. if (idFromWeb == null && idFromUpdates == null) {
  245. // present on neither web nor updates
  246. callback(null, null)
  247. } else if (idFromWeb != null && idFromUpdates == null) {
  248. // present only on web
  249. metrics.inc('updates.batches.project-history-id.from-web')
  250. callback(null, idFromWeb)
  251. } else if (idFromWeb == null && idFromUpdates != null) {
  252. // present only on updates
  253. metrics.inc('updates.batches.project-history-id.from-updates')
  254. callback(null, idFromUpdates)
  255. } else if (idFromWeb.toString() !== idFromUpdates.toString()) {
  256. // inconsistent between web and updates
  257. metrics.inc('updates.batches.project-history-id.inconsistent-with-web')
  258. logger.warn(
  259. {
  260. projectId,
  261. idFromWeb,
  262. idFromUpdates,
  263. idWasCached: cached,
  264. updates,
  265. },
  266. 'inconsistent project history id between updates and web'
  267. )
  268. callback(
  269. new OError('inconsistent project history id between updates and web')
  270. )
  271. } else {
  272. // the same on web and updates
  273. metrics.inc('updates.batches.project-history-id.from-updates')
  274. callback(null, idFromWeb)
  275. }
  276. })
  277. }
  278. function _handleOpsOutOfOrderError(projectId, projectHistoryId, err, ...rest) {
  279. const adjustedLength = Math.max(rest.length, 1)
  280. const results = rest.slice(0, adjustedLength - 1)
  281. const callback = rest[adjustedLength - 1]
  282. ErrorRecorder.getFailureRecord(projectId, (error, failureRecord) => {
  283. if (error != null) {
  284. return callback(error)
  285. }
  286. // Bypass ops-out-of-order errors in the stored chunk when in forceDebug mode
  287. if (failureRecord != null && failureRecord.forceDebug === true) {
  288. logger.warn(
  289. { projectId, projectHistoryId },
  290. 'ops out of order in chunk, forced continue'
  291. )
  292. callback(null, ...results) // return results without error
  293. } else {
  294. logger.warn(
  295. { projectId, projectHistoryId },
  296. 'ops out of order in chunk, returning error'
  297. )
  298. callback(err, ...results)
  299. }
  300. })
  301. }
  302. function _getMostRecentVersionWithDebug(projectId, projectHistoryId, callback) {
  303. HistoryStoreManager.getMostRecentVersion(
  304. projectId,
  305. projectHistoryId,
  306. (err, ...results) => {
  307. if (err instanceof Errors.OpsOutOfOrderError) {
  308. _handleOpsOutOfOrderError(
  309. projectId,
  310. projectHistoryId,
  311. err,
  312. ...results,
  313. callback
  314. )
  315. } else {
  316. callback(err, ...results)
  317. }
  318. }
  319. )
  320. }
  321. function _processUpdates(
  322. projectId,
  323. projectHistoryId,
  324. updates,
  325. extendLock,
  326. callback
  327. ) {
  328. const profile = new Profiler('_processUpdates', {
  329. project_id: projectId,
  330. projectHistoryId,
  331. })
  332. // skip updates first if we're in a sync, we might not need to do anything else
  333. SyncManager.skipUpdatesDuringSync(
  334. projectId,
  335. updates,
  336. (error, filteredUpdates, newSyncState) => {
  337. profile.log('skipUpdatesDuringSync')
  338. if (error != null) {
  339. return callback(error)
  340. }
  341. if (filteredUpdates.length === 0) {
  342. // return early if there are no updates to apply
  343. return SyncManager.setResyncState(projectId, newSyncState, callback)
  344. }
  345. // only make request to history service if we have actual updates to process
  346. _getMostRecentVersionWithDebug(
  347. projectId,
  348. projectHistoryId,
  349. (error, baseVersion, projectStructureAndDocVersions) => {
  350. if (projectStructureAndDocVersions == null) {
  351. projectStructureAndDocVersions = { project: null, docs: {} }
  352. }
  353. profile.log('getMostRecentVersion')
  354. if (error != null) {
  355. return callback(error)
  356. }
  357. async.waterfall(
  358. [
  359. cb => {
  360. cb = profile.wrap('expandSyncUpdates', cb)
  361. SyncManager.expandSyncUpdates(
  362. projectId,
  363. projectHistoryId,
  364. filteredUpdates,
  365. extendLock,
  366. cb
  367. )
  368. },
  369. (expandedUpdates, cb) => {
  370. let unappliedUpdates
  371. try {
  372. unappliedUpdates = _skipAlreadyAppliedUpdates(
  373. projectId,
  374. expandedUpdates,
  375. projectStructureAndDocVersions
  376. )
  377. } catch (err) {
  378. return cb(err)
  379. }
  380. profile.log('skipAlreadyAppliedUpdates')
  381. const compressedUpdates =
  382. UpdateCompressor.compressRawUpdates(unappliedUpdates)
  383. const timeTaken = profile
  384. .log('compressRawUpdates')
  385. .getTimeDelta()
  386. if (timeTaken >= 1000) {
  387. logger.debug(
  388. { projectId, updates: unappliedUpdates, timeTaken },
  389. 'slow compression of raw updates'
  390. )
  391. }
  392. cb = profile.wrap('createBlobs', cb)
  393. BlobManager.createBlobsForUpdates(
  394. projectId,
  395. projectHistoryId,
  396. compressedUpdates,
  397. extendLock,
  398. cb
  399. )
  400. },
  401. (updatesWithBlobs, cb) => {
  402. cb = profile.wrap('convertToChanges', cb)
  403. UpdateTranslator.convertToChanges(
  404. projectId,
  405. updatesWithBlobs,
  406. cb
  407. )
  408. },
  409. (changes, cb) => {
  410. changes = changes.map(change => change.toRaw())
  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. }