UpdateManager.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. // @ts-check
  2. const { callbackifyAll } = require('@overleaf/promise-utils')
  3. const LockManager = require('./LockManager')
  4. const RedisManager = require('./RedisManager')
  5. const ProjectHistoryRedisManager = require('./ProjectHistoryRedisManager')
  6. const RealTimeRedisManager = require('./RealTimeRedisManager')
  7. const ShareJsUpdateManager = require('./ShareJsUpdateManager')
  8. const HistoryManager = require('./HistoryManager')
  9. const logger = require('@overleaf/logger')
  10. const Metrics = require('./Metrics')
  11. const Errors = require('./Errors')
  12. const DocumentManager = require('./DocumentManager')
  13. const RangesManager = require('./RangesManager')
  14. const SnapshotManager = require('./SnapshotManager')
  15. const WebApiManager = require('./WebApiManager')
  16. const Profiler = require('./Profiler')
  17. const { isInsert, isDelete, getDocLength, computeDocHash } = require('./Utils')
  18. const HistoryOTUpdateManager = require('./HistoryOTUpdateManager')
  19. /**
  20. * @import { Ranges, Update, HistoryUpdate } from "./types"
  21. */
  22. const UpdateManager = {
  23. async processOutstandingUpdates(projectId, docId) {
  24. const timer = new Metrics.Timer('updateManager.processOutstandingUpdates')
  25. try {
  26. await UpdateManager.fetchAndApplyUpdates(projectId, docId)
  27. timer.done({ status: 'success' })
  28. } catch (err) {
  29. timer.done({ status: 'error' })
  30. throw err
  31. }
  32. },
  33. async processOutstandingUpdatesWithLock(projectId, docId) {
  34. const profile = new Profiler('processOutstandingUpdatesWithLock', {
  35. project_id: projectId,
  36. doc_id: docId,
  37. })
  38. const lockValue = await LockManager.promises.tryLock(docId)
  39. if (lockValue == null) {
  40. return
  41. }
  42. profile.log('tryLock')
  43. try {
  44. await UpdateManager.processOutstandingUpdates(projectId, docId)
  45. profile.log('processOutstandingUpdates')
  46. } finally {
  47. await LockManager.promises.releaseLock(docId, lockValue)
  48. profile.log('releaseLock').end()
  49. }
  50. await UpdateManager.continueProcessingUpdatesWithLock(projectId, docId)
  51. },
  52. async continueProcessingUpdatesWithLock(projectId, docId) {
  53. const length = await RealTimeRedisManager.promises.getUpdatesLength(docId)
  54. if (length > 0) {
  55. await UpdateManager.processOutstandingUpdatesWithLock(projectId, docId)
  56. }
  57. },
  58. async fetchAndApplyUpdates(projectId, docId) {
  59. const profile = new Profiler('fetchAndApplyUpdates', {
  60. project_id: projectId,
  61. doc_id: docId,
  62. })
  63. const updates =
  64. await RealTimeRedisManager.promises.getPendingUpdatesForDoc(docId)
  65. logger.debug(
  66. { projectId, docId, count: updates.length },
  67. 'processing updates'
  68. )
  69. if (updates.length === 0) {
  70. return
  71. }
  72. profile.log('getPendingUpdatesForDoc')
  73. for (const update of updates) {
  74. if (HistoryOTUpdateManager.isHistoryOTEditOperationUpdate(update)) {
  75. await HistoryOTUpdateManager.applyUpdate(projectId, docId, update)
  76. } else {
  77. await UpdateManager.applyUpdate(projectId, docId, update)
  78. }
  79. profile.log('applyUpdate')
  80. }
  81. profile.log('async done').end()
  82. },
  83. /**
  84. * Apply an update to the given document
  85. *
  86. * @param {string} projectId
  87. * @param {string} docId
  88. * @param {Update} update
  89. */
  90. async applyUpdate(projectId, docId, update) {
  91. const profile = new Profiler('applyUpdate', {
  92. project_id: projectId,
  93. doc_id: docId,
  94. })
  95. UpdateManager._sanitizeUpdate(update)
  96. profile.log('sanitizeUpdate', { sync: true })
  97. try {
  98. let {
  99. lines,
  100. version,
  101. ranges,
  102. pathname,
  103. projectHistoryId,
  104. historyRangesSupport,
  105. type,
  106. } = await DocumentManager.promises.getDoc(projectId, docId)
  107. profile.log('getDoc')
  108. if (lines == null || version == null) {
  109. throw new Errors.NotFoundError(`document not found: ${docId}`)
  110. }
  111. if (type !== 'sharejs-text-ot') {
  112. throw new Errors.OTTypeMismatchError(type, 'sharejs-text-ot')
  113. }
  114. const previousVersion = version
  115. const incomingUpdateVersion = update.v
  116. let updatedDocLines, appliedOps
  117. ;({ updatedDocLines, version, appliedOps } =
  118. await ShareJsUpdateManager.promises.applyUpdate(
  119. projectId,
  120. docId,
  121. update,
  122. lines,
  123. version
  124. ))
  125. profile.log('sharejs.applyUpdate', {
  126. // only synchronous when the update applies directly to the
  127. // doc version, otherwise getPreviousDocOps is called.
  128. sync: incomingUpdateVersion === previousVersion,
  129. })
  130. const {
  131. newRanges,
  132. rangesWereCollapsed,
  133. historyUpdates,
  134. removedChangeIds,
  135. } = RangesManager.applyUpdate(
  136. projectId,
  137. docId,
  138. ranges,
  139. appliedOps,
  140. updatedDocLines,
  141. { historyRangesSupport }
  142. )
  143. profile.log('RangesManager.applyUpdate', { sync: true })
  144. await RedisManager.promises.updateDocument(
  145. projectId,
  146. docId,
  147. updatedDocLines,
  148. version,
  149. appliedOps,
  150. newRanges,
  151. update.meta
  152. )
  153. profile.log('RedisManager.updateDocument')
  154. UpdateManager._adjustHistoryUpdatesMetadata(
  155. historyUpdates,
  156. pathname,
  157. projectHistoryId,
  158. lines,
  159. ranges,
  160. updatedDocLines,
  161. historyRangesSupport
  162. )
  163. if (historyUpdates.length > 0) {
  164. Metrics.inc('history-queue', 1, { status: 'project-history' })
  165. try {
  166. const projectOpsLength =
  167. await ProjectHistoryRedisManager.promises.queueOps(
  168. projectId,
  169. ...historyUpdates.map(op => JSON.stringify(op))
  170. )
  171. HistoryManager.recordAndFlushHistoryOps(
  172. projectId,
  173. historyUpdates,
  174. projectOpsLength
  175. )
  176. profile.log('recordAndFlushHistoryOps')
  177. } catch (err) {
  178. // The full project history can re-sync a project in case
  179. // updates went missing.
  180. // Just record the error here and acknowledge the write-op.
  181. Metrics.inc('history-queue-error')
  182. }
  183. }
  184. // applyUpdate is not triggered by accept change operations, so any
  185. // tracked change removed by the ops we just applied was rejected.
  186. // Look up the authors of those rejected changes from the pre-update
  187. // ranges so we can notify web below.
  188. if (removedChangeIds.length > 0) {
  189. const rejectedChangeAuthorIds = (ranges?.changes || [])
  190. .filter(change => removedChangeIds.includes(change.id))
  191. .map(change => change.metadata.user_id)
  192. // Fire-and-forget without awaiting because
  193. // we hold the doc lock here, and the result of the
  194. // notification doesn't affect the update
  195. WebApiManager.promises
  196. .notifyTrackChangesRejected(
  197. projectId,
  198. docId,
  199. rejectedChangeAuthorIds,
  200. update.meta?.user_id
  201. )
  202. .catch(err => {
  203. logger.warn(
  204. { err, projectId, docId, rejectedChangeAuthorIds },
  205. 'failed to notify web of rejected track changes'
  206. )
  207. })
  208. }
  209. if (rangesWereCollapsed) {
  210. Metrics.inc('doc-snapshot')
  211. logger.debug(
  212. {
  213. projectId,
  214. docId,
  215. previousVersion,
  216. lines,
  217. ranges,
  218. update,
  219. },
  220. 'update collapsed some ranges, snapshotting previous content'
  221. )
  222. // Do this last, since it's a mongo call, and so potentially longest running
  223. // If it overruns the lock, it's ok, since all of our redis work is done
  224. await SnapshotManager.promises.recordSnapshot(
  225. projectId,
  226. docId,
  227. previousVersion,
  228. pathname,
  229. lines,
  230. ranges
  231. )
  232. }
  233. } catch (error) {
  234. RealTimeRedisManager.sendData({
  235. project_id: projectId,
  236. doc_id: docId,
  237. error: error instanceof Error ? error.message : error,
  238. })
  239. profile.log('sendData')
  240. throw error
  241. } finally {
  242. profile.end()
  243. }
  244. },
  245. async lockUpdatesAndDo(method, projectId, docId, ...args) {
  246. const profile = new Profiler('lockUpdatesAndDo', {
  247. project_id: projectId,
  248. doc_id: docId,
  249. })
  250. const lockValue = await LockManager.promises.getLock(docId)
  251. profile.log('getLock')
  252. let result
  253. try {
  254. await UpdateManager.processOutstandingUpdates(projectId, docId)
  255. profile.log('processOutstandingUpdates')
  256. result = await method(projectId, docId, ...args)
  257. profile.log('method')
  258. } finally {
  259. await LockManager.promises.releaseLock(docId, lockValue)
  260. profile.log('releaseLock').end()
  261. }
  262. // We held the lock for a while so updates might have queued up
  263. UpdateManager.continueProcessingUpdatesWithLock(projectId, docId).catch(
  264. err => {
  265. // The processing may fail for invalid user updates.
  266. // This can be very noisy, put them on level DEBUG
  267. // and record a metric.
  268. Metrics.inc('background-processing-updates-error')
  269. logger.debug(
  270. { err, projectId, docId },
  271. 'error processing updates in background'
  272. )
  273. }
  274. )
  275. return result
  276. },
  277. _sanitizeUpdate(update) {
  278. // In Javascript, characters are 16-bits wide. It does not understand surrogates as characters.
  279. //
  280. // From Wikipedia (http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane):
  281. // "The High Surrogates (U+D800–U+DBFF) and Low Surrogate (U+DC00–U+DFFF) codes are reserved
  282. // for encoding non-BMP characters in UTF-16 by using a pair of 16-bit codes: one High Surrogate
  283. // and one Low Surrogate. A single surrogate code point will never be assigned a character.""
  284. //
  285. // The main offender seems to be \uD835 as a stand alone character, which would be the first
  286. // 16-bit character of a blackboard bold character (http://www.fileformat.info/info/unicode/char/1d400/index.htm).
  287. // Something must be going on client side that is screwing up the encoding and splitting the
  288. // two 16-bit characters so that \uD835 is standalone.
  289. for (const op of update.op || []) {
  290. if (op.i != null) {
  291. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  292. op.i = op.i.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  293. }
  294. }
  295. return update
  296. },
  297. /**
  298. * Add metadata that will be useful to project history
  299. *
  300. * @param {HistoryUpdate[]} updates
  301. * @param {string} pathname
  302. * @param {string} projectHistoryId
  303. * @param {string[]} lines - document lines before updates were applied
  304. * @param {Ranges} ranges - ranges before updates were applied
  305. * @param {string[]} newLines - document lines after updates were applied
  306. * @param {boolean} historyRangesSupport
  307. */
  308. _adjustHistoryUpdatesMetadata(
  309. updates,
  310. pathname,
  311. projectHistoryId,
  312. lines,
  313. ranges,
  314. newLines,
  315. historyRangesSupport
  316. ) {
  317. let docLength = getDocLength(lines)
  318. let historyDocLength = docLength
  319. for (const change of ranges.changes ?? []) {
  320. if ('d' in change.op) {
  321. historyDocLength += change.op.d.length
  322. }
  323. }
  324. for (const update of updates) {
  325. update.projectHistoryId = projectHistoryId
  326. if (!update.meta) {
  327. update.meta = {}
  328. }
  329. update.meta.pathname = pathname
  330. update.meta.doc_length = docLength
  331. if (historyRangesSupport && historyDocLength !== docLength) {
  332. update.meta.history_doc_length = historyDocLength
  333. }
  334. // Each update may contain multiple ops, i.e.
  335. // [{
  336. // ops: [{i: "foo", p: 4}, {d: "bar", p:8}]
  337. // }, {
  338. // ops: [{d: "baz", p: 40}, {i: "qux", p:8}]
  339. // }]
  340. // We want to include the doc_length at the start of each update,
  341. // before it's ops are applied. However, we need to track any
  342. // changes to it for the next update.
  343. for (const op of update.op) {
  344. if (isInsert(op)) {
  345. docLength += op.i.length
  346. if (!op.trackedDeleteRejection) {
  347. // Tracked delete rejections end up retaining characters rather
  348. // than inserting
  349. historyDocLength += op.i.length
  350. }
  351. }
  352. if (isDelete(op)) {
  353. docLength -= op.d.length
  354. if (update.meta.tc) {
  355. // This is a tracked delete. It will be translated into a retain in
  356. // history, except any enclosed tracked inserts, which will be
  357. // translated into regular deletes.
  358. for (const change of op.trackedChanges ?? []) {
  359. if (change.type === 'insert') {
  360. historyDocLength -= change.length
  361. }
  362. }
  363. } else {
  364. // This is a regular delete. It will be translated to a delete in
  365. // history.
  366. historyDocLength -= op.d.length
  367. }
  368. }
  369. }
  370. if (!historyRangesSupport) {
  371. // Prevent project-history from processing tracked changes
  372. delete update.meta.tc
  373. }
  374. }
  375. if (historyRangesSupport && updates.length > 0) {
  376. const lastUpdate = updates[updates.length - 1]
  377. lastUpdate.meta ??= {}
  378. lastUpdate.meta.doc_hash = computeDocHash(newLines)
  379. }
  380. },
  381. }
  382. module.exports = { ...callbackifyAll(UpdateManager), promises: UpdateManager }