UpdatesProcessor.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. // Unconventional callback signature. The caller needs the queue size
  164. // even when an error is thrown in order to record the queue size in
  165. // the projectHistoryFailures collection. We'll have to find another
  166. // way to achieve this when we promisify.
  167. callback(error, queueSize)
  168. }
  169. )
  170. } else {
  171. logger.debug({ projectId }, 'no updates to process')
  172. callback(null, queueSize)
  173. }
  174. })
  175. }
  176. function _countAndProcessUpdates(...args) {
  177. _mocks._countAndProcessUpdates(...args)
  178. }
  179. function _processUpdatesBatch(projectId, updates, extendLock, callback) {
  180. // If the project doesn't have a history then we can bail out here
  181. _getHistoryId(projectId, updates, (error, historyId) => {
  182. if (error != null) {
  183. return callback(OError.tag(error))
  184. }
  185. if (historyId == null) {
  186. logger.debug(
  187. { projectId },
  188. 'discarding updates as project does not use history'
  189. )
  190. return callback()
  191. }
  192. _processUpdates(projectId, historyId, updates, extendLock, error => {
  193. if (error != null) {
  194. return callback(OError.tag(error))
  195. }
  196. callback()
  197. })
  198. })
  199. }
  200. export function _getHistoryId(projectId, updates, callback) {
  201. let idFromUpdates = null
  202. // check that all updates have the same history id
  203. for (const update of updates) {
  204. if (update.projectHistoryId != null) {
  205. if (idFromUpdates == null) {
  206. idFromUpdates = update.projectHistoryId.toString()
  207. } else if (idFromUpdates !== update.projectHistoryId.toString()) {
  208. metrics.inc('updates.batches.project-history-id.inconsistent-update')
  209. logger.warn(
  210. {
  211. projectId,
  212. updates,
  213. idFromUpdates,
  214. currentId: update.projectHistoryId,
  215. },
  216. 'inconsistent project history id between updates'
  217. )
  218. return callback(
  219. new OError('inconsistent project history id between updates')
  220. )
  221. }
  222. }
  223. }
  224. WebApiManager.getHistoryId(projectId, (error, idFromWeb) => {
  225. if (error != null && idFromUpdates != null) {
  226. // present only on updates
  227. // 404s from web are an error
  228. metrics.inc('updates.batches.project-history-id.from-updates')
  229. return callback(null, idFromUpdates)
  230. } else if (error != null) {
  231. return callback(OError.tag(error))
  232. }
  233. if (idFromWeb == null && idFromUpdates == null) {
  234. // present on neither web nor updates
  235. callback(null, null)
  236. } else if (idFromWeb != null && idFromUpdates == null) {
  237. // present only on web
  238. metrics.inc('updates.batches.project-history-id.from-web')
  239. callback(null, idFromWeb)
  240. } else if (idFromWeb == null && idFromUpdates != null) {
  241. // present only on updates
  242. metrics.inc('updates.batches.project-history-id.from-updates')
  243. callback(null, idFromUpdates)
  244. } else if (idFromWeb.toString() !== idFromUpdates.toString()) {
  245. // inconsistent between web and updates
  246. metrics.inc('updates.batches.project-history-id.inconsistent-with-web')
  247. logger.warn(
  248. {
  249. projectId,
  250. idFromWeb,
  251. idFromUpdates,
  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. export 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. let changes
  391. try {
  392. changes = UpdateTranslator.convertToChanges(
  393. projectId,
  394. updatesWithBlobs
  395. ).map(change => change.toRaw())
  396. } catch (err) {
  397. return cb(err)
  398. } finally {
  399. profile.log('convertToChanges')
  400. }
  401. cb(null, changes)
  402. },
  403. (changes, cb) => {
  404. let change
  405. const numChanges = changes.length
  406. const byteLength = Buffer.byteLength(
  407. JSON.stringify(changes),
  408. 'utf8'
  409. )
  410. let numOperations = 0
  411. for (change of changes) {
  412. if (change.operations != null) {
  413. numOperations += change.operations.length
  414. }
  415. }
  416. metrics.timing('history-store.request.changes', numChanges, 1)
  417. metrics.timing('history-store.request.bytes', byteLength, 1)
  418. metrics.timing(
  419. 'history-store.request.operations',
  420. numOperations,
  421. 1
  422. )
  423. // thresholds taken from write_latex/main/lib/history_exporter.rb
  424. if (numChanges > 1000) {
  425. metrics.inc('history-store.request.exceeds-threshold.changes')
  426. }
  427. if (byteLength > Math.pow(1024, 2)) {
  428. metrics.inc('history-store.request.exceeds-threshold.bytes')
  429. const changeLengths = changes.map(change =>
  430. Buffer.byteLength(JSON.stringify(change), 'utf8')
  431. )
  432. logger.warn(
  433. { projectId, byteLength, changeLengths },
  434. 'change size exceeds limit'
  435. )
  436. }
  437. cb = profile.wrap('sendChanges', cb)
  438. // this is usually the longest request, so extend the lock before starting it
  439. extendLock(error => {
  440. if (error != null) {
  441. return cb(error)
  442. }
  443. if (changes.length === 0) {
  444. return cb()
  445. } // avoid unnecessary requests to history service
  446. HistoryStoreManager.sendChanges(
  447. projectId,
  448. projectHistoryId,
  449. changes,
  450. baseVersion,
  451. cb
  452. )
  453. })
  454. },
  455. cb => {
  456. cb = profile.wrap('setResyncState', cb)
  457. SyncManager.setResyncState(projectId, newSyncState, cb)
  458. },
  459. ],
  460. error => {
  461. profile.end()
  462. callback(error)
  463. }
  464. )
  465. }
  466. )
  467. }
  468. )
  469. }
  470. _mocks._skipAlreadyAppliedUpdates = (
  471. projectId,
  472. updates,
  473. projectStructureAndDocVersions
  474. ) => {
  475. function alreadySeenProjectVersion(previousProjectStructureVersion, update) {
  476. return (
  477. UpdateTranslator.isProjectStructureUpdate(update) &&
  478. previousProjectStructureVersion != null &&
  479. update.version != null &&
  480. Versions.gte(previousProjectStructureVersion, update.version)
  481. )
  482. }
  483. function alreadySeenDocVersion(previousDocVersions, update) {
  484. if (UpdateTranslator.isTextUpdate(update) && update.v != null) {
  485. const docId = update.doc
  486. return (
  487. previousDocVersions[docId] != null &&
  488. previousDocVersions[docId].v != null &&
  489. Versions.gte(previousDocVersions[docId].v, update.v)
  490. )
  491. } else {
  492. return false
  493. }
  494. }
  495. // check that the incoming updates are in the correct order (we do not
  496. // want to send out of order updates to the history service)
  497. let incomingProjectStructureVersion = null
  498. const incomingDocVersions = {}
  499. for (const update of updates) {
  500. if (alreadySeenProjectVersion(incomingProjectStructureVersion, update)) {
  501. logger.warn(
  502. { projectId, update, incomingProjectStructureVersion },
  503. 'incoming project structure updates are out of order'
  504. )
  505. throw new Errors.OpsOutOfOrderError(
  506. 'project structure version out of order on incoming updates'
  507. )
  508. } else if (alreadySeenDocVersion(incomingDocVersions, update)) {
  509. logger.warn(
  510. { projectId, update, incomingDocVersions },
  511. 'incoming doc updates are out of order'
  512. )
  513. throw new Errors.OpsOutOfOrderError(
  514. 'doc version out of order on incoming updates'
  515. )
  516. }
  517. // update the current project structure and doc versions
  518. if (UpdateTranslator.isProjectStructureUpdate(update)) {
  519. incomingProjectStructureVersion = update.version
  520. } else if (UpdateTranslator.isTextUpdate(update)) {
  521. incomingDocVersions[update.doc] = { v: update.v }
  522. }
  523. }
  524. // discard updates already applied
  525. const updatesToApply = []
  526. const previousProjectStructureVersion = projectStructureAndDocVersions.project
  527. const previousDocVersions = projectStructureAndDocVersions.docs
  528. if (projectStructureAndDocVersions != null) {
  529. const updateProjectVersions = []
  530. for (const update of updates) {
  531. if (update != null && update.version != null) {
  532. updateProjectVersions.push(update.version)
  533. }
  534. }
  535. logger.debug(
  536. { projectId, projectStructureAndDocVersions, updateProjectVersions },
  537. 'comparing updates with existing project versions'
  538. )
  539. }
  540. for (const update of updates) {
  541. if (alreadySeenProjectVersion(previousProjectStructureVersion, update)) {
  542. metrics.inc('updates.discarded_project_structure_version')
  543. logger.debug(
  544. { projectId, update, previousProjectStructureVersion },
  545. 'discarding previously applied project structure update'
  546. )
  547. continue
  548. }
  549. if (alreadySeenDocVersion(previousDocVersions, update)) {
  550. metrics.inc('updates.discarded_doc_version')
  551. logger.debug(
  552. { projectId, update, previousDocVersions },
  553. 'discarding previously applied doc update'
  554. )
  555. continue
  556. }
  557. // remove non-BMP characters from resync updates that have bypassed the normal docupdater flow
  558. _sanitizeUpdate(update)
  559. // if all checks above are ok then accept the update
  560. updatesToApply.push(update)
  561. }
  562. return updatesToApply
  563. }
  564. export function _skipAlreadyAppliedUpdates(...args) {
  565. return _mocks._skipAlreadyAppliedUpdates(...args)
  566. }
  567. function _sanitizeUpdate(update) {
  568. // adapted from docupdater's UpdateManager, we should clean these in docupdater
  569. // too but we already have queues with this problem so we will handle it here
  570. // too for robustness.
  571. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  572. const removeBadChars = str => str.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  573. // clean up any bad chars in resync diffs
  574. if (update.op) {
  575. for (const op of update.op) {
  576. if (op.i != null) {
  577. op.i = removeBadChars(op.i)
  578. }
  579. }
  580. }
  581. // clean up any bad chars in resync new docs
  582. if (update.docLines != null) {
  583. update.docLines = removeBadChars(update.docLines)
  584. }
  585. return update
  586. }
  587. export const promises = {
  588. processUpdatesForProject: promisify(processUpdatesForProject),
  589. }