RangesManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. * @import { Comment, CommentOp, InsertOp, DeleteOp, HistoryOp, Op } from './types'
  10. * @import { HistoryCommentOp, HistoryDeleteOp, HistoryInsertOp, HistoryRetainOp } from './types'
  11. * @import { HistoryDeleteTrackedChange, HistoryUpdate, Ranges, TrackedChange, Update } from './types'
  12. */
  13. const RANGE_DELTA_BUCKETS = [0, 1, 2, 3, 4, 5, 10, 20, 50]
  14. const RangesManager = {
  15. MAX_COMMENTS: 500,
  16. MAX_CHANGES: 2000,
  17. /**
  18. * Apply an update to the given doc (lines and ranges) and return new ranges
  19. *
  20. * @param {string} projectId
  21. * @param {string} docId
  22. * @param {Ranges} ranges - ranges before the updates were applied
  23. * @param {Update[]} updates
  24. * @param {string[]} newDocLines - the document lines after the updates were applied
  25. * @param {object} opts
  26. * @param {boolean} [opts.historyRangesSupport] - whether history ranges support is enabled
  27. * @returns {{ newRanges: Ranges, rangesWereCollapsed: boolean, historyUpdates: HistoryUpdate[] }}
  28. */
  29. applyUpdate(projectId, docId, ranges, updates, newDocLines, opts = {}) {
  30. if (ranges == null) {
  31. ranges = {}
  32. }
  33. if (updates == null) {
  34. updates = []
  35. }
  36. const { changes, comments } = _.cloneDeep(ranges)
  37. const rangesTracker = new RangesTracker(changes, comments)
  38. const [emptyRangeCountBefore, totalRangeCountBefore] =
  39. RangesManager._emptyRangesCount(rangesTracker)
  40. const historyUpdates = []
  41. for (const update of updates) {
  42. const trackingChanges = Boolean(update.meta?.tc)
  43. rangesTracker.track_changes = trackingChanges
  44. if (update.meta?.tc) {
  45. rangesTracker.setIdSeed(update.meta.tc)
  46. }
  47. const historyOps = []
  48. for (const op of update.op) {
  49. let croppedCommentOps = []
  50. if (opts.historyRangesSupport) {
  51. historyOps.push(
  52. getHistoryOp(op, rangesTracker.comments, rangesTracker.changes)
  53. )
  54. if (isDelete(op) && trackingChanges) {
  55. // If a tracked delete overlaps a comment, the comment must be
  56. // cropped. The extent of the cropping is calculated before the
  57. // delete is applied, but the cropping operations are applied
  58. // later, after the delete is applied.
  59. croppedCommentOps = getCroppedCommentOps(op, rangesTracker.comments)
  60. }
  61. } else if (isInsert(op) || isDelete(op)) {
  62. historyOps.push(op)
  63. }
  64. rangesTracker.applyOp(op, { user_id: update.meta?.user_id })
  65. if (croppedCommentOps.length > 0) {
  66. historyOps.push(
  67. ...croppedCommentOps.map(op =>
  68. getHistoryOpForComment(op, rangesTracker.changes)
  69. )
  70. )
  71. }
  72. }
  73. if (historyOps.length > 0) {
  74. historyUpdates.push({ ...update, op: historyOps })
  75. }
  76. }
  77. if (
  78. rangesTracker.changes?.length > RangesManager.MAX_CHANGES ||
  79. rangesTracker.comments?.length > RangesManager.MAX_COMMENTS
  80. ) {
  81. throw new Error('too many comments or tracked changes')
  82. }
  83. try {
  84. // This is a consistency check that all of our ranges and
  85. // comments still match the corresponding text
  86. rangesTracker.validate(newDocLines.join('\n'))
  87. } catch (err) {
  88. logger.error(
  89. { err, projectId, docId, newDocLines, updates },
  90. 'error validating ranges'
  91. )
  92. throw err
  93. }
  94. const [emptyRangeCountAfter, totalRangeCountAfter] =
  95. RangesManager._emptyRangesCount(rangesTracker)
  96. const rangesWereCollapsed =
  97. emptyRangeCountAfter > emptyRangeCountBefore ||
  98. totalRangeCountAfter + 1 < totalRangeCountBefore // also include the case where multiple ranges were removed
  99. // monitor the change in range count, we may want to snapshot before large decreases
  100. if (totalRangeCountAfter < totalRangeCountBefore) {
  101. Metrics.histogram(
  102. 'range-delta',
  103. totalRangeCountBefore - totalRangeCountAfter,
  104. RANGE_DELTA_BUCKETS,
  105. { status_code: rangesWereCollapsed ? 'saved' : 'unsaved' }
  106. )
  107. }
  108. const newRanges = RangesManager._getRanges(rangesTracker)
  109. logger.debug(
  110. {
  111. projectId,
  112. docId,
  113. changesCount: newRanges.changes?.length,
  114. commentsCount: newRanges.comments?.length,
  115. rangesWereCollapsed,
  116. },
  117. 'applied updates to ranges'
  118. )
  119. return { newRanges, rangesWereCollapsed, historyUpdates }
  120. },
  121. acceptChanges(changeIds, ranges) {
  122. const { changes, comments } = ranges
  123. logger.debug(`accepting ${changeIds.length} changes in ranges`)
  124. const rangesTracker = new RangesTracker(changes, comments)
  125. rangesTracker.removeChangeIds(changeIds)
  126. const newRanges = RangesManager._getRanges(rangesTracker)
  127. return newRanges
  128. },
  129. deleteComment(commentId, ranges) {
  130. const { changes, comments } = ranges
  131. logger.debug({ commentId }, 'deleting comment in ranges')
  132. const rangesTracker = new RangesTracker(changes, comments)
  133. rangesTracker.removeCommentId(commentId)
  134. const newRanges = RangesManager._getRanges(rangesTracker)
  135. return newRanges
  136. },
  137. /**
  138. *
  139. * @param {object} args
  140. * @param {string} args.docId
  141. * @param {string[]} args.acceptedChangeIds
  142. * @param {TrackedChange[]} args.changes
  143. * @param {string} args.pathname
  144. * @param {string} args.projectHistoryId
  145. * @param {string[]} args.lines
  146. */
  147. getHistoryUpdatesForAcceptedChanges({
  148. docId,
  149. acceptedChangeIds,
  150. changes,
  151. pathname,
  152. projectHistoryId,
  153. lines,
  154. }) {
  155. /** @type {(change: TrackedChange) => boolean} */
  156. const isAccepted = change => acceptedChangeIds.includes(change.id)
  157. const historyOps = []
  158. // Keep ops in order of offset, with deletes before inserts
  159. const sortedChanges = changes.slice().sort(function (c1, c2) {
  160. const result = c1.op.p - c2.op.p
  161. if (result !== 0) {
  162. return result
  163. } else if (isInsert(c1.op) && isDelete(c2.op)) {
  164. return 1
  165. } else if (isDelete(c1.op) && isInsert(c2.op)) {
  166. return -1
  167. } else {
  168. return 0
  169. }
  170. })
  171. const docLength = getDocLength(lines)
  172. let historyDocLength = docLength
  173. for (const change of sortedChanges) {
  174. if (isDelete(change.op)) {
  175. historyDocLength += change.op.d.length
  176. }
  177. }
  178. let unacceptedDeletes = 0
  179. for (const change of sortedChanges) {
  180. /** @type {HistoryOp | undefined} */
  181. let op
  182. if (isDelete(change.op)) {
  183. if (isAccepted(change)) {
  184. op = {
  185. p: change.op.p,
  186. d: change.op.d,
  187. }
  188. if (unacceptedDeletes > 0) {
  189. op.hpos = op.p + unacceptedDeletes
  190. }
  191. } else {
  192. unacceptedDeletes += change.op.d.length
  193. }
  194. } else if (isInsert(change.op)) {
  195. if (isAccepted(change)) {
  196. op = {
  197. p: change.op.p,
  198. r: change.op.i,
  199. tracking: { type: 'none' },
  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. /**
  456. * Return the ops necessary to properly crop comments when a tracked delete is
  457. * received
  458. *
  459. * The editor treats a tracked delete as a proper delete and updates the
  460. * comment range accordingly. The history doesn't do that and remembers the
  461. * extent of the comment in the tracked delete. In order to keep the history
  462. * consistent with the editor, we'll send ops that will crop the comment in
  463. * the history.
  464. *
  465. * @param {DeleteOp} op
  466. * @param {Comment[]} comments
  467. * @returns {CommentOp[]}
  468. */
  469. function getCroppedCommentOps(op, comments) {
  470. const deleteStart = op.p
  471. const deleteLength = op.d.length
  472. const deleteEnd = deleteStart + deleteLength
  473. /** @type {HistoryCommentOp[]} */
  474. const historyCommentOps = []
  475. for (const comment of comments) {
  476. const commentStart = comment.op.p
  477. const commentLength = comment.op.c.length
  478. const commentEnd = commentStart + commentLength
  479. if (deleteStart <= commentStart && deleteEnd > commentStart) {
  480. // The comment overlaps the start of the comment or all of it.
  481. const overlapLength = Math.min(deleteEnd, commentEnd) - commentStart
  482. /** @type {CommentOp} */
  483. const commentOp = {
  484. p: deleteStart,
  485. c: comment.op.c.slice(overlapLength),
  486. t: comment.op.t,
  487. }
  488. if (comment.op.resolved) {
  489. commentOp.resolved = true
  490. }
  491. historyCommentOps.push(commentOp)
  492. } else if (
  493. deleteStart > commentStart &&
  494. deleteStart < commentEnd &&
  495. deleteEnd >= commentEnd
  496. ) {
  497. // The comment overlaps the end of the comment.
  498. const overlapLength = commentEnd - deleteStart
  499. /** @type {CommentOp} */
  500. const commentOp = {
  501. p: commentStart,
  502. c: comment.op.c.slice(0, -overlapLength),
  503. t: comment.op.t,
  504. }
  505. if (comment.op.resolved) {
  506. commentOp.resolved = true
  507. }
  508. historyCommentOps.push(commentOp)
  509. }
  510. }
  511. return historyCommentOps
  512. }
  513. module.exports = RangesManager