UpdateManager.js 11 KB

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