UpdateCompressor.js 13 KB

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