RangesManager.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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(projectId, docId, changeIds, ranges, lines) {
  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. ts: Date.now(),
  216. doc_length: docLength,
  217. pathname,
  218. },
  219. }
  220. if (projectHistoryId) {
  221. historyOp.projectHistoryId = projectHistoryId
  222. }
  223. if (historyOp.meta && historyDocLength !== docLength) {
  224. historyOp.meta.history_doc_length = historyDocLength
  225. }
  226. historyOps.push(historyOp)
  227. if (isDelete(change.op) && isAccepted(change)) {
  228. historyDocLength -= change.op.d.length
  229. }
  230. }
  231. return historyOps
  232. },
  233. _getRanges(rangesTracker) {
  234. // Return the minimal data structure needed, since most documents won't have any
  235. // changes or comments
  236. const response = {}
  237. if (rangesTracker.changes != null && rangesTracker.changes.length > 0) {
  238. response.changes = rangesTracker.changes
  239. }
  240. if (rangesTracker.comments != null && rangesTracker.comments.length > 0) {
  241. response.comments = rangesTracker.comments
  242. }
  243. return response
  244. },
  245. _emptyRangesCount(ranges) {
  246. let emptyCount = 0
  247. let totalCount = 0
  248. for (const comment of ranges.comments || []) {
  249. totalCount++
  250. if (comment.op.c === '') {
  251. emptyCount++
  252. }
  253. }
  254. for (const change of ranges.changes || []) {
  255. totalCount++
  256. if (change.op.i != null) {
  257. if (change.op.i === '') {
  258. emptyCount++
  259. }
  260. }
  261. }
  262. return [emptyCount, totalCount]
  263. },
  264. }
  265. /**
  266. * Calculate ops to be sent to the history system.
  267. *
  268. * @param {Op} op - the editor op
  269. * @param {TrackedChange[]} changes - the list of tracked changes in the
  270. * document before the op is applied. That list, coming from
  271. * RangesTracker is ordered by position.
  272. * @returns {HistoryOp}
  273. */
  274. function getHistoryOp(op, comments, changes, opts = {}) {
  275. if (isInsert(op)) {
  276. return getHistoryOpForInsert(op, comments, changes)
  277. } else if (isDelete(op)) {
  278. return getHistoryOpForDelete(op, changes)
  279. } else if (isComment(op)) {
  280. return getHistoryOpForComment(op, changes)
  281. } else {
  282. throw new OError('Unrecognized op', { op })
  283. }
  284. }
  285. /**
  286. * Calculate history ops for an insert
  287. *
  288. * Inserts are moved forward by tracked deletes placed strictly before the
  289. * op. When an insert is made at the same position as a tracked delete, the
  290. * insert is placed before the tracked delete.
  291. *
  292. * We also add a commentIds property when inserts are made inside a comment.
  293. * The current behaviour is to include the insert in the comment only if the
  294. * insert is made strictly inside the comment. Inserts made at the edges are
  295. * not included in the comment.
  296. *
  297. * @param {InsertOp} op
  298. * @param {Comment[]} comments
  299. * @param {TrackedChange[]} changes
  300. * @returns {HistoryInsertOp}
  301. */
  302. function getHistoryOpForInsert(op, comments, changes) {
  303. let hpos = op.p
  304. let trackedDeleteRejection = false
  305. const commentIds = new Set()
  306. for (const comment of comments) {
  307. if (comment.op.p < op.p && op.p < comment.op.p + comment.op.c.length) {
  308. // Insert is inside the comment; add the comment id
  309. commentIds.add(comment.op.t)
  310. }
  311. }
  312. // If it's determined that the op is a tracked delete rejection, we have to
  313. // calculate its proper history position. If multiple tracked deletes are
  314. // found at the same position as the insert, the tracked deletes that come
  315. // before the tracked delete that was actually rejected offset the history
  316. // position.
  317. let trackedDeleteRejectionOffset = 0
  318. for (const change of changes) {
  319. if (!isDelete(change.op)) {
  320. // We're only interested in tracked deletes
  321. continue
  322. }
  323. if (change.op.p < op.p) {
  324. // Tracked delete is before the op. Move the op forward.
  325. hpos += change.op.d.length
  326. } else if (change.op.p === op.p) {
  327. // Tracked delete is at the same position as the op.
  328. if (op.u && change.op.d.startsWith(op.i)) {
  329. // We're undoing and the insert matches the start of the tracked
  330. // delete. RangesManager treats this as a tracked delete rejection. We
  331. // will note this in the op so that project-history can take the
  332. // appropriate action.
  333. trackedDeleteRejection = true
  334. // The history must be updated to take into account all preceding
  335. // tracked deletes at the same position
  336. hpos += trackedDeleteRejectionOffset
  337. // No need to continue. All subsequent tracked deletes are after the
  338. // insert.
  339. break
  340. } else {
  341. // This tracked delete does not match the insert. Note its length in
  342. // case we find a tracked delete that matches later.
  343. trackedDeleteRejectionOffset += change.op.d.length
  344. }
  345. } else {
  346. // Tracked delete is after the insert. Tracked deletes are ordered, so
  347. // we know that all subsequent tracked deletes will be after the insert
  348. // and we can bail out.
  349. break
  350. }
  351. }
  352. /** @type {HistoryInsertOp} */
  353. const historyOp = { ...op }
  354. if (commentIds.size > 0) {
  355. historyOp.commentIds = Array.from(commentIds)
  356. }
  357. if (hpos !== op.p) {
  358. historyOp.hpos = hpos
  359. }
  360. if (trackedDeleteRejection) {
  361. historyOp.trackedDeleteRejection = true
  362. }
  363. return historyOp
  364. }
  365. /**
  366. * Calculate history op for a delete
  367. *
  368. * Deletes are moved forward by tracked deletes placed before or at the position of the
  369. * op. If a tracked delete is inside the delete, the delete is split in parts
  370. * so that characters are deleted around the tracked delete, but the tracked
  371. * delete itself is not deleted.
  372. *
  373. * @param {DeleteOp} op
  374. * @param {TrackedChange[]} changes
  375. * @returns {HistoryDeleteOp}
  376. */
  377. function getHistoryOpForDelete(op, changes, opts = {}) {
  378. let hpos = op.p
  379. const opEnd = op.p + op.d.length
  380. /** @type HistoryDeleteTrackedChange[] */
  381. const changesInsideDelete = []
  382. for (const change of changes) {
  383. if (change.op.p <= op.p) {
  384. if (isDelete(change.op)) {
  385. // Tracked delete is before or at the position of the incoming delete.
  386. // Move the op forward.
  387. hpos += change.op.d.length
  388. } else if (isInsert(change.op)) {
  389. const changeEnd = change.op.p + change.op.i.length
  390. const endPos = Math.min(changeEnd, opEnd)
  391. if (endPos > op.p) {
  392. // Part of the tracked insert is inside the delete
  393. changesInsideDelete.push({
  394. type: 'insert',
  395. offset: 0,
  396. length: endPos - op.p,
  397. })
  398. }
  399. }
  400. } else if (change.op.p < op.p + op.d.length) {
  401. // Tracked change inside the deleted text. Record it for the history system.
  402. if (isDelete(change.op)) {
  403. changesInsideDelete.push({
  404. type: 'delete',
  405. offset: change.op.p - op.p,
  406. length: change.op.d.length,
  407. })
  408. } else if (isInsert(change.op)) {
  409. changesInsideDelete.push({
  410. type: 'insert',
  411. offset: change.op.p - op.p,
  412. length: Math.min(change.op.i.length, opEnd - change.op.p),
  413. })
  414. }
  415. } else {
  416. // We've seen all tracked changes before or inside the delete
  417. break
  418. }
  419. }
  420. /** @type {HistoryDeleteOp} */
  421. const historyOp = { ...op }
  422. if (hpos !== op.p) {
  423. historyOp.hpos = hpos
  424. }
  425. if (changesInsideDelete.length > 0) {
  426. historyOp.trackedChanges = changesInsideDelete
  427. }
  428. return historyOp
  429. }
  430. /**
  431. * Calculate history ops for a comment
  432. *
  433. * Comments are moved forward by tracked deletes placed before or at the
  434. * position of the op. If a tracked delete is inside the comment, the length of
  435. * the comment is extended to include the tracked delete.
  436. *
  437. * @param {CommentOp} op
  438. * @param {TrackedChange[]} changes
  439. * @returns {HistoryCommentOp}
  440. */
  441. function getHistoryOpForComment(op, changes) {
  442. let hpos = op.p
  443. let hlen = op.c.length
  444. for (const change of changes) {
  445. if (!isDelete(change.op)) {
  446. // We're only interested in tracked deletes
  447. continue
  448. }
  449. if (change.op.p <= op.p) {
  450. // Tracked delete is before or at the position of the incoming comment.
  451. // Move the op forward.
  452. hpos += change.op.d.length
  453. } else if (change.op.p < op.p + op.c.length) {
  454. // Tracked comment inside the comment. Extend the length
  455. hlen += change.op.d.length
  456. } else {
  457. // We've seen all tracked deletes before or inside the comment
  458. break
  459. }
  460. }
  461. /** @type {HistoryCommentOp} */
  462. const historyOp = { ...op }
  463. if (hpos !== op.p) {
  464. historyOp.hpos = hpos
  465. }
  466. if (hlen !== op.c.length) {
  467. historyOp.hlen = hlen
  468. }
  469. return historyOp
  470. }
  471. /**
  472. * Return the ops necessary to properly crop comments when a tracked delete is
  473. * received
  474. *
  475. * The editor treats a tracked delete as a proper delete and updates the
  476. * comment range accordingly. The history doesn't do that and remembers the
  477. * extent of the comment in the tracked delete. In order to keep the history
  478. * consistent with the editor, we'll send ops that will crop the comment in
  479. * the history.
  480. *
  481. * @param {DeleteOp} op
  482. * @param {Comment[]} comments
  483. * @returns {CommentOp[]}
  484. */
  485. function getCroppedCommentOps(op, comments) {
  486. const deleteStart = op.p
  487. const deleteLength = op.d.length
  488. const deleteEnd = deleteStart + deleteLength
  489. /** @type {HistoryCommentOp[]} */
  490. const historyCommentOps = []
  491. for (const comment of comments) {
  492. const commentStart = comment.op.p
  493. const commentLength = comment.op.c.length
  494. const commentEnd = commentStart + commentLength
  495. if (deleteStart <= commentStart && deleteEnd > commentStart) {
  496. // The comment overlaps the start of the comment or all of it.
  497. const overlapLength = Math.min(deleteEnd, commentEnd) - commentStart
  498. /** @type {CommentOp} */
  499. const commentOp = {
  500. p: deleteStart,
  501. c: comment.op.c.slice(overlapLength),
  502. t: comment.op.t,
  503. }
  504. if (comment.op.resolved) {
  505. commentOp.resolved = true
  506. }
  507. historyCommentOps.push(commentOp)
  508. } else if (
  509. deleteStart > commentStart &&
  510. deleteStart < commentEnd &&
  511. deleteEnd >= commentEnd
  512. ) {
  513. // The comment overlaps the end of the comment.
  514. const overlapLength = commentEnd - deleteStart
  515. /** @type {CommentOp} */
  516. const commentOp = {
  517. p: commentStart,
  518. c: comment.op.c.slice(0, -overlapLength),
  519. t: comment.op.t,
  520. }
  521. if (comment.op.resolved) {
  522. commentOp.resolved = true
  523. }
  524. historyCommentOps.push(commentOp)
  525. }
  526. }
  527. return historyCommentOps
  528. }
  529. module.exports = RangesManager