UpdateCompressor.js 15 KB

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