UpdateManager.js 12 KB

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