UpdateManager.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // @ts-check
  2. const { callbackifyAll } = require('@overleaf/promise-utils')
  3. const LockManager = require('./LockManager')
  4. const RedisManager = require('./RedisManager')
  5. const RealTimeRedisManager = require('./RealTimeRedisManager')
  6. const ShareJsUpdateManager = require('./ShareJsUpdateManager')
  7. const HistoryManager = require('./HistoryManager')
  8. const _ = require('lodash')
  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 UpdateManager = {
  17. async processOutstandingUpdates(projectId, docId) {
  18. const timer = new Metrics.Timer('updateManager.processOutstandingUpdates')
  19. try {
  20. await UpdateManager.fetchAndApplyUpdates(projectId, docId)
  21. timer.done({ status: 'success' })
  22. } catch (err) {
  23. timer.done({ status: 'error' })
  24. throw err
  25. }
  26. },
  27. async processOutstandingUpdatesWithLock(projectId, docId) {
  28. const profile = new Profiler('processOutstandingUpdatesWithLock', {
  29. project_id: projectId,
  30. doc_id: docId,
  31. })
  32. const lockValue = await LockManager.promises.tryLock(docId)
  33. if (lockValue == null) {
  34. return
  35. }
  36. profile.log('tryLock')
  37. try {
  38. await UpdateManager.processOutstandingUpdates(projectId, docId)
  39. profile.log('processOutstandingUpdates')
  40. } finally {
  41. await LockManager.promises.releaseLock(docId, lockValue)
  42. profile.log('releaseLock').end()
  43. }
  44. await UpdateManager.continueProcessingUpdatesWithLock(projectId, docId)
  45. },
  46. async continueProcessingUpdatesWithLock(projectId, docId) {
  47. const length = await RealTimeRedisManager.promises.getUpdatesLength(docId)
  48. if (length > 0) {
  49. await UpdateManager.processOutstandingUpdatesWithLock(projectId, docId)
  50. }
  51. },
  52. async fetchAndApplyUpdates(projectId, docId) {
  53. const profile = new Profiler('fetchAndApplyUpdates', {
  54. project_id: projectId,
  55. doc_id: docId,
  56. })
  57. const updates = await RealTimeRedisManager.promises.getPendingUpdatesForDoc(
  58. docId
  59. )
  60. logger.debug(
  61. { projectId, docId, count: updates.length },
  62. 'processing updates'
  63. )
  64. if (updates.length === 0) {
  65. return
  66. }
  67. profile.log('getPendingUpdatesForDoc')
  68. for (const update of updates) {
  69. await UpdateManager.applyUpdate(projectId, docId, update)
  70. profile.log('applyUpdate')
  71. }
  72. profile.log('async done').end()
  73. },
  74. async applyUpdate(projectId, docId, update) {
  75. const profile = new Profiler('applyUpdate', {
  76. project_id: projectId,
  77. doc_id: docId,
  78. })
  79. UpdateManager._sanitizeUpdate(update)
  80. profile.log('sanitizeUpdate', { sync: true })
  81. try {
  82. let { lines, version, ranges, pathname, projectHistoryId } =
  83. await DocumentManager.promises.getDoc(projectId, docId)
  84. profile.log('getDoc')
  85. if (lines == null || version == null) {
  86. throw new Errors.NotFoundError(`document not found: ${docId}`)
  87. }
  88. const previousVersion = version
  89. const incomingUpdateVersion = update.v
  90. let updatedDocLines, appliedOps
  91. ;({ updatedDocLines, version, appliedOps } =
  92. await ShareJsUpdateManager.promises.applyUpdate(
  93. projectId,
  94. docId,
  95. update,
  96. lines,
  97. version
  98. ))
  99. profile.log('sharejs.applyUpdate', {
  100. // only synchronous when the update applies directly to the
  101. // doc version, otherwise getPreviousDocOps is called.
  102. sync: incomingUpdateVersion === previousVersion,
  103. })
  104. const { newRanges, rangesWereCollapsed } = RangesManager.applyUpdate(
  105. projectId,
  106. docId,
  107. ranges,
  108. appliedOps,
  109. updatedDocLines
  110. )
  111. profile.log('RangesManager.applyUpdate', { sync: true })
  112. UpdateManager._addProjectHistoryMetadataToOps(
  113. appliedOps,
  114. pathname,
  115. projectHistoryId,
  116. lines
  117. )
  118. const projectOpsLength = await RedisManager.promises.updateDocument(
  119. projectId,
  120. docId,
  121. updatedDocLines,
  122. version,
  123. appliedOps,
  124. newRanges,
  125. update.meta
  126. )
  127. profile.log('RedisManager.updateDocument')
  128. HistoryManager.recordAndFlushHistoryOps(
  129. projectId,
  130. appliedOps,
  131. projectOpsLength
  132. )
  133. profile.log('recordAndFlushHistoryOps')
  134. if (rangesWereCollapsed) {
  135. Metrics.inc('doc-snapshot')
  136. logger.debug(
  137. {
  138. projectId,
  139. docId,
  140. previousVersion,
  141. lines,
  142. ranges,
  143. update,
  144. },
  145. 'update collapsed some ranges, snapshotting previous content'
  146. )
  147. // Do this last, since it's a mongo call, and so potentially longest running
  148. // If it overruns the lock, it's ok, since all of our redis work is done
  149. await SnapshotManager.promises.recordSnapshot(
  150. projectId,
  151. docId,
  152. previousVersion,
  153. pathname,
  154. lines,
  155. ranges
  156. )
  157. }
  158. } catch (error) {
  159. RealTimeRedisManager.sendData({
  160. project_id: projectId,
  161. doc_id: docId,
  162. error: error instanceof Error ? error.message : error,
  163. })
  164. profile.log('sendData')
  165. throw error
  166. } finally {
  167. profile.end()
  168. }
  169. },
  170. // lockUpdatesAndDo can't be promisified yet because it expects a
  171. // callback-style function
  172. async lockUpdatesAndDo(method, projectId, docId, ...args) {
  173. const profile = new Profiler('lockUpdatesAndDo', {
  174. project_id: projectId,
  175. doc_id: docId,
  176. })
  177. const lockValue = await LockManager.promises.getLock(docId)
  178. profile.log('getLock')
  179. let responseArgs
  180. try {
  181. await UpdateManager.processOutstandingUpdates(projectId, docId)
  182. profile.log('processOutstandingUpdates')
  183. // TODO: method is still a callback-style function. Change this when promisifying DocumentManager
  184. responseArgs = await new Promise((resolve, reject) => {
  185. method(projectId, docId, ...args, (error, ...responseArgs) => {
  186. if (error) {
  187. reject(error)
  188. } else {
  189. resolve(responseArgs)
  190. }
  191. })
  192. })
  193. profile.log('method')
  194. } finally {
  195. await LockManager.promises.releaseLock(docId, lockValue)
  196. profile.log('releaseLock').end()
  197. }
  198. // We held the lock for a while so updates might have queued up
  199. UpdateManager.continueProcessingUpdatesWithLock(projectId, docId).catch(
  200. err => {
  201. // The processing may fail for invalid user updates.
  202. // This can be very noisy, put them on level DEBUG
  203. // and record a metric.
  204. Metrics.inc('background-processing-updates-error')
  205. logger.debug(
  206. { err, projectId, docId },
  207. 'error processing updates in background'
  208. )
  209. }
  210. )
  211. return responseArgs
  212. },
  213. _sanitizeUpdate(update) {
  214. // In Javascript, characters are 16-bits wide. It does not understand surrogates as characters.
  215. //
  216. // From Wikipedia (http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane):
  217. // "The High Surrogates (U+D800–U+DBFF) and Low Surrogate (U+DC00–U+DFFF) codes are reserved
  218. // for encoding non-BMP characters in UTF-16 by using a pair of 16-bit codes: one High Surrogate
  219. // and one Low Surrogate. A single surrogate code point will never be assigned a character.""
  220. //
  221. // The main offender seems to be \uD835 as a stand alone character, which would be the first
  222. // 16-bit character of a blackboard bold character (http://www.fileformat.info/info/unicode/char/1d400/index.htm).
  223. // Something must be going on client side that is screwing up the encoding and splitting the
  224. // two 16-bit characters so that \uD835 is standalone.
  225. for (const op of update.op || []) {
  226. if (op.i != null) {
  227. // Replace high and low surrogate characters with 'replacement character' (\uFFFD)
  228. op.i = op.i.replace(/[\uD800-\uDFFF]/g, '\uFFFD')
  229. }
  230. }
  231. return update
  232. },
  233. _addProjectHistoryMetadataToOps(updates, pathname, projectHistoryId, lines) {
  234. let docLength = _.reduce(lines, (chars, line) => chars + line.length, 0)
  235. docLength += lines.length - 1 // count newline characters
  236. updates.forEach(function (update) {
  237. update.projectHistoryId = projectHistoryId
  238. if (!update.meta) {
  239. update.meta = {}
  240. }
  241. update.meta.pathname = pathname
  242. update.meta.doc_length = docLength
  243. // Each update may contain multiple ops, i.e.
  244. // [{
  245. // ops: [{i: "foo", p: 4}, {d: "bar", p:8}]
  246. // }, {
  247. // ops: [{d: "baz", p: 40}, {i: "qux", p:8}]
  248. // }]
  249. // We want to include the doc_length at the start of each update,
  250. // before it's ops are applied. However, we need to track any
  251. // changes to it for the next update.
  252. for (const op of update.op) {
  253. if (op.i != null) {
  254. docLength += op.i.length
  255. }
  256. if (op.d != null) {
  257. docLength -= op.d.length
  258. }
  259. }
  260. })
  261. },
  262. }
  263. const CallbackifiedUpdateManager = callbackifyAll(UpdateManager)
  264. module.exports = CallbackifiedUpdateManager
  265. module.exports.promises = UpdateManager
  266. module.exports.lockUpdatesAndDo = function lockUpdatesAndDo(
  267. method,
  268. projectId,
  269. docId,
  270. ...rest
  271. ) {
  272. const adjustedLength = Math.max(rest.length, 1)
  273. const args = rest.slice(0, adjustedLength - 1)
  274. const callback = rest[adjustedLength - 1]
  275. // TODO: During the transition to promises, UpdateManager.lockUpdatesAndDo
  276. // returns the potentially multiple arguments that must be provided to the
  277. // callback in an array.
  278. UpdateManager.lockUpdatesAndDo(method, projectId, docId, ...args)
  279. .then(responseArgs => {
  280. callback(null, ...responseArgs)
  281. })
  282. .catch(err => {
  283. callback(err)
  284. })
  285. }