UpdateCompressor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 firstUpdateIsHistoryV1OT = EditOperationBuilder.isValid(firstUpdate.op)
  215. const secondUpdateIsHistoryV1OT = EditOperationBuilder.isValid(
  216. secondUpdate.op
  217. )
  218. if (firstUpdateIsHistoryV1OT !== secondUpdateIsHistoryV1OT) {
  219. // cannot merge mix of sharejs-text-op and history-ot, should not happen.
  220. return [firstUpdate, secondUpdate]
  221. }
  222. if (
  223. firstUpdate.doc !== secondUpdate.doc ||
  224. firstUpdate.pathname !== secondUpdate.pathname
  225. ) {
  226. return [firstUpdate, secondUpdate]
  227. }
  228. if (firstUpdate.meta.user_id !== secondUpdate.meta.user_id) {
  229. return [firstUpdate, secondUpdate]
  230. }
  231. if (
  232. (firstUpdate.meta.type === 'external' &&
  233. secondUpdate.meta.type !== 'external') ||
  234. (firstUpdate.meta.type !== 'external' &&
  235. secondUpdate.meta.type === 'external') ||
  236. (firstUpdate.meta.type === 'external' &&
  237. secondUpdate.meta.type === 'external' &&
  238. firstUpdate.meta.source !== secondUpdate.meta.source)
  239. ) {
  240. return [firstUpdate, secondUpdate]
  241. }
  242. if (secondUpdate.meta.ts - firstUpdate.meta.ts > MAX_TIME_BETWEEN_UPDATES) {
  243. return [firstUpdate, secondUpdate]
  244. }
  245. if (
  246. (firstUpdate.meta.tc == null && secondUpdate.meta.tc != null) ||
  247. (firstUpdate.meta.tc != null && secondUpdate.meta.tc == null)
  248. ) {
  249. // One update is tracking changes and the other isn't. Tracking changes
  250. // results in different behaviour in the history, so we need to keep these
  251. // two updates separate.
  252. return [firstUpdate, secondUpdate]
  253. }
  254. if (Boolean(firstUpdate.op.u) !== Boolean(secondUpdate.op.u)) {
  255. // One update is an undo and the other isn't. If we were to merge the two
  256. // updates, we would have to choose one value for the flag, which would be
  257. // partially incorrect. Moreover, a tracked delete that is also an undo is
  258. // treated as a tracked insert rejection by the history, so these updates
  259. // need to be well separated.
  260. return [firstUpdate, secondUpdate]
  261. }
  262. if (firstUpdateIsHistoryV1OT && secondUpdateIsHistoryV1OT) {
  263. const op1 = EditOperationBuilder.fromJSON(firstUpdate.op)
  264. const op2 = EditOperationBuilder.fromJSON(secondUpdate.op)
  265. if (!op1.canBeComposedWith(op2)) return [firstUpdate, secondUpdate]
  266. return [
  267. mergeUpdatesWithOp(firstUpdate, secondUpdate, op1.compose(op2).toJSON()),
  268. ]
  269. }
  270. if (
  271. firstUpdate.op.trackedDeleteRejection ||
  272. secondUpdate.op.trackedDeleteRejection
  273. ) {
  274. // Do not merge tracked delete rejections. Each tracked delete rejection is
  275. // a separate operation.
  276. return [firstUpdate, secondUpdate]
  277. }
  278. if (
  279. firstUpdate.op.trackedChanges != null ||
  280. secondUpdate.op.trackedChanges != null
  281. ) {
  282. // Do not merge ops that span tracked changes.
  283. // TODO: This could theoretically be handled, but it would be complex. One
  284. // would need to take tracked deletes into account when merging inserts and
  285. // deletes together.
  286. return [firstUpdate, secondUpdate]
  287. }
  288. const firstOp = firstUpdate.op
  289. const secondOp = secondUpdate.op
  290. const firstSize =
  291. (firstOp.i && firstOp.i.length) || (firstOp.d && firstOp.d.length)
  292. const secondSize =
  293. (secondOp.i && secondOp.i.length) || (secondOp.d && secondOp.d.length)
  294. const firstOpInsideSecondOp =
  295. secondOp.p <= firstOp.p && firstOp.p <= secondOp.p + secondSize
  296. const secondOpInsideFirstOp =
  297. firstOp.p <= secondOp.p && secondOp.p <= firstOp.p + firstSize
  298. const combinedLengthUnderLimit = firstSize + secondSize < MAX_UPDATE_SIZE
  299. // Two inserts
  300. if (
  301. firstOp.i != null &&
  302. secondOp.i != null &&
  303. secondOpInsideFirstOp &&
  304. combinedLengthUnderLimit &&
  305. insertOpsInsideSameComments(firstOp, secondOp)
  306. ) {
  307. return [
  308. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  309. ...firstOp,
  310. i: strInject(firstOp.i, secondOp.p - firstOp.p, secondOp.i),
  311. }),
  312. ]
  313. }
  314. // Two deletes
  315. if (
  316. firstOp.d != null &&
  317. secondOp.d != null &&
  318. firstOpInsideSecondOp &&
  319. combinedLengthUnderLimit &&
  320. firstUpdate.meta.tc == null &&
  321. secondUpdate.meta.tc == null
  322. ) {
  323. return [
  324. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  325. ...secondOp,
  326. d: strInject(secondOp.d, firstOp.p - secondOp.p, firstOp.d),
  327. }),
  328. ]
  329. }
  330. // An insert and then a delete
  331. if (
  332. firstOp.i != null &&
  333. secondOp.d != null &&
  334. secondOpInsideFirstOp &&
  335. firstUpdate.meta.tc == null &&
  336. secondUpdate.meta.tc == null
  337. ) {
  338. const offset = secondOp.p - firstOp.p
  339. const insertedText = firstOp.i.slice(offset, offset + secondOp.d.length)
  340. // Only trim the insert when the delete is fully contained within in it
  341. if (insertedText === secondOp.d) {
  342. const insert = strRemove(firstOp.i, offset, secondOp.d.length)
  343. if (insert === '') {
  344. return []
  345. } else {
  346. return [
  347. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  348. ...firstOp,
  349. i: insert,
  350. }),
  351. ]
  352. }
  353. } else {
  354. // This will only happen if the delete extends outside the insert
  355. return [firstUpdate, secondUpdate]
  356. }
  357. }
  358. // A delete then an insert at the same place, likely a copy-paste of a chunk of content
  359. if (
  360. firstOp.d != null &&
  361. secondOp.i != null &&
  362. firstOp.p === secondOp.p &&
  363. firstUpdate.meta.tc == null &&
  364. secondUpdate.meta.tc == null
  365. ) {
  366. const offset = firstOp.p
  367. const hoffset = firstOp.hpos
  368. const diffUpdates = diffAsShareJsOps(firstOp.d, secondOp.i).map(
  369. function (op) {
  370. // diffAsShareJsOps() returns ops with positions relative to the position
  371. // of the copy/paste. We need to adjust these positions so that they
  372. // apply to the whole document instead.
  373. const pos = op.p
  374. op.p = pos + offset
  375. if (hoffset != null) {
  376. op.hpos = pos + hoffset
  377. }
  378. if (firstOp.u && secondOp.u) {
  379. op.u = true
  380. }
  381. if ('i' in op && secondOp.commentIds != null) {
  382. // Make sure that commentIds metadata is propagated to inserts
  383. op.commentIds = secondOp.commentIds
  384. }
  385. const update = mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  386. // Set the doc hash only on the last update
  387. delete update.meta.doc_hash
  388. return update
  389. }
  390. )
  391. const docHash = secondUpdate.meta.doc_hash
  392. if (docHash != null && diffUpdates.length > 0) {
  393. diffUpdates[diffUpdates.length - 1].meta.doc_hash = docHash
  394. }
  395. // Doing a diff like this loses track of the doc lengths for each
  396. // update, so recalculate them
  397. let docLength =
  398. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  399. for (const update of diffUpdates) {
  400. update.meta.doc_length = docLength
  401. docLength = adjustLengthByOp(docLength, update.op, {
  402. tracked: update.meta.tc != null,
  403. })
  404. delete update.meta.history_doc_length
  405. }
  406. return diffUpdates
  407. }
  408. return [firstUpdate, secondUpdate]
  409. }
  410. /**
  411. * Return the diff between two strings
  412. *
  413. * @param {string} before
  414. * @param {string} after
  415. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  416. */
  417. export function diffAsShareJsOps(before, after) {
  418. const diffs = dmp.diff_main(before, after)
  419. dmp.diff_cleanupSemantic(diffs)
  420. const ops = []
  421. let position = 0
  422. for (const diff of diffs) {
  423. const [type, content] = diff
  424. if (type === ADDED) {
  425. ops.push({
  426. i: content,
  427. p: position,
  428. })
  429. position += content.length
  430. } else if (type === REMOVED) {
  431. ops.push({
  432. d: content,
  433. p: position,
  434. })
  435. } else if (type === UNCHANGED) {
  436. position += content.length
  437. } else {
  438. throw new Error('Unknown type')
  439. }
  440. }
  441. return ops
  442. }
  443. /**
  444. * Checks if two insert ops are inside the same comments
  445. *
  446. * @param {InsertOp} op1
  447. * @param {InsertOp} op2
  448. * @returns {boolean}
  449. */
  450. function insertOpsInsideSameComments(op1, op2) {
  451. const commentIds1 = op1.commentIds
  452. const commentIds2 = op2.commentIds
  453. if (commentIds1 == null && commentIds2 == null) {
  454. // None are inside comments
  455. return true
  456. }
  457. if (
  458. commentIds1 != null &&
  459. commentIds2 != null &&
  460. commentIds1.every(id => commentIds2.includes(id)) &&
  461. commentIds2.every(id => commentIds1.includes(id))
  462. ) {
  463. // Both are inside the same comments
  464. return true
  465. }
  466. return false
  467. }