UpdateCompressor.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. for (const op of ops) {
  103. const splitUpdate = cloneWithOp(update, op)
  104. if (docLength != null) {
  105. splitUpdate.meta.doc_length = docLength
  106. docLength = adjustLengthByOp(docLength, op, {
  107. tracked: update.meta.tc != null,
  108. })
  109. delete splitUpdate.meta.history_doc_length
  110. }
  111. splitUpdates.push(splitUpdate)
  112. }
  113. }
  114. return splitUpdates
  115. }
  116. export function filterBlankUpdates(updates) {
  117. // Diffing an insert and delete can return blank inserts and deletes
  118. // which the OL history service doesn't have an equivalent for.
  119. //
  120. // NOTE: this relies on the updates only containing either op.i or op.d entries
  121. // but not both, which is the case because diffAsShareJsOps does this
  122. return updates.filter(
  123. update => !(update.op && (update.op.i === '' || update.op.d === ''))
  124. )
  125. }
  126. export function concatUpdatesWithSameVersion(updates) {
  127. const concattedUpdates = []
  128. for (let update of updates) {
  129. if (update.op != null) {
  130. update = cloneWithOp(update, [update.op])
  131. const lastUpdate = concattedUpdates[concattedUpdates.length - 1]
  132. if (
  133. lastUpdate != null &&
  134. lastUpdate.op != null &&
  135. lastUpdate.v === update.v &&
  136. lastUpdate.doc === update.doc &&
  137. lastUpdate.pathname === update.pathname
  138. ) {
  139. lastUpdate.op = lastUpdate.op.concat(update.op)
  140. } else {
  141. concattedUpdates.push(update)
  142. }
  143. } else {
  144. concattedUpdates.push(update)
  145. }
  146. }
  147. return concattedUpdates
  148. }
  149. export function compressRawUpdates(rawUpdates) {
  150. let updates = convertToSingleOpUpdates(rawUpdates)
  151. updates = compressUpdates(updates)
  152. updates = filterBlankUpdates(updates)
  153. updates = concatUpdatesWithSameVersion(updates)
  154. return updates
  155. }
  156. export function compressUpdates(updates) {
  157. if (updates.length === 0) {
  158. return []
  159. }
  160. let compressedUpdates = [updates.shift()]
  161. for (const update of updates) {
  162. const lastCompressedUpdate = compressedUpdates.pop()
  163. if (lastCompressedUpdate != null) {
  164. const newCompressedUpdates = _concatTwoUpdates(
  165. lastCompressedUpdate,
  166. update
  167. )
  168. compressedUpdates = compressedUpdates.concat(newCompressedUpdates)
  169. } else {
  170. compressedUpdates.push(update)
  171. }
  172. }
  173. return compressedUpdates
  174. }
  175. /**
  176. * If possible, merge two updates into a single update that has the same effect.
  177. *
  178. * It's useful to do some of this work at this point while we're dealing with
  179. * document-updater updates. The deletes, in particular include the deleted
  180. * text. This allows us to find pieces of inserts and deletes that cancel each
  181. * other out because they insert/delete the exact same text. This compression
  182. * makes the diff smaller.
  183. */
  184. function _concatTwoUpdates(firstUpdate, secondUpdate) {
  185. // Previously we cloned firstUpdate and secondUpdate at this point but we
  186. // can skip this step because whenever they are returned with
  187. // modification there is always a clone at that point via
  188. // mergeUpdatesWithOp.
  189. if (firstUpdate.op == null || secondUpdate.op == null) {
  190. // Project structure ops
  191. return [firstUpdate, secondUpdate]
  192. }
  193. if (
  194. firstUpdate.doc !== secondUpdate.doc ||
  195. firstUpdate.pathname !== secondUpdate.pathname
  196. ) {
  197. return [firstUpdate, secondUpdate]
  198. }
  199. if (firstUpdate.meta.user_id !== secondUpdate.meta.user_id) {
  200. return [firstUpdate, secondUpdate]
  201. }
  202. if (
  203. (firstUpdate.meta.type === 'external' &&
  204. secondUpdate.meta.type !== 'external') ||
  205. (firstUpdate.meta.type !== 'external' &&
  206. secondUpdate.meta.type === 'external') ||
  207. (firstUpdate.meta.type === 'external' &&
  208. secondUpdate.meta.type === 'external' &&
  209. firstUpdate.meta.source !== secondUpdate.meta.source)
  210. ) {
  211. return [firstUpdate, secondUpdate]
  212. }
  213. if (secondUpdate.meta.ts - firstUpdate.meta.ts > MAX_TIME_BETWEEN_UPDATES) {
  214. return [firstUpdate, secondUpdate]
  215. }
  216. if (
  217. (firstUpdate.meta.tc == null && secondUpdate.meta.tc != null) ||
  218. (firstUpdate.meta.tc != null && secondUpdate.meta.tc == null)
  219. ) {
  220. // One update is tracking changes and the other isn't. Tracking changes
  221. // results in different behaviour in the history, so we need to keep these
  222. // two updates separate.
  223. return [firstUpdate, secondUpdate]
  224. }
  225. if (Boolean(firstUpdate.op.u) !== Boolean(secondUpdate.op.u)) {
  226. // One update is an undo and the other isn't. If we were to merge the two
  227. // updates, we would have to choose one value for the flag, which would be
  228. // partially incorrect. Moreover, a tracked delete that is also an undo is
  229. // treated as a tracked insert rejection by the history, so these updates
  230. // need to be well separated.
  231. return [firstUpdate, secondUpdate]
  232. }
  233. if (
  234. firstUpdate.op.trackedDeleteRejection ||
  235. secondUpdate.op.trackedDeleteRejection
  236. ) {
  237. // Do not merge tracked delete rejections. Each tracked delete rejection is
  238. // a separate operation.
  239. return [firstUpdate, secondUpdate]
  240. }
  241. if (
  242. firstUpdate.op.trackedChanges != null ||
  243. secondUpdate.op.trackedChanges != null
  244. ) {
  245. // Do not merge ops that span tracked changes.
  246. // TODO: This could theoretically be handled, but it would be complex. One
  247. // would need to take tracked deletes into account when merging inserts and
  248. // deletes together.
  249. return [firstUpdate, secondUpdate]
  250. }
  251. const firstOp = firstUpdate.op
  252. const secondOp = secondUpdate.op
  253. const firstSize =
  254. (firstOp.i && firstOp.i.length) || (firstOp.d && firstOp.d.length)
  255. const secondSize =
  256. (secondOp.i && secondOp.i.length) || (secondOp.d && secondOp.d.length)
  257. const firstOpInsideSecondOp =
  258. secondOp.p <= firstOp.p && firstOp.p <= secondOp.p + secondSize
  259. const secondOpInsideFirstOp =
  260. firstOp.p <= secondOp.p && secondOp.p <= firstOp.p + firstSize
  261. const combinedLengthUnderLimit = firstSize + secondSize < MAX_UPDATE_SIZE
  262. // Two inserts
  263. if (
  264. firstOp.i != null &&
  265. secondOp.i != null &&
  266. secondOpInsideFirstOp &&
  267. combinedLengthUnderLimit
  268. ) {
  269. return [
  270. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  271. ...firstOp,
  272. i: strInject(firstOp.i, secondOp.p - firstOp.p, secondOp.i),
  273. }),
  274. ]
  275. }
  276. // Two deletes
  277. if (
  278. firstOp.d != null &&
  279. secondOp.d != null &&
  280. firstOpInsideSecondOp &&
  281. combinedLengthUnderLimit &&
  282. firstUpdate.meta.tc == null &&
  283. secondUpdate.meta.tc == null
  284. ) {
  285. return [
  286. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  287. ...secondOp,
  288. d: strInject(secondOp.d, firstOp.p - secondOp.p, firstOp.d),
  289. }),
  290. ]
  291. }
  292. // An insert and then a delete
  293. if (
  294. firstOp.i != null &&
  295. secondOp.d != null &&
  296. secondOpInsideFirstOp &&
  297. firstUpdate.meta.tc == null &&
  298. secondUpdate.meta.tc == null
  299. ) {
  300. const offset = secondOp.p - firstOp.p
  301. const insertedText = firstOp.i.slice(offset, offset + secondOp.d.length)
  302. // Only trim the insert when the delete is fully contained within in it
  303. if (insertedText === secondOp.d) {
  304. const insert = strRemove(firstOp.i, offset, secondOp.d.length)
  305. if (insert === '') {
  306. return []
  307. } else {
  308. return [
  309. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  310. ...firstOp,
  311. i: insert,
  312. }),
  313. ]
  314. }
  315. } else {
  316. // This will only happen if the delete extends outside the insert
  317. return [firstUpdate, secondUpdate]
  318. }
  319. }
  320. // A delete then an insert at the same place, likely a copy-paste of a chunk of content
  321. if (
  322. firstOp.d != null &&
  323. secondOp.i != null &&
  324. firstOp.p === secondOp.p &&
  325. firstUpdate.meta.tc == null &&
  326. secondUpdate.meta.tc == null
  327. ) {
  328. const offset = firstOp.p
  329. const hoffset = firstOp.hpos
  330. const diffUpdates = diffAsShareJsOps(firstOp.d, secondOp.i).map(
  331. function (op) {
  332. // diffAsShareJsOps() returns ops with positions relative to the position
  333. // of the copy/paste. We need to adjust these positions so that they
  334. // apply to the whole document instead.
  335. const pos = op.p
  336. op.p = pos + offset
  337. if (hoffset != null) {
  338. op.hpos = pos + hoffset
  339. }
  340. if (firstOp.u && secondOp.u) {
  341. op.u = true
  342. }
  343. return mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  344. }
  345. )
  346. // Doing a diff like this loses track of the doc lengths for each
  347. // update, so recalculate them
  348. let docLength =
  349. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  350. for (const update of diffUpdates) {
  351. update.meta.doc_length = docLength
  352. docLength = adjustLengthByOp(docLength, update.op, {
  353. tracked: update.meta.tc != null,
  354. })
  355. delete update.meta.history_doc_length
  356. }
  357. return diffUpdates
  358. }
  359. return [firstUpdate, secondUpdate]
  360. }
  361. /**
  362. * Return the diff between two strings
  363. *
  364. * @param {string} before
  365. * @param {string} after
  366. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  367. */
  368. export function diffAsShareJsOps(before, after) {
  369. const diffs = dmp.diff_main(before, after)
  370. dmp.diff_cleanupSemantic(diffs)
  371. const ops = []
  372. let position = 0
  373. for (const diff of diffs) {
  374. const type = diff[0]
  375. const content = diff[1]
  376. if (type === ADDED) {
  377. ops.push({
  378. i: content,
  379. p: position,
  380. })
  381. position += content.length
  382. } else if (type === REMOVED) {
  383. ops.push({
  384. d: content,
  385. p: position,
  386. })
  387. } else if (type === UNCHANGED) {
  388. position += content.length
  389. } else {
  390. throw new Error('Unknown type')
  391. }
  392. }
  393. return ops
  394. }