UpdatesProcessor.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. const changes = UpdateTranslator.convertToChanges(
  391. projectId,
  392. updatesWithBlobs
  393. ).map(change => change.toRaw())
  394. profile.log('convertToChanges')
  395. let change
  396. const numChanges = changes.length
  397. const byteLength = Buffer.byteLength(
  398. JSON.stringify(changes),
  399. 'utf8'
  400. )
  401. let numOperations = 0
  402. for (change of changes) {
  403. if (change.operations != null) {
  404. numOperations += change.operations.length
  405. }
  406. }
  407. metrics.timing('history-store.request.changes', numChanges, 1)
  408. metrics.timing('history-store.request.bytes', byteLength, 1)
  409. metrics.timing(
  410. 'history-store.request.operations',
  411. numOperations,
  412. 1
  413. )
  414. // thresholds taken from write_latex/main/lib/history_exporter.rb
  415. if (numChanges > 1000) {
  416. metrics.inc('history-store.request.exceeds-threshold.changes')
  417. }
  418. if (byteLength > Math.pow(1024, 2)) {
  419. metrics.inc('history-store.request.exceeds-threshold.bytes')
  420. const changeLengths = changes.map(change =>
  421. Buffer.byteLength(JSON.stringify(change), 'utf8')
  422. )
  423. logger.warn(
  424. { projectId, byteLength, changeLengths },
  425. 'change size exceeds limit'
  426. )
  427. }
  428. cb = profile.wrap('sendChanges', cb)
  429. // this is usually the longest request, so extend the lock before starting it
  430. extendLock(error => {
  431. if (error != null) {
  432. return cb(error)
  433. }
  434. if (changes.length === 0) {
  435. return cb()
  436. } // avoid unnecessary requests to history service
  437. HistoryStoreManager.sendChanges(
  438. projectId,
  439. projectHistoryId,
  440. changes,
  441. baseVersion,
  442. cb
  443. )
  444. })
  445. },
  446. cb => {
  447. cb = profile.wrap('setResyncState', cb)
  448. SyncManager.setResyncState(projectId, newSyncState, cb)
  449. },
  450. ],
  451. error => {
  452. profile.end()
  453. callback(error)
  454. }
  455. )
  456. }
  457. )
  458. }
  459. )
  460. }
  461. _mocks._skipAlreadyAppliedUpdates = (
  462. projectId,
  463. updates,
  464. projectStructureAndDocVersions
  465. ) => {
  466. function alreadySeenProjectVersion(previousProjectStructureVersion, update) {
  467. return (
  468. UpdateTranslator.isProjectStructureUpdate(update) &&
  469. previousProjectStructureVersion != null &&
  470. update.version != null &&
  471. Versions.gte(previousProjectStructureVersion, update.version)
  472. )
  473. }
  474. function alreadySeenDocVersion(previousDocVersions, update) {
  475. if (UpdateTranslator.isTextUpdate(update) && update.v != null) {
  476. const docId = update.doc
  477. return (
  478. previousDocVersions[docId] != null &&
  479. previousDocVersions[docId].v != null &&
  480. Versions.gte(previousDocVersions[docId].v, update.v)
  481. )
  482. } else {
  483. return false
  484. }
  485. }
  486. // check that the incoming updates are in the correct order (we do not
  487. // want to send out of order updates to the history service)
  488. let incomingProjectStructureVersion = null
  489. const incomingDocVersions = {}
  490. for (const update of updates) {
  491. if (alreadySeenProjectVersion(incomingProjectStructureVersion, update)) {
  492. logger.warn(
  493. { projectId, update, incomingProjectStructureVersion },
  494. 'incoming project structure updates are out of order'
  495. )
  496. throw new Errors.OpsOutOfOrderError(
  497. 'project structure version out of order on incoming updates'
  498. )
  499. } else if (alreadySeenDocVersion(incomingDocVersions, update)) {
  500. logger.warn(
  501. { projectId, update, incomingDocVersions },
  502. 'incoming doc updates are out of order'
  503. )
  504. throw new Errors.OpsOutOfOrderError(
  505. 'doc version out of order on incoming updates'
  506. )
  507. }
  508. // update the current project structure and doc versions
  509. if (UpdateTranslator.isProjectStructureUpdate(update)) {
  510. incomingProjectStructureVersion = update.version
  511. } else if (UpdateTranslator.isTextUpdate(update)) {
  512. incomingDocVersions[update.doc] = { v: update.v }
  513. }
  514. }
  515. // discard updates already applied
  516. const updatesToApply = []
  517. const previousProjectStructureVersion = projectStructureAndDocVersions.project
  518. const previousDocVersions = projectStructureAndDocVersions.docs
  519. if (projectStructureAndDocVersions != null) {
  520. const updateProjectVersions = []
  521. for (const update of updates) {
  522. if (update != null && update.version != null) {
  523. updateProjectVersions.push(update.version)
  524. }
  525. }
  526. logger.debug(
  527. { projectId, projectStructureAndDocVersions, updateProjectVersions },
  528. 'comparing updates with existing project versions'
  529. )
  530. }
  531. for (const update of updates) {
  532. if (alreadySeenProjectVersion(previousProjectStructureVersion, update)) {
  533. metrics.inc('updates.discarded_project_structure_version')
  534. logger.debug(
  535. { projectId, update, previousProjectStructureVersion },
  536. 'discarding previously applied project structure update'
  537. )
  538. continue
  539. }
  540. if (alreadySeenDocVersion(previousDocVersions, update)) {
  541. metrics.inc('updates.discarded_doc_version')
  542. logger.debug(
  543. { projectId, update, previousDocVersions },
  544. 'discarding previously applied doc update'
  545. )
  546. continue
  547. }
  548. // remove non-BMP characters from resync updates that have bypassed the normal docupdater flow
  549. _sanitizeUpdate(update)
  550. // if all checks above are ok then accept the update
  551. updatesToApply.push(update)
  552. }
  553. return updatesToApply
  554. }
  555. export function _skipAlreadyAppliedUpdates(...args) {
  556. return _mocks._skipAlreadyAppliedUpdates(...args)
  557. }
  558. function _sanitizeUpdate(update) {
  559. // adapted from docupdater's UpdateManager, we should clean these in docupdater
  560. // too but we already have queues with this problem so we will handle it here
  561. // too for robustness.
  562. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  563. const removeBadChars = str => str.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  564. // clean up any bad chars in resync diffs
  565. if (update.op) {
  566. for (const op of update.op) {
  567. if (op.i != null) {
  568. op.i = removeBadChars(op.i)
  569. }
  570. }
  571. }
  572. // clean up any bad chars in resync new docs
  573. if (update.docLines != null) {
  574. update.docLines = removeBadChars(update.docLines)
  575. }
  576. return update
  577. }
  578. export const promises = {
  579. processUpdatesForProject: promisify(processUpdatesForProject),
  580. }