UpdateCompressor.js 14 KB

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