UpdatesProcessor.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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) => {
  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. updates,
  252. },
  253. 'inconsistent project history id between updates and web'
  254. )
  255. callback(
  256. new OError('inconsistent project history id between updates and web')
  257. )
  258. } else {
  259. // the same on web and updates
  260. metrics.inc('updates.batches.project-history-id.from-updates')
  261. callback(null, idFromWeb)
  262. }
  263. })
  264. }
  265. function _handleOpsOutOfOrderError(projectId, projectHistoryId, err, ...rest) {
  266. const adjustedLength = Math.max(rest.length, 1)
  267. const results = rest.slice(0, adjustedLength - 1)
  268. const callback = rest[adjustedLength - 1]
  269. ErrorRecorder.getFailureRecord(projectId, (error, failureRecord) => {
  270. if (error != null) {
  271. return callback(error)
  272. }
  273. // Bypass ops-out-of-order errors in the stored chunk when in forceDebug mode
  274. if (failureRecord != null && failureRecord.forceDebug === true) {
  275. logger.warn(
  276. { projectId, projectHistoryId },
  277. 'ops out of order in chunk, forced continue'
  278. )
  279. callback(null, ...results) // return results without error
  280. } else {
  281. logger.warn(
  282. { projectId, projectHistoryId },
  283. 'ops out of order in chunk, returning error'
  284. )
  285. callback(err, ...results)
  286. }
  287. })
  288. }
  289. function _getMostRecentVersionWithDebug(projectId, projectHistoryId, callback) {
  290. HistoryStoreManager.getMostRecentVersion(
  291. projectId,
  292. projectHistoryId,
  293. (err, ...results) => {
  294. if (err instanceof Errors.OpsOutOfOrderError) {
  295. _handleOpsOutOfOrderError(
  296. projectId,
  297. projectHistoryId,
  298. err,
  299. ...results,
  300. callback
  301. )
  302. } else {
  303. callback(err, ...results)
  304. }
  305. }
  306. )
  307. }
  308. function _processUpdates(
  309. projectId,
  310. projectHistoryId,
  311. updates,
  312. extendLock,
  313. callback
  314. ) {
  315. const profile = new Profiler('_processUpdates', {
  316. project_id: projectId,
  317. projectHistoryId,
  318. })
  319. // skip updates first if we're in a sync, we might not need to do anything else
  320. SyncManager.skipUpdatesDuringSync(
  321. projectId,
  322. updates,
  323. (error, filteredUpdates, newSyncState) => {
  324. profile.log('skipUpdatesDuringSync')
  325. if (error != null) {
  326. return callback(error)
  327. }
  328. if (filteredUpdates.length === 0) {
  329. // return early if there are no updates to apply
  330. return SyncManager.setResyncState(projectId, newSyncState, callback)
  331. }
  332. // only make request to history service if we have actual updates to process
  333. _getMostRecentVersionWithDebug(
  334. projectId,
  335. projectHistoryId,
  336. (error, baseVersion, projectStructureAndDocVersions) => {
  337. if (projectStructureAndDocVersions == null) {
  338. projectStructureAndDocVersions = { project: null, docs: {} }
  339. }
  340. profile.log('getMostRecentVersion')
  341. if (error != null) {
  342. return callback(error)
  343. }
  344. async.waterfall(
  345. [
  346. cb => {
  347. cb = profile.wrap('expandSyncUpdates', cb)
  348. SyncManager.expandSyncUpdates(
  349. projectId,
  350. projectHistoryId,
  351. filteredUpdates,
  352. extendLock,
  353. cb
  354. )
  355. },
  356. (expandedUpdates, cb) => {
  357. let unappliedUpdates
  358. try {
  359. unappliedUpdates = _skipAlreadyAppliedUpdates(
  360. projectId,
  361. expandedUpdates,
  362. projectStructureAndDocVersions
  363. )
  364. } catch (err) {
  365. return cb(err)
  366. }
  367. profile.log('skipAlreadyAppliedUpdates')
  368. const compressedUpdates =
  369. UpdateCompressor.compressRawUpdates(unappliedUpdates)
  370. const timeTaken = profile
  371. .log('compressRawUpdates')
  372. .getTimeDelta()
  373. if (timeTaken >= 1000) {
  374. logger.debug(
  375. { projectId, updates: unappliedUpdates, timeTaken },
  376. 'slow compression of raw updates'
  377. )
  378. }
  379. cb = profile.wrap('createBlobs', cb)
  380. BlobManager.createBlobsForUpdates(
  381. projectId,
  382. projectHistoryId,
  383. compressedUpdates,
  384. extendLock,
  385. cb
  386. )
  387. },
  388. (updatesWithBlobs, cb) => {
  389. const changes = UpdateTranslator.convertToChanges(
  390. projectId,
  391. updatesWithBlobs
  392. ).map(change => change.toRaw())
  393. profile.log('convertToChanges')
  394. let change
  395. const numChanges = changes.length
  396. const byteLength = Buffer.byteLength(
  397. JSON.stringify(changes),
  398. 'utf8'
  399. )
  400. let numOperations = 0
  401. for (change of changes) {
  402. if (change.operations != null) {
  403. numOperations += change.operations.length
  404. }
  405. }
  406. metrics.timing('history-store.request.changes', numChanges, 1)
  407. metrics.timing('history-store.request.bytes', byteLength, 1)
  408. metrics.timing(
  409. 'history-store.request.operations',
  410. numOperations,
  411. 1
  412. )
  413. // thresholds taken from write_latex/main/lib/history_exporter.rb
  414. if (numChanges > 1000) {
  415. metrics.inc('history-store.request.exceeds-threshold.changes')
  416. }
  417. if (byteLength > Math.pow(1024, 2)) {
  418. metrics.inc('history-store.request.exceeds-threshold.bytes')
  419. const changeLengths = changes.map(change =>
  420. Buffer.byteLength(JSON.stringify(change), 'utf8')
  421. )
  422. logger.warn(
  423. { projectId, byteLength, changeLengths },
  424. 'change size exceeds limit'
  425. )
  426. }
  427. cb = profile.wrap('sendChanges', cb)
  428. // this is usually the longest request, so extend the lock before starting it
  429. extendLock(error => {
  430. if (error != null) {
  431. return cb(error)
  432. }
  433. if (changes.length === 0) {
  434. return cb()
  435. } // avoid unnecessary requests to history service
  436. HistoryStoreManager.sendChanges(
  437. projectId,
  438. projectHistoryId,
  439. changes,
  440. baseVersion,
  441. cb
  442. )
  443. })
  444. },
  445. cb => {
  446. cb = profile.wrap('setResyncState', cb)
  447. SyncManager.setResyncState(projectId, newSyncState, cb)
  448. },
  449. ],
  450. error => {
  451. profile.end()
  452. callback(error)
  453. }
  454. )
  455. }
  456. )
  457. }
  458. )
  459. }
  460. _mocks._skipAlreadyAppliedUpdates = (
  461. projectId,
  462. updates,
  463. projectStructureAndDocVersions
  464. ) => {
  465. function alreadySeenProjectVersion(previousProjectStructureVersion, update) {
  466. return (
  467. UpdateTranslator.isProjectStructureUpdate(update) &&
  468. previousProjectStructureVersion != null &&
  469. update.version != null &&
  470. Versions.gte(previousProjectStructureVersion, update.version)
  471. )
  472. }
  473. function alreadySeenDocVersion(previousDocVersions, update) {
  474. if (UpdateTranslator.isTextUpdate(update) && update.v != null) {
  475. const docId = update.doc
  476. return (
  477. previousDocVersions[docId] != null &&
  478. previousDocVersions[docId].v != null &&
  479. Versions.gte(previousDocVersions[docId].v, update.v)
  480. )
  481. } else {
  482. return false
  483. }
  484. }
  485. // check that the incoming updates are in the correct order (we do not
  486. // want to send out of order updates to the history service)
  487. let incomingProjectStructureVersion = null
  488. const incomingDocVersions = {}
  489. for (const update of updates) {
  490. if (alreadySeenProjectVersion(incomingProjectStructureVersion, update)) {
  491. logger.warn(
  492. { projectId, update, incomingProjectStructureVersion },
  493. 'incoming project structure updates are out of order'
  494. )
  495. throw new Errors.OpsOutOfOrderError(
  496. 'project structure version out of order on incoming updates'
  497. )
  498. } else if (alreadySeenDocVersion(incomingDocVersions, update)) {
  499. logger.warn(
  500. { projectId, update, incomingDocVersions },
  501. 'incoming doc updates are out of order'
  502. )
  503. throw new Errors.OpsOutOfOrderError(
  504. 'doc version out of order on incoming updates'
  505. )
  506. }
  507. // update the current project structure and doc versions
  508. if (UpdateTranslator.isProjectStructureUpdate(update)) {
  509. incomingProjectStructureVersion = update.version
  510. } else if (UpdateTranslator.isTextUpdate(update)) {
  511. incomingDocVersions[update.doc] = { v: update.v }
  512. }
  513. }
  514. // discard updates already applied
  515. const updatesToApply = []
  516. const previousProjectStructureVersion = projectStructureAndDocVersions.project
  517. const previousDocVersions = projectStructureAndDocVersions.docs
  518. if (projectStructureAndDocVersions != null) {
  519. const updateProjectVersions = []
  520. for (const update of updates) {
  521. if (update != null && update.version != null) {
  522. updateProjectVersions.push(update.version)
  523. }
  524. }
  525. logger.debug(
  526. { projectId, projectStructureAndDocVersions, updateProjectVersions },
  527. 'comparing updates with existing project versions'
  528. )
  529. }
  530. for (const update of updates) {
  531. if (alreadySeenProjectVersion(previousProjectStructureVersion, update)) {
  532. metrics.inc('updates.discarded_project_structure_version')
  533. logger.debug(
  534. { projectId, update, previousProjectStructureVersion },
  535. 'discarding previously applied project structure update'
  536. )
  537. continue
  538. }
  539. if (alreadySeenDocVersion(previousDocVersions, update)) {
  540. metrics.inc('updates.discarded_doc_version')
  541. logger.debug(
  542. { projectId, update, previousDocVersions },
  543. 'discarding previously applied doc update'
  544. )
  545. continue
  546. }
  547. // remove non-BMP characters from resync updates that have bypassed the normal docupdater flow
  548. _sanitizeUpdate(update)
  549. // if all checks above are ok then accept the update
  550. updatesToApply.push(update)
  551. }
  552. return updatesToApply
  553. }
  554. export function _skipAlreadyAppliedUpdates(...args) {
  555. return _mocks._skipAlreadyAppliedUpdates(...args)
  556. }
  557. function _sanitizeUpdate(update) {
  558. // adapted from docupdater's UpdateManager, we should clean these in docupdater
  559. // too but we already have queues with this problem so we will handle it here
  560. // too for robustness.
  561. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  562. const removeBadChars = str => str.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  563. // clean up any bad chars in resync diffs
  564. if (update.op) {
  565. for (const op of update.op) {
  566. if (op.i != null) {
  567. op.i = removeBadChars(op.i)
  568. }
  569. }
  570. }
  571. // clean up any bad chars in resync new docs
  572. if (update.docLines != null) {
  573. update.docLines = removeBadChars(update.docLines)
  574. }
  575. return update
  576. }
  577. export const promises = {
  578. processUpdatesForProject: promisify(processUpdatesForProject),
  579. }