UpdateCompressor.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. // @ts-check
  2. import OError from '@overleaf/o-error'
  3. import DMP from 'diff-match-patch'
  4. /**
  5. * @typedef {import('./types').DeleteOp} DeleteOp
  6. * @typedef {import('./types').InsertOp} InsertOp
  7. * @typedef {import('./types').Op} Op
  8. * @typedef {import('./types').Update} Update
  9. */
  10. const MAX_TIME_BETWEEN_UPDATES = 60 * 1000 // one minute
  11. const MAX_UPDATE_SIZE = 2 * 1024 * 1024 // 2 MB
  12. const ADDED = 1
  13. const REMOVED = -1
  14. const UNCHANGED = 0
  15. const strInject = (s1, pos, s2) => s1.slice(0, pos) + s2 + s1.slice(pos)
  16. const strRemove = (s1, pos, length) => s1.slice(0, pos) + s1.slice(pos + length)
  17. const dmp = new DMP()
  18. dmp.Diff_Timeout = 0.1 // prevent the diff algorithm from searching too hard for changes in unrelated content
  19. const cloneWithOp = function (update, op) {
  20. // to improve performance, shallow clone the update
  21. // and its meta property (also an object), then
  22. // overwrite the op property directly.
  23. update = Object.assign({}, update)
  24. update.meta = Object.assign({}, update.meta)
  25. update.op = op
  26. return update
  27. }
  28. const mergeUpdatesWithOp = function (firstUpdate, secondUpdate, op) {
  29. // We want to take doc_length and ts from the firstUpdate, v from the second
  30. const update = cloneWithOp(firstUpdate, op)
  31. if (secondUpdate.v != null) {
  32. update.v = secondUpdate.v
  33. }
  34. return update
  35. }
  36. /**
  37. * Adjust the given length to account for the given op
  38. *
  39. * The resulting length is the new length of the doc after the op is applied.
  40. *
  41. * @param {number} length
  42. * @param {Op} op
  43. * @param {object} opts
  44. * @param {boolean} [opts.tracked] - whether or not the update is a tracked change
  45. * @returns {number} the adjusted length
  46. */
  47. function adjustLengthByOp(length, op, opts = {}) {
  48. if ('i' in op && op.i != null) {
  49. if (op.trackedDeleteRejection) {
  50. // Tracked delete rejection: will be translated into a retain
  51. return length
  52. } else {
  53. return length + op.i.length
  54. }
  55. } else if ('d' in op && op.d != null) {
  56. if (opts.tracked) {
  57. // Tracked delete: will be translated into a retain, except where it overlaps tracked inserts.
  58. for (const change of op.trackedChanges ?? []) {
  59. if (change.type === 'insert') {
  60. length -= change.length
  61. }
  62. }
  63. return length
  64. } else {
  65. return length - op.d.length
  66. }
  67. } else if ('r' in op && op.r != null) {
  68. return length
  69. } else if ('c' in op && op.c != null) {
  70. return length
  71. } else {
  72. throw new OError('unexpected op type')
  73. }
  74. }
  75. /**
  76. * Updates come from the doc updater in format
  77. * {
  78. * op: [ { ... op1 ... }, { ... op2 ... } ]
  79. * meta: { ts: ..., user_id: ... }
  80. * }
  81. * but it's easier to work with on op per update, so convert these updates to
  82. * our compressed format
  83. * [{
  84. * op: op1
  85. * meta: { ts: ..., user_id: ... }
  86. * }, {
  87. * op: op2
  88. * meta: { ts: ..., user_id: ... }
  89. * }]
  90. *
  91. * @param {Update[]} updates
  92. * @returns {Update[]} single op updates
  93. */
  94. export function convertToSingleOpUpdates(updates) {
  95. const splitUpdates = []
  96. for (const update of updates) {
  97. if (!('op' in update)) {
  98. // Not a text op, likely a project strucure op
  99. splitUpdates.push(update)
  100. continue
  101. }
  102. const ops = update.op
  103. let docLength = update.meta.history_doc_length ?? update.meta.doc_length
  104. // Temporary fix for document-updater sending a length of -1 for empty
  105. // documents. This can be removed after all queues have been flushed.
  106. if (docLength === -1) {
  107. docLength = 0
  108. }
  109. for (const op of ops) {
  110. const splitUpdate = cloneWithOp(update, op)
  111. if (docLength != null) {
  112. splitUpdate.meta.doc_length = docLength
  113. docLength = adjustLengthByOp(docLength, op, {
  114. tracked: update.meta.tc != null,
  115. })
  116. delete splitUpdate.meta.history_doc_length
  117. }
  118. splitUpdates.push(splitUpdate)
  119. }
  120. }
  121. return splitUpdates
  122. }
  123. export function filterBlankUpdates(updates) {
  124. // Diffing an insert and delete can return blank inserts and deletes
  125. // which the OL history service doesn't have an equivalent for.
  126. //
  127. // NOTE: this relies on the updates only containing either op.i or op.d entries
  128. // but not both, which is the case because diffAsShareJsOps does this
  129. return updates.filter(
  130. update => !(update.op && (update.op.i === '' || update.op.d === ''))
  131. )
  132. }
  133. export function concatUpdatesWithSameVersion(updates) {
  134. const concattedUpdates = []
  135. for (let update of updates) {
  136. if (update.op != null) {
  137. update = cloneWithOp(update, [update.op])
  138. const lastUpdate = concattedUpdates[concattedUpdates.length - 1]
  139. if (
  140. lastUpdate != null &&
  141. lastUpdate.op != null &&
  142. lastUpdate.v === update.v &&
  143. lastUpdate.doc === update.doc &&
  144. lastUpdate.pathname === update.pathname
  145. ) {
  146. lastUpdate.op = lastUpdate.op.concat(update.op)
  147. } else {
  148. concattedUpdates.push(update)
  149. }
  150. } else {
  151. concattedUpdates.push(update)
  152. }
  153. }
  154. return concattedUpdates
  155. }
  156. export function compressRawUpdates(rawUpdates) {
  157. let updates = convertToSingleOpUpdates(rawUpdates)
  158. updates = compressUpdates(updates)
  159. updates = filterBlankUpdates(updates)
  160. updates = concatUpdatesWithSameVersion(updates)
  161. return updates
  162. }
  163. export function compressUpdates(updates) {
  164. if (updates.length === 0) {
  165. return []
  166. }
  167. let compressedUpdates = [updates.shift()]
  168. for (const update of updates) {
  169. const lastCompressedUpdate = compressedUpdates.pop()
  170. if (lastCompressedUpdate != null) {
  171. const newCompressedUpdates = _concatTwoUpdates(
  172. lastCompressedUpdate,
  173. update
  174. )
  175. compressedUpdates = compressedUpdates.concat(newCompressedUpdates)
  176. } else {
  177. compressedUpdates.push(update)
  178. }
  179. }
  180. return compressedUpdates
  181. }
  182. /**
  183. * If possible, merge two updates into a single update that has the same effect.
  184. *
  185. * It's useful to do some of this work at this point while we're dealing with
  186. * document-updater updates. The deletes, in particular include the deleted
  187. * text. This allows us to find pieces of inserts and deletes that cancel each
  188. * other out because they insert/delete the exact same text. This compression
  189. * makes the diff smaller.
  190. */
  191. function _concatTwoUpdates(firstUpdate, secondUpdate) {
  192. // Previously we cloned firstUpdate and secondUpdate at this point but we
  193. // can skip this step because whenever they are returned with
  194. // modification there is always a clone at that point via
  195. // mergeUpdatesWithOp.
  196. if (firstUpdate.op == null || secondUpdate.op == null) {
  197. // Project structure ops
  198. return [firstUpdate, secondUpdate]
  199. }
  200. if (
  201. firstUpdate.doc !== secondUpdate.doc ||
  202. firstUpdate.pathname !== secondUpdate.pathname
  203. ) {
  204. return [firstUpdate, secondUpdate]
  205. }
  206. if (firstUpdate.meta.user_id !== secondUpdate.meta.user_id) {
  207. return [firstUpdate, secondUpdate]
  208. }
  209. if (
  210. (firstUpdate.meta.type === 'external' &&
  211. secondUpdate.meta.type !== 'external') ||
  212. (firstUpdate.meta.type !== 'external' &&
  213. secondUpdate.meta.type === 'external') ||
  214. (firstUpdate.meta.type === 'external' &&
  215. secondUpdate.meta.type === 'external' &&
  216. firstUpdate.meta.source !== secondUpdate.meta.source)
  217. ) {
  218. return [firstUpdate, secondUpdate]
  219. }
  220. if (secondUpdate.meta.ts - firstUpdate.meta.ts > MAX_TIME_BETWEEN_UPDATES) {
  221. return [firstUpdate, secondUpdate]
  222. }
  223. if (
  224. (firstUpdate.meta.tc == null && secondUpdate.meta.tc != null) ||
  225. (firstUpdate.meta.tc != null && secondUpdate.meta.tc == null)
  226. ) {
  227. // One update is tracking changes and the other isn't. Tracking changes
  228. // results in different behaviour in the history, so we need to keep these
  229. // two updates separate.
  230. return [firstUpdate, secondUpdate]
  231. }
  232. if (Boolean(firstUpdate.op.u) !== Boolean(secondUpdate.op.u)) {
  233. // One update is an undo and the other isn't. If we were to merge the two
  234. // updates, we would have to choose one value for the flag, which would be
  235. // partially incorrect. Moreover, a tracked delete that is also an undo is
  236. // treated as a tracked insert rejection by the history, so these updates
  237. // need to be well separated.
  238. return [firstUpdate, secondUpdate]
  239. }
  240. if (
  241. firstUpdate.op.trackedDeleteRejection ||
  242. secondUpdate.op.trackedDeleteRejection
  243. ) {
  244. // Do not merge tracked delete rejections. Each tracked delete rejection is
  245. // a separate operation.
  246. return [firstUpdate, secondUpdate]
  247. }
  248. if (
  249. firstUpdate.op.trackedChanges != null ||
  250. secondUpdate.op.trackedChanges != null
  251. ) {
  252. // Do not merge ops that span tracked changes.
  253. // TODO: This could theoretically be handled, but it would be complex. One
  254. // would need to take tracked deletes into account when merging inserts and
  255. // deletes together.
  256. return [firstUpdate, secondUpdate]
  257. }
  258. const firstOp = firstUpdate.op
  259. const secondOp = secondUpdate.op
  260. const firstSize =
  261. (firstOp.i && firstOp.i.length) || (firstOp.d && firstOp.d.length)
  262. const secondSize =
  263. (secondOp.i && secondOp.i.length) || (secondOp.d && secondOp.d.length)
  264. const firstOpInsideSecondOp =
  265. secondOp.p <= firstOp.p && firstOp.p <= secondOp.p + secondSize
  266. const secondOpInsideFirstOp =
  267. firstOp.p <= secondOp.p && secondOp.p <= firstOp.p + firstSize
  268. const combinedLengthUnderLimit = firstSize + secondSize < MAX_UPDATE_SIZE
  269. // Two inserts
  270. if (
  271. firstOp.i != null &&
  272. secondOp.i != null &&
  273. secondOpInsideFirstOp &&
  274. combinedLengthUnderLimit &&
  275. insertOpsInsideSameComments(firstOp, secondOp)
  276. ) {
  277. return [
  278. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  279. ...firstOp,
  280. i: strInject(firstOp.i, secondOp.p - firstOp.p, secondOp.i),
  281. }),
  282. ]
  283. }
  284. // Two deletes
  285. if (
  286. firstOp.d != null &&
  287. secondOp.d != null &&
  288. firstOpInsideSecondOp &&
  289. combinedLengthUnderLimit &&
  290. firstUpdate.meta.tc == null &&
  291. secondUpdate.meta.tc == null
  292. ) {
  293. return [
  294. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  295. ...secondOp,
  296. d: strInject(secondOp.d, firstOp.p - secondOp.p, firstOp.d),
  297. }),
  298. ]
  299. }
  300. // An insert and then a delete
  301. if (
  302. firstOp.i != null &&
  303. secondOp.d != null &&
  304. secondOpInsideFirstOp &&
  305. firstUpdate.meta.tc == null &&
  306. secondUpdate.meta.tc == null
  307. ) {
  308. const offset = secondOp.p - firstOp.p
  309. const insertedText = firstOp.i.slice(offset, offset + secondOp.d.length)
  310. // Only trim the insert when the delete is fully contained within in it
  311. if (insertedText === secondOp.d) {
  312. const insert = strRemove(firstOp.i, offset, secondOp.d.length)
  313. if (insert === '') {
  314. return []
  315. } else {
  316. return [
  317. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  318. ...firstOp,
  319. i: insert,
  320. }),
  321. ]
  322. }
  323. } else {
  324. // This will only happen if the delete extends outside the insert
  325. return [firstUpdate, secondUpdate]
  326. }
  327. }
  328. // A delete then an insert at the same place, likely a copy-paste of a chunk of content
  329. if (
  330. firstOp.d != null &&
  331. secondOp.i != null &&
  332. firstOp.p === secondOp.p &&
  333. firstUpdate.meta.tc == null &&
  334. secondUpdate.meta.tc == null
  335. ) {
  336. const offset = firstOp.p
  337. const hoffset = firstOp.hpos
  338. const diffUpdates = diffAsShareJsOps(firstOp.d, secondOp.i).map(
  339. function (op) {
  340. // diffAsShareJsOps() returns ops with positions relative to the position
  341. // of the copy/paste. We need to adjust these positions so that they
  342. // apply to the whole document instead.
  343. const pos = op.p
  344. op.p = pos + offset
  345. if (hoffset != null) {
  346. op.hpos = pos + hoffset
  347. }
  348. if (firstOp.u && secondOp.u) {
  349. op.u = true
  350. }
  351. if ('i' in op && secondOp.commentIds != null) {
  352. // Make sure that commentIds metadata is propagated to inserts
  353. op.commentIds = secondOp.commentIds
  354. }
  355. return mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  356. }
  357. )
  358. // Doing a diff like this loses track of the doc lengths for each
  359. // update, so recalculate them
  360. let docLength =
  361. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  362. for (const update of diffUpdates) {
  363. update.meta.doc_length = docLength
  364. docLength = adjustLengthByOp(docLength, update.op, {
  365. tracked: update.meta.tc != null,
  366. })
  367. delete update.meta.history_doc_length
  368. }
  369. return diffUpdates
  370. }
  371. return [firstUpdate, secondUpdate]
  372. }
  373. /**
  374. * Return the diff between two strings
  375. *
  376. * @param {string} before
  377. * @param {string} after
  378. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  379. */
  380. export function diffAsShareJsOps(before, after) {
  381. const diffs = dmp.diff_main(before, after)
  382. dmp.diff_cleanupSemantic(diffs)
  383. const ops = []
  384. let position = 0
  385. for (const diff of diffs) {
  386. const type = diff[0]
  387. const content = diff[1]
  388. if (type === ADDED) {
  389. ops.push({
  390. i: content,
  391. p: position,
  392. })
  393. position += content.length
  394. } else if (type === REMOVED) {
  395. ops.push({
  396. d: content,
  397. p: position,
  398. })
  399. } else if (type === UNCHANGED) {
  400. position += content.length
  401. } else {
  402. throw new Error('Unknown type')
  403. }
  404. }
  405. return ops
  406. }
  407. /**
  408. * Checks if two insert ops are inside the same comments
  409. *
  410. * @param {InsertOp} op1
  411. * @param {InsertOp} op2
  412. * @returns {boolean}
  413. */
  414. function insertOpsInsideSameComments(op1, op2) {
  415. const commentIds1 = op1.commentIds
  416. const commentIds2 = op2.commentIds
  417. if (commentIds1 == null && commentIds2 == null) {
  418. // None are inside comments
  419. return true
  420. }
  421. if (
  422. commentIds1 != null &&
  423. commentIds2 != null &&
  424. commentIds1.every(id => commentIds2.includes(id)) &&
  425. commentIds2.every(id => commentIds1.includes(id))
  426. ) {
  427. // Both are inside the same comments
  428. return true
  429. }
  430. return false
  431. }