RangesManager.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // @ts-check
  2. const RangesTracker = require('@overleaf/ranges-tracker')
  3. const logger = require('@overleaf/logger')
  4. const OError = require('@overleaf/o-error')
  5. const Metrics = require('./Metrics')
  6. const _ = require('lodash')
  7. const { isInsert, isDelete, isComment, getDocLength } = require('./Utils')
  8. /**
  9. * @typedef {import('./types').Comment} Comment
  10. * @typedef {import('./types').CommentOp} CommentOp
  11. * @typedef {import('./types').DeleteOp} DeleteOp
  12. * @typedef {import('./types').HistoryCommentOp} HistoryCommentOp
  13. * @typedef {import('./types').HistoryDeleteOp} HistoryDeleteOp
  14. * @typedef {import('./types').HistoryDeleteTrackedChange} HistoryDeleteTrackedChange
  15. * @typedef {import('./types').HistoryInsertOp} HistoryInsertOp
  16. * @typedef {import('./types').HistoryRetainOp} HistoryRetainOp
  17. * @typedef {import('./types').HistoryOp} HistoryOp
  18. * @typedef {import('./types').HistoryUpdate} HistoryUpdate
  19. * @typedef {import('./types').InsertOp} InsertOp
  20. * @typedef {import('./types').Op} Op
  21. * @typedef {import('./types').Ranges} Ranges
  22. * @typedef {import('./types').TrackedChange} TrackedChange
  23. * @typedef {import('./types').Update} Update
  24. */
  25. const RANGE_DELTA_BUCKETS = [0, 1, 2, 3, 4, 5, 10, 20, 50]
  26. const RangesManager = {
  27. MAX_COMMENTS: 500,
  28. MAX_CHANGES: 2000,
  29. /**
  30. * Apply an update to the given doc (lines and ranges) and return new ranges
  31. *
  32. * @param {string} projectId
  33. * @param {string} docId
  34. * @param {Ranges} ranges - ranges before the updates were applied
  35. * @param {Update[]} updates
  36. * @param {string[]} newDocLines - the document lines after the updates were applied
  37. * @param {object} opts
  38. * @param {boolean} [opts.historyRangesSupport] - whether history ranges support is enabled
  39. * @returns {{ newRanges: Ranges, rangesWereCollapsed: boolean, historyUpdates: HistoryUpdate[] }}
  40. */
  41. applyUpdate(projectId, docId, ranges, updates, newDocLines, opts = {}) {
  42. if (ranges == null) {
  43. ranges = {}
  44. }
  45. if (updates == null) {
  46. updates = []
  47. }
  48. const { changes, comments } = _.cloneDeep(ranges)
  49. const rangesTracker = new RangesTracker(changes, comments)
  50. const [emptyRangeCountBefore, totalRangeCountBefore] =
  51. RangesManager._emptyRangesCount(rangesTracker)
  52. const historyUpdates = []
  53. for (const update of updates) {
  54. rangesTracker.track_changes = Boolean(update.meta?.tc)
  55. if (update.meta?.tc) {
  56. rangesTracker.setIdSeed(update.meta.tc)
  57. }
  58. const historyOps = []
  59. for (const op of update.op) {
  60. if (opts.historyRangesSupport) {
  61. historyOps.push(
  62. getHistoryOp(op, rangesTracker.comments, rangesTracker.changes)
  63. )
  64. } else if (isInsert(op) || isDelete(op)) {
  65. historyOps.push(op)
  66. }
  67. rangesTracker.applyOp(op, { user_id: update.meta?.user_id })
  68. }
  69. if (historyOps.length > 0) {
  70. historyUpdates.push({ ...update, op: historyOps })
  71. }
  72. }
  73. if (
  74. rangesTracker.changes?.length > RangesManager.MAX_CHANGES ||
  75. rangesTracker.comments?.length > RangesManager.MAX_COMMENTS
  76. ) {
  77. throw new Error('too many comments or tracked changes')
  78. }
  79. try {
  80. // This is a consistency check that all of our ranges and
  81. // comments still match the corresponding text
  82. rangesTracker.validate(newDocLines.join('\n'))
  83. } catch (err) {
  84. logger.error(
  85. { err, projectId, docId, newDocLines, updates },
  86. 'error validating ranges'
  87. )
  88. throw err
  89. }
  90. const [emptyRangeCountAfter, totalRangeCountAfter] =
  91. RangesManager._emptyRangesCount(rangesTracker)
  92. const rangesWereCollapsed =
  93. emptyRangeCountAfter > emptyRangeCountBefore ||
  94. totalRangeCountAfter + 1 < totalRangeCountBefore // also include the case where multiple ranges were removed
  95. // monitor the change in range count, we may want to snapshot before large decreases
  96. if (totalRangeCountAfter < totalRangeCountBefore) {
  97. Metrics.histogram(
  98. 'range-delta',
  99. totalRangeCountBefore - totalRangeCountAfter,
  100. RANGE_DELTA_BUCKETS,
  101. { status_code: rangesWereCollapsed ? 'saved' : 'unsaved' }
  102. )
  103. }
  104. const newRanges = RangesManager._getRanges(rangesTracker)
  105. logger.debug(
  106. {
  107. projectId,
  108. docId,
  109. changesCount: newRanges.changes?.length,
  110. commentsCount: newRanges.comments?.length,
  111. rangesWereCollapsed,
  112. },
  113. 'applied updates to ranges'
  114. )
  115. return { newRanges, rangesWereCollapsed, historyUpdates }
  116. },
  117. acceptChanges(changeIds, ranges) {
  118. const { changes, comments } = ranges
  119. logger.debug(`accepting ${changeIds.length} changes in ranges`)
  120. const rangesTracker = new RangesTracker(changes, comments)
  121. rangesTracker.removeChangeIds(changeIds)
  122. const newRanges = RangesManager._getRanges(rangesTracker)
  123. return newRanges
  124. },
  125. deleteComment(commentId, ranges) {
  126. const { changes, comments } = ranges
  127. logger.debug({ commentId }, 'deleting comment in ranges')
  128. const rangesTracker = new RangesTracker(changes, comments)
  129. rangesTracker.removeCommentId(commentId)
  130. const newRanges = RangesManager._getRanges(rangesTracker)
  131. return newRanges
  132. },
  133. /**
  134. *
  135. * @param {object} args
  136. * @param {string} args.docId
  137. * @param {string[]} args.acceptedChangeIds
  138. * @param {TrackedChange[]} args.changes
  139. * @param {string} args.pathname
  140. * @param {string} args.projectHistoryId
  141. * @param {string[]} args.lines
  142. */
  143. getHistoryUpdatesForAcceptedChanges({
  144. docId,
  145. acceptedChangeIds,
  146. changes,
  147. pathname,
  148. projectHistoryId,
  149. lines,
  150. }) {
  151. /** @type {(change: TrackedChange) => boolean} */
  152. const isAccepted = change => acceptedChangeIds.includes(change.id)
  153. const historyOps = []
  154. // Keep ops in order of offset, with deletes before inserts
  155. const sortedChanges = changes.slice().sort(function (c1, c2) {
  156. const result = c1.op.p - c2.op.p
  157. if (result !== 0) {
  158. return result
  159. } else if (isInsert(c1.op) && isDelete(c2.op)) {
  160. return 1
  161. } else if (isDelete(c1.op) && isInsert(c2.op)) {
  162. return -1
  163. } else {
  164. return 0
  165. }
  166. })
  167. const docLength = getDocLength(lines)
  168. let historyDocLength = docLength
  169. for (const change of sortedChanges) {
  170. if (isDelete(change.op)) {
  171. historyDocLength += change.op.d.length
  172. }
  173. }
  174. let unacceptedDeletes = 0
  175. for (const change of sortedChanges) {
  176. /** @type {HistoryOp | undefined} */
  177. let op
  178. if (isDelete(change.op)) {
  179. if (isAccepted(change)) {
  180. op = {
  181. p: change.op.p,
  182. d: change.op.d,
  183. }
  184. if (unacceptedDeletes > 0) {
  185. op.hpos = op.p + unacceptedDeletes
  186. }
  187. } else {
  188. unacceptedDeletes += change.op.d.length
  189. }
  190. } else if (isInsert(change.op)) {
  191. if (isAccepted(change)) {
  192. op = {
  193. p: change.op.p,
  194. r: change.op.i,
  195. tracking: {
  196. type: 'none',
  197. userId: change.metadata.user_id,
  198. ts: change.metadata.ts,
  199. },
  200. }
  201. if (unacceptedDeletes > 0) {
  202. op.hpos = op.p + unacceptedDeletes
  203. }
  204. }
  205. }
  206. if (!op) {
  207. continue
  208. }
  209. /** @type {HistoryUpdate} */
  210. const historyOp = {
  211. doc: docId,
  212. op: [op],
  213. meta: {
  214. ...change.metadata,
  215. doc_length: docLength,
  216. pathname,
  217. },
  218. }
  219. if (projectHistoryId) {
  220. historyOp.projectHistoryId = projectHistoryId
  221. }
  222. if (historyOp.meta && historyDocLength !== docLength) {
  223. historyOp.meta.history_doc_length = historyDocLength
  224. }
  225. historyOps.push(historyOp)
  226. if (isDelete(change.op) && isAccepted(change)) {
  227. historyDocLength -= change.op.d.length
  228. }
  229. }
  230. return historyOps
  231. },
  232. _getRanges(rangesTracker) {
  233. // Return the minimal data structure needed, since most documents won't have any
  234. // changes or comments
  235. const response = {}
  236. if (rangesTracker.changes != null && rangesTracker.changes.length > 0) {
  237. response.changes = rangesTracker.changes
  238. }
  239. if (rangesTracker.comments != null && rangesTracker.comments.length > 0) {
  240. response.comments = rangesTracker.comments
  241. }
  242. return response
  243. },
  244. _emptyRangesCount(ranges) {
  245. let emptyCount = 0
  246. let totalCount = 0
  247. for (const comment of ranges.comments || []) {
  248. totalCount++
  249. if (comment.op.c === '') {
  250. emptyCount++
  251. }
  252. }
  253. for (const change of ranges.changes || []) {
  254. totalCount++
  255. if (change.op.i != null) {
  256. if (change.op.i === '') {
  257. emptyCount++
  258. }
  259. }
  260. }
  261. return [emptyCount, totalCount]
  262. },
  263. }
  264. /**
  265. * Calculate ops to be sent to the history system.
  266. *
  267. * @param {Op} op - the editor op
  268. * @param {TrackedChange[]} changes - the list of tracked changes in the
  269. * document before the op is applied. That list, coming from
  270. * RangesTracker is ordered by position.
  271. * @returns {HistoryOp}
  272. */
  273. function getHistoryOp(op, comments, changes, opts = {}) {
  274. if (isInsert(op)) {
  275. return getHistoryOpForInsert(op, comments, changes)
  276. } else if (isDelete(op)) {
  277. return getHistoryOpForDelete(op, changes)
  278. } else if (isComment(op)) {
  279. return getHistoryOpForComment(op, changes)
  280. } else {
  281. throw new OError('Unrecognized op', { op })
  282. }
  283. }
  284. /**
  285. * Calculate history ops for an insert
  286. *
  287. * Inserts are moved forward by tracked deletes placed strictly before the
  288. * op. When an insert is made at the same position as a tracked delete, the
  289. * insert is placed before the tracked delete.
  290. *
  291. * We also add a commentIds property when inserts are made inside a comment.
  292. * The current behaviour is to include the insert in the comment only if the
  293. * insert is made strictly inside the comment. Inserts made at the edges are
  294. * not included in the comment.
  295. *
  296. * @param {InsertOp} op
  297. * @param {Comment[]} comments
  298. * @param {TrackedChange[]} changes
  299. * @returns {HistoryInsertOp}
  300. */
  301. function getHistoryOpForInsert(op, comments, changes) {
  302. let hpos = op.p
  303. let trackedDeleteRejection = false
  304. const commentIds = new Set()
  305. for (const comment of comments) {
  306. if (comment.op.p < op.p && op.p < comment.op.p + comment.op.c.length) {
  307. // Insert is inside the comment; add the comment id
  308. commentIds.add(comment.op.t)
  309. }
  310. }
  311. for (const change of changes) {
  312. if (!isDelete(change.op)) {
  313. // We're only interested in tracked deletes
  314. continue
  315. }
  316. if (change.op.p < op.p) {
  317. // Tracked delete is before the op. Move the op forward.
  318. hpos += change.op.d.length
  319. } else if (change.op.p === op.p) {
  320. // Tracked delete is at the same position as the op. The insert comes before
  321. // the tracked delete so it doesn't move.
  322. if (op.u && change.op.d.startsWith(op.i)) {
  323. // We're undoing and the insert matches the start of the tracked
  324. // delete. RangesManager treats this as a tracked delete rejection. We
  325. // will note this in the op so that project-history can take the
  326. // appropriate action.
  327. trackedDeleteRejection = true
  328. }
  329. } else {
  330. // Tracked delete is after the insert. Tracked deletes are ordered, so
  331. // we know that all subsequent tracked deletes will be after the insert
  332. // and we can bail out.
  333. break
  334. }
  335. }
  336. /** @type {HistoryInsertOp} */
  337. const historyOp = { ...op }
  338. if (commentIds.size > 0) {
  339. historyOp.commentIds = Array.from(commentIds)
  340. }
  341. if (hpos !== op.p) {
  342. historyOp.hpos = hpos
  343. }
  344. if (trackedDeleteRejection) {
  345. historyOp.trackedDeleteRejection = true
  346. }
  347. return historyOp
  348. }
  349. /**
  350. * Calculate history op for a delete
  351. *
  352. * Deletes are moved forward by tracked deletes placed before or at the position of the
  353. * op. If a tracked delete is inside the delete, the delete is split in parts
  354. * so that characters are deleted around the tracked delete, but the tracked
  355. * delete itself is not deleted.
  356. *
  357. * @param {DeleteOp} op
  358. * @param {TrackedChange[]} changes
  359. * @returns {HistoryDeleteOp}
  360. */
  361. function getHistoryOpForDelete(op, changes, opts = {}) {
  362. let hpos = op.p
  363. const opEnd = op.p + op.d.length
  364. /** @type HistoryDeleteTrackedChange[] */
  365. const changesInsideDelete = []
  366. for (const change of changes) {
  367. if (change.op.p <= op.p) {
  368. if (isDelete(change.op)) {
  369. // Tracked delete is before or at the position of the incoming delete.
  370. // Move the op forward.
  371. hpos += change.op.d.length
  372. } else if (isInsert(change.op)) {
  373. const changeEnd = change.op.p + change.op.i.length
  374. const endPos = Math.min(changeEnd, opEnd)
  375. if (endPos > op.p) {
  376. // Part of the tracked insert is inside the delete
  377. changesInsideDelete.push({
  378. type: 'insert',
  379. offset: 0,
  380. length: endPos - op.p,
  381. })
  382. }
  383. }
  384. } else if (change.op.p < op.p + op.d.length) {
  385. // Tracked change inside the deleted text. Record it for the history system.
  386. if (isDelete(change.op)) {
  387. changesInsideDelete.push({
  388. type: 'delete',
  389. offset: change.op.p - op.p,
  390. length: change.op.d.length,
  391. })
  392. } else if (isInsert(change.op)) {
  393. changesInsideDelete.push({
  394. type: 'insert',
  395. offset: change.op.p - op.p,
  396. length: Math.min(change.op.i.length, opEnd - change.op.p),
  397. })
  398. }
  399. } else {
  400. // We've seen all tracked changes before or inside the delete
  401. break
  402. }
  403. }
  404. /** @type {HistoryDeleteOp} */
  405. const historyOp = { ...op }
  406. if (hpos !== op.p) {
  407. historyOp.hpos = hpos
  408. }
  409. if (changesInsideDelete.length > 0) {
  410. historyOp.trackedChanges = changesInsideDelete
  411. }
  412. return historyOp
  413. }
  414. /**
  415. * Calculate history ops for a comment
  416. *
  417. * Comments are moved forward by tracked deletes placed before or at the
  418. * position of the op. If a tracked delete is inside the comment, the length of
  419. * the comment is extended to include the tracked delete.
  420. *
  421. * @param {CommentOp} op
  422. * @param {TrackedChange[]} changes
  423. * @returns {HistoryCommentOp}
  424. */
  425. function getHistoryOpForComment(op, changes) {
  426. let hpos = op.p
  427. let hlen = op.c.length
  428. for (const change of changes) {
  429. if (!isDelete(change.op)) {
  430. // We're only interested in tracked deletes
  431. continue
  432. }
  433. if (change.op.p <= op.p) {
  434. // Tracked delete is before or at the position of the incoming comment.
  435. // Move the op forward.
  436. hpos += change.op.d.length
  437. } else if (change.op.p < op.p + op.c.length) {
  438. // Tracked comment inside the comment. Extend the length
  439. hlen += change.op.d.length
  440. } else {
  441. // We've seen all tracked deletes before or inside the comment
  442. break
  443. }
  444. }
  445. /** @type {HistoryCommentOp} */
  446. const historyOp = { ...op }
  447. if (hpos !== op.p) {
  448. historyOp.hpos = hpos
  449. }
  450. if (hlen !== op.c.length) {
  451. historyOp.hlen = hlen
  452. }
  453. return historyOp
  454. }
  455. module.exports = RangesManager