UpdatesProcessor.js 19 KB

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