UpdateManager.js 12 KB

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