UpdatesProcessor.js 19 KB

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