UpdateCompressor.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 && op.u == null) {
  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 ('c' in op && op.c != null) {
  68. return length
  69. } else {
  70. throw new OError('unexpected op type')
  71. }
  72. }
  73. /**
  74. * Updates come from the doc updater in format
  75. * {
  76. * op: [ { ... op1 ... }, { ... op2 ... } ]
  77. * meta: { ts: ..., user_id: ... }
  78. * }
  79. * but it's easier to work with on op per update, so convert these updates to
  80. * our compressed format
  81. * [{
  82. * op: op1
  83. * meta: { ts: ..., user_id: ... }
  84. * }, {
  85. * op: op2
  86. * meta: { ts: ..., user_id: ... }
  87. * }]
  88. *
  89. * @param {Update[]} updates
  90. * @returns {Update[]} single op updates
  91. */
  92. export function convertToSingleOpUpdates(updates) {
  93. const splitUpdates = []
  94. for (const update of updates) {
  95. if (!('op' in update)) {
  96. // Not a text op, likely a project strucure op
  97. splitUpdates.push(update)
  98. continue
  99. }
  100. const ops = update.op
  101. let docLength = update.meta.history_doc_length ?? update.meta.doc_length
  102. // Temporary fix for document-updater sending a length of -1 for empty
  103. // documents. This can be removed after all queues have been flushed.
  104. if (docLength === -1) {
  105. docLength = 0
  106. }
  107. for (const op of ops) {
  108. const splitUpdate = cloneWithOp(update, op)
  109. if (docLength != null) {
  110. splitUpdate.meta.doc_length = docLength
  111. docLength = adjustLengthByOp(docLength, op, {
  112. tracked: update.meta.tc != null,
  113. })
  114. delete splitUpdate.meta.history_doc_length
  115. }
  116. splitUpdates.push(splitUpdate)
  117. }
  118. }
  119. return splitUpdates
  120. }
  121. export function filterBlankUpdates(updates) {
  122. // Diffing an insert and delete can return blank inserts and deletes
  123. // which the OL history service doesn't have an equivalent for.
  124. //
  125. // NOTE: this relies on the updates only containing either op.i or op.d entries
  126. // but not both, which is the case because diffAsShareJsOps does this
  127. return updates.filter(
  128. update => !(update.op && (update.op.i === '' || update.op.d === ''))
  129. )
  130. }
  131. export function concatUpdatesWithSameVersion(updates) {
  132. const concattedUpdates = []
  133. for (let update of updates) {
  134. if (update.op != null) {
  135. update = cloneWithOp(update, [update.op])
  136. const lastUpdate = concattedUpdates[concattedUpdates.length - 1]
  137. if (
  138. lastUpdate != null &&
  139. lastUpdate.op != null &&
  140. lastUpdate.v === update.v &&
  141. lastUpdate.doc === update.doc &&
  142. lastUpdate.pathname === update.pathname
  143. ) {
  144. lastUpdate.op = lastUpdate.op.concat(update.op)
  145. } else {
  146. concattedUpdates.push(update)
  147. }
  148. } else {
  149. concattedUpdates.push(update)
  150. }
  151. }
  152. return concattedUpdates
  153. }
  154. export function compressRawUpdates(rawUpdates) {
  155. let updates = convertToSingleOpUpdates(rawUpdates)
  156. updates = compressUpdates(updates)
  157. updates = filterBlankUpdates(updates)
  158. updates = concatUpdatesWithSameVersion(updates)
  159. return updates
  160. }
  161. export function compressUpdates(updates) {
  162. if (updates.length === 0) {
  163. return []
  164. }
  165. let compressedUpdates = [updates.shift()]
  166. for (const update of updates) {
  167. const lastCompressedUpdate = compressedUpdates.pop()
  168. if (lastCompressedUpdate != null) {
  169. const newCompressedUpdates = _concatTwoUpdates(
  170. lastCompressedUpdate,
  171. update
  172. )
  173. compressedUpdates = compressedUpdates.concat(newCompressedUpdates)
  174. } else {
  175. compressedUpdates.push(update)
  176. }
  177. }
  178. return compressedUpdates
  179. }
  180. /**
  181. * If possible, merge two updates into a single update that has the same effect.
  182. *
  183. * It's useful to do some of this work at this point while we're dealing with
  184. * document-updater updates. The deletes, in particular include the deleted
  185. * text. This allows us to find pieces of inserts and deletes that cancel each
  186. * other out because they insert/delete the exact same text. This compression
  187. * makes the diff smaller.
  188. */
  189. function _concatTwoUpdates(firstUpdate, secondUpdate) {
  190. // Previously we cloned firstUpdate and secondUpdate at this point but we
  191. // can skip this step because whenever they are returned with
  192. // modification there is always a clone at that point via
  193. // mergeUpdatesWithOp.
  194. if (firstUpdate.op == null || secondUpdate.op == null) {
  195. // Project structure ops
  196. return [firstUpdate, secondUpdate]
  197. }
  198. if (
  199. firstUpdate.doc !== secondUpdate.doc ||
  200. firstUpdate.pathname !== secondUpdate.pathname
  201. ) {
  202. return [firstUpdate, secondUpdate]
  203. }
  204. if (firstUpdate.meta.user_id !== secondUpdate.meta.user_id) {
  205. return [firstUpdate, secondUpdate]
  206. }
  207. if (
  208. (firstUpdate.meta.type === 'external' &&
  209. secondUpdate.meta.type !== 'external') ||
  210. (firstUpdate.meta.type !== 'external' &&
  211. secondUpdate.meta.type === 'external') ||
  212. (firstUpdate.meta.type === 'external' &&
  213. secondUpdate.meta.type === 'external' &&
  214. firstUpdate.meta.source !== secondUpdate.meta.source)
  215. ) {
  216. return [firstUpdate, secondUpdate]
  217. }
  218. if (secondUpdate.meta.ts - firstUpdate.meta.ts > MAX_TIME_BETWEEN_UPDATES) {
  219. return [firstUpdate, secondUpdate]
  220. }
  221. if (
  222. (firstUpdate.meta.tc == null && secondUpdate.meta.tc != null) ||
  223. (firstUpdate.meta.tc != null && secondUpdate.meta.tc == null)
  224. ) {
  225. // One update is tracking changes and the other isn't. Tracking changes
  226. // results in different behaviour in the history, so we need to keep these
  227. // two updates separate.
  228. return [firstUpdate, secondUpdate]
  229. }
  230. if (Boolean(firstUpdate.op.u) !== Boolean(secondUpdate.op.u)) {
  231. // One update is an undo and the other isn't. If we were to merge the two
  232. // updates, we would have to choose one value for the flag, which would be
  233. // partially incorrect. Moreover, a tracked delete that is also an undo is
  234. // treated as a tracked insert rejection by the history, so these updates
  235. // need to be well separated.
  236. return [firstUpdate, secondUpdate]
  237. }
  238. if (
  239. firstUpdate.op.trackedDeleteRejection ||
  240. secondUpdate.op.trackedDeleteRejection
  241. ) {
  242. // Do not merge tracked delete rejections. Each tracked delete rejection is
  243. // a separate operation.
  244. return [firstUpdate, secondUpdate]
  245. }
  246. if (
  247. firstUpdate.op.trackedChanges != null ||
  248. secondUpdate.op.trackedChanges != null
  249. ) {
  250. // Do not merge ops that span tracked changes.
  251. // TODO: This could theoretically be handled, but it would be complex. One
  252. // would need to take tracked deletes into account when merging inserts and
  253. // deletes together.
  254. return [firstUpdate, secondUpdate]
  255. }
  256. const firstOp = firstUpdate.op
  257. const secondOp = secondUpdate.op
  258. const firstSize =
  259. (firstOp.i && firstOp.i.length) || (firstOp.d && firstOp.d.length)
  260. const secondSize =
  261. (secondOp.i && secondOp.i.length) || (secondOp.d && secondOp.d.length)
  262. const firstOpInsideSecondOp =
  263. secondOp.p <= firstOp.p && firstOp.p <= secondOp.p + secondSize
  264. const secondOpInsideFirstOp =
  265. firstOp.p <= secondOp.p && secondOp.p <= firstOp.p + firstSize
  266. const combinedLengthUnderLimit = firstSize + secondSize < MAX_UPDATE_SIZE
  267. // Two inserts
  268. if (
  269. firstOp.i != null &&
  270. secondOp.i != null &&
  271. secondOpInsideFirstOp &&
  272. combinedLengthUnderLimit
  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. return mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  349. }
  350. )
  351. // Doing a diff like this loses track of the doc lengths for each
  352. // update, so recalculate them
  353. let docLength =
  354. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  355. for (const update of diffUpdates) {
  356. update.meta.doc_length = docLength
  357. docLength = adjustLengthByOp(docLength, update.op, {
  358. tracked: update.meta.tc != null,
  359. })
  360. delete update.meta.history_doc_length
  361. }
  362. return diffUpdates
  363. }
  364. return [firstUpdate, secondUpdate]
  365. }
  366. /**
  367. * Return the diff between two strings
  368. *
  369. * @param {string} before
  370. * @param {string} after
  371. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  372. */
  373. export function diffAsShareJsOps(before, after) {
  374. const diffs = dmp.diff_main(before, after)
  375. dmp.diff_cleanupSemantic(diffs)
  376. const ops = []
  377. let position = 0
  378. for (const diff of diffs) {
  379. const type = diff[0]
  380. const content = diff[1]
  381. if (type === ADDED) {
  382. ops.push({
  383. i: content,
  384. p: position,
  385. })
  386. position += content.length
  387. } else if (type === REMOVED) {
  388. ops.push({
  389. d: content,
  390. p: position,
  391. })
  392. } else if (type === UNCHANGED) {
  393. position += content.length
  394. } else {
  395. throw new Error('Unknown type')
  396. }
  397. }
  398. return ops
  399. }