UpdateCompressor.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. // @ts-check
  2. import Metrics from '@overleaf/metrics'
  3. import OError from '@overleaf/o-error'
  4. import DMP from 'diff-match-patch'
  5. import { EditOperationBuilder } from 'overleaf-editor-core'
  6. import zlib from 'node:zlib'
  7. import { ReadableString, WritableBuffer } from '@overleaf/stream-utils'
  8. import Stream from 'node:stream'
  9. import logger from '@overleaf/logger'
  10. import { callbackify } from '@overleaf/promise-utils'
  11. import Settings from '@overleaf/settings'
  12. /**
  13. * @import { DeleteOp, InsertOp, Op, Update } from './types'
  14. */
  15. const MAX_TIME_BETWEEN_UPDATES = 60 * 1000 // one minute
  16. const MAX_UPDATE_SIZE = 2 * 1024 * 1024 // 2 MB
  17. const ADDED = 1
  18. const REMOVED = -1
  19. const UNCHANGED = 0
  20. const strInject = (s1, pos, s2) => s1.slice(0, pos) + s2 + s1.slice(pos)
  21. const strRemove = (s1, pos, length) => s1.slice(0, pos) + s1.slice(pos + length)
  22. const dmp = new DMP()
  23. dmp.Diff_Timeout = 0.1 // prevent the diff algorithm from searching too hard for changes in unrelated content
  24. const cloneWithOp = function (update, op) {
  25. // to improve performance, shallow clone the update
  26. // and its meta property (also an object), then
  27. // overwrite the op property directly.
  28. update = Object.assign({}, update)
  29. update.meta = Object.assign({}, update.meta)
  30. update.op = op
  31. return update
  32. }
  33. const mergeUpdatesWithOp = function (firstUpdate, secondUpdate, op) {
  34. // We want to take doc_length and ts from the firstUpdate, v and doc_hash from the second
  35. const update = cloneWithOp(firstUpdate, op)
  36. if (secondUpdate.v != null) {
  37. update.v = secondUpdate.v
  38. }
  39. if (secondUpdate.meta.doc_hash != null) {
  40. update.meta.doc_hash = secondUpdate.meta.doc_hash
  41. } else {
  42. delete update.meta.doc_hash
  43. }
  44. return update
  45. }
  46. /**
  47. * Adjust the given length to account for the given op
  48. *
  49. * The resulting length is the new length of the doc after the op is applied.
  50. *
  51. * @param {number} length
  52. * @param {Op} op
  53. * @param {object} opts
  54. * @param {boolean} [opts.tracked] - whether or not the update is a tracked change
  55. * @returns {number} the adjusted length
  56. */
  57. function adjustLengthByOp(length, op, opts = {}) {
  58. if ('i' in op && op.i != null) {
  59. if (op.trackedDeleteRejection) {
  60. // Tracked delete rejection: will be translated into a retain
  61. return length
  62. } else {
  63. return length + op.i.length
  64. }
  65. } else if ('d' in op && op.d != null) {
  66. if (opts.tracked) {
  67. // Tracked delete: will be translated into a retain, except where it overlaps tracked inserts.
  68. for (const change of op.trackedChanges ?? []) {
  69. if (change.type === 'insert') {
  70. length -= change.length
  71. }
  72. }
  73. return length
  74. } else {
  75. return length - op.d.length
  76. }
  77. } else if ('r' in op && op.r != null) {
  78. return length
  79. } else if ('c' in op && op.c != null) {
  80. return length
  81. } else {
  82. throw new OError('unexpected op type')
  83. }
  84. }
  85. /**
  86. * Updates come from the doc updater in format
  87. * {
  88. * op: [ { ... op1 ... }, { ... op2 ... } ]
  89. * meta: { ts: ..., user_id: ... }
  90. * }
  91. * but it's easier to work with on op per update, so convert these updates to
  92. * our compressed format
  93. * [{
  94. * op: op1
  95. * meta: { ts: ..., user_id: ... }
  96. * }, {
  97. * op: op2
  98. * meta: { ts: ..., user_id: ... }
  99. * }]
  100. *
  101. * @param {Update[]} updates
  102. * @returns {Update[]} single op updates
  103. */
  104. export function convertToSingleOpUpdates(updates) {
  105. const splitUpdates = []
  106. for (const update of updates) {
  107. if (!('op' in update)) {
  108. // Not a text op, likely a project strucure op
  109. splitUpdates.push(update)
  110. continue
  111. }
  112. const ops = update.op
  113. let docLength = update.meta.history_doc_length ?? update.meta.doc_length
  114. // Temporary fix for document-updater sending a length of -1 for empty
  115. // documents. This can be removed after all queues have been flushed.
  116. if (docLength === -1) {
  117. docLength = 0
  118. }
  119. const docHash = update.meta.doc_hash
  120. for (const op of ops) {
  121. const splitUpdate = cloneWithOp(update, op)
  122. // Only the last update will keep the doc_hash property
  123. delete splitUpdate.meta.doc_hash
  124. if (docLength != null) {
  125. splitUpdate.meta.doc_length = docLength
  126. docLength = adjustLengthByOp(docLength, op, {
  127. tracked: update.meta.tc != null,
  128. })
  129. delete splitUpdate.meta.history_doc_length
  130. }
  131. splitUpdates.push(splitUpdate)
  132. }
  133. if (docHash != null && splitUpdates.length > 0) {
  134. splitUpdates[splitUpdates.length - 1].meta.doc_hash = docHash
  135. }
  136. }
  137. return splitUpdates
  138. }
  139. export function filterBlankUpdates(updates) {
  140. // Diffing an insert and delete can return blank inserts and deletes
  141. // which the OL history service doesn't have an equivalent for.
  142. //
  143. // NOTE: this relies on the updates only containing either op.i or op.d entries
  144. // but not both, which is the case because diffAsShareJsOps does this
  145. return updates.filter(
  146. update => !(update.op && (update.op.i === '' || update.op.d === ''))
  147. )
  148. }
  149. export function concatUpdatesWithSameVersion(updates) {
  150. const concattedUpdates = []
  151. for (let update of updates) {
  152. if (update.op != null) {
  153. update = cloneWithOp(update, [update.op])
  154. const lastUpdate = concattedUpdates[concattedUpdates.length - 1]
  155. if (
  156. lastUpdate != null &&
  157. lastUpdate.op != null &&
  158. lastUpdate.v === update.v &&
  159. lastUpdate.doc === update.doc &&
  160. lastUpdate.pathname === update.pathname &&
  161. EditOperationBuilder.isValid(update.op[0]) ===
  162. EditOperationBuilder.isValid(lastUpdate.op[0])
  163. ) {
  164. lastUpdate.op = lastUpdate.op.concat(update.op)
  165. if (update.meta.doc_hash == null) {
  166. delete lastUpdate.meta.doc_hash
  167. } else {
  168. lastUpdate.meta.doc_hash = update.meta.doc_hash
  169. }
  170. } else {
  171. concattedUpdates.push(update)
  172. }
  173. } else {
  174. concattedUpdates.push(update)
  175. }
  176. }
  177. return concattedUpdates
  178. }
  179. async function estimateStorage(updates) {
  180. const blob = JSON.stringify(updates)
  181. const bytes = Buffer.from(blob).byteLength
  182. const read = new ReadableString(blob)
  183. const compress = zlib.createGzip()
  184. const write = new WritableBuffer()
  185. await Stream.promises.pipeline(read, compress, write)
  186. const bytesGz = write.size()
  187. return { bytes, bytesGz, nUpdates: updates.length }
  188. }
  189. /**
  190. * @param {Update[]} rawUpdates
  191. * @param {string} projectId
  192. * @param {import("./Profiler").Profiler} profile
  193. * @return {Promise<Update[]>}
  194. */
  195. async function compressRawUpdatesWithMetrics(rawUpdates, projectId, profile) {
  196. if (100 * Math.random() > Settings.estimateCompressionSample) {
  197. return compressRawUpdatesWithProfile(rawUpdates, projectId, profile)
  198. }
  199. const before = await estimateStorage(rawUpdates)
  200. profile.log('estimateRawUpdatesSize')
  201. const updates = compressRawUpdatesWithProfile(rawUpdates, projectId, profile)
  202. const after = await estimateStorage(updates)
  203. for (const [path, values] of Object.entries({ before, after })) {
  204. for (const [method, v] of Object.entries(values)) {
  205. Metrics.summary('updates_compression_estimate', v, { path, method })
  206. }
  207. }
  208. for (const method of Object.keys(before)) {
  209. const percentage = Math.ceil(100 * (after[method] / before[method]))
  210. Metrics.summary('updates_compression_percentage', percentage, { method })
  211. }
  212. profile.log('estimateCompressedUpdatesSize')
  213. return updates
  214. }
  215. export const compressRawUpdatesWithMetricsCb = callbackify(
  216. compressRawUpdatesWithMetrics
  217. )
  218. /**
  219. * @param {Update[]} rawUpdates
  220. * @param {string} projectId
  221. * @param {import("./Profiler").Profiler} profile
  222. * @return {Update[]}
  223. */
  224. function compressRawUpdatesWithProfile(rawUpdates, projectId, profile) {
  225. const updates = compressRawUpdates(rawUpdates)
  226. const timeTaken = profile.log('compressRawUpdates').getTimeDelta()
  227. if (timeTaken >= 1000) {
  228. logger.debug(
  229. { projectId, updates: rawUpdates, timeTaken },
  230. 'slow compression of raw updates'
  231. )
  232. }
  233. return updates
  234. }
  235. export function compressRawUpdates(rawUpdates) {
  236. let updates = convertToSingleOpUpdates(rawUpdates)
  237. updates = compressUpdates(updates)
  238. updates = filterBlankUpdates(updates)
  239. updates = concatUpdatesWithSameVersion(updates)
  240. return updates
  241. }
  242. export function compressUpdates(updates) {
  243. if (updates.length === 0) {
  244. return []
  245. }
  246. let compressedUpdates = [updates.shift()]
  247. for (const update of updates) {
  248. const lastCompressedUpdate = compressedUpdates.pop()
  249. if (lastCompressedUpdate != null) {
  250. const newCompressedUpdates = _concatTwoUpdates(
  251. lastCompressedUpdate,
  252. update
  253. )
  254. compressedUpdates = compressedUpdates.concat(newCompressedUpdates)
  255. } else {
  256. compressedUpdates.push(update)
  257. }
  258. }
  259. return compressedUpdates
  260. }
  261. /**
  262. * If possible, merge two updates into a single update that has the same effect.
  263. *
  264. * It's useful to do some of this work at this point while we're dealing with
  265. * document-updater updates. The deletes, in particular include the deleted
  266. * text. This allows us to find pieces of inserts and deletes that cancel each
  267. * other out because they insert/delete the exact same text. This compression
  268. * makes the diff smaller.
  269. */
  270. function _concatTwoUpdates(firstUpdate, secondUpdate) {
  271. // Previously we cloned firstUpdate and secondUpdate at this point but we
  272. // can skip this step because whenever they are returned with
  273. // modification there is always a clone at that point via
  274. // mergeUpdatesWithOp.
  275. if (firstUpdate.op == null || secondUpdate.op == null) {
  276. // Project structure ops
  277. return [firstUpdate, secondUpdate]
  278. }
  279. const firstUpdateIsHistoryOT = EditOperationBuilder.isValid(firstUpdate.op)
  280. const secondUpdateIsHistoryOT = EditOperationBuilder.isValid(secondUpdate.op)
  281. if (firstUpdateIsHistoryOT !== secondUpdateIsHistoryOT) {
  282. // cannot merge mix of sharejs-text-op and history-ot, should not happen.
  283. return [firstUpdate, secondUpdate]
  284. }
  285. if (
  286. firstUpdate.doc !== secondUpdate.doc ||
  287. firstUpdate.pathname !== secondUpdate.pathname
  288. ) {
  289. return [firstUpdate, secondUpdate]
  290. }
  291. if (firstUpdate.meta.resync || secondUpdate.meta.resync) {
  292. // Do not merge ops where one of them is a resync. We produce a list of
  293. // resync ops that first corrects the content, then the ranges. By
  294. // compressing the content updates seperately from the ranges updates,
  295. // the ranges can become out-of-sync. To stop this, disallow compressing
  296. // any resync updates.
  297. return [firstUpdate, secondUpdate]
  298. }
  299. if (firstUpdate.meta.user_id !== secondUpdate.meta.user_id) {
  300. return [firstUpdate, secondUpdate]
  301. }
  302. if (
  303. (firstUpdate.meta.type === 'external' &&
  304. secondUpdate.meta.type !== 'external') ||
  305. (firstUpdate.meta.type !== 'external' &&
  306. secondUpdate.meta.type === 'external') ||
  307. (firstUpdate.meta.type === 'external' &&
  308. secondUpdate.meta.type === 'external' &&
  309. firstUpdate.meta.source !== secondUpdate.meta.source)
  310. ) {
  311. return [firstUpdate, secondUpdate]
  312. }
  313. if (secondUpdate.meta.ts - firstUpdate.meta.ts > MAX_TIME_BETWEEN_UPDATES) {
  314. return [firstUpdate, secondUpdate]
  315. }
  316. if (
  317. (firstUpdate.meta.tc == null && secondUpdate.meta.tc != null) ||
  318. (firstUpdate.meta.tc != null && secondUpdate.meta.tc == null)
  319. ) {
  320. // One update is tracking changes and the other isn't. Tracking changes
  321. // results in different behaviour in the history, so we need to keep these
  322. // two updates separate.
  323. return [firstUpdate, secondUpdate]
  324. }
  325. if (Boolean(firstUpdate.op.u) !== Boolean(secondUpdate.op.u)) {
  326. // One update is an undo and the other isn't. If we were to merge the two
  327. // updates, we would have to choose one value for the flag, which would be
  328. // partially incorrect. Moreover, a tracked delete that is also an undo is
  329. // treated as a tracked insert rejection by the history, so these updates
  330. // need to be well separated.
  331. return [firstUpdate, secondUpdate]
  332. }
  333. if (firstUpdateIsHistoryOT && secondUpdateIsHistoryOT) {
  334. const op1 = EditOperationBuilder.fromJSON(firstUpdate.op)
  335. const op2 = EditOperationBuilder.fromJSON(secondUpdate.op)
  336. if (!op1.canBeComposedWith(op2)) return [firstUpdate, secondUpdate]
  337. return [
  338. mergeUpdatesWithOp(firstUpdate, secondUpdate, op1.compose(op2).toJSON()),
  339. ]
  340. }
  341. if (
  342. firstUpdate.op.trackedDeleteRejection ||
  343. secondUpdate.op.trackedDeleteRejection
  344. ) {
  345. // Do not merge tracked delete rejections. Each tracked delete rejection is
  346. // a separate operation.
  347. return [firstUpdate, secondUpdate]
  348. }
  349. if (
  350. firstUpdate.op.trackedChanges != null ||
  351. secondUpdate.op.trackedChanges != null
  352. ) {
  353. // Do not merge ops that span tracked changes.
  354. // TODO: This could theoretically be handled, but it would be complex. One
  355. // would need to take tracked deletes into account when merging inserts and
  356. // deletes together.
  357. return [firstUpdate, secondUpdate]
  358. }
  359. const firstOp = firstUpdate.op
  360. const secondOp = secondUpdate.op
  361. const firstSize =
  362. (firstOp.i && firstOp.i.length) || (firstOp.d && firstOp.d.length)
  363. const secondSize =
  364. (secondOp.i && secondOp.i.length) || (secondOp.d && secondOp.d.length)
  365. const firstOpInsideSecondOp =
  366. secondOp.p <= firstOp.p && firstOp.p <= secondOp.p + secondSize
  367. const secondOpInsideFirstOp =
  368. firstOp.p <= secondOp.p && secondOp.p <= firstOp.p + firstSize
  369. const combinedLengthUnderLimit = firstSize + secondSize < MAX_UPDATE_SIZE
  370. // When ops come from a multi-component update, the history position offset
  371. // (hpos - p) may differ between ops because each component's hpos is computed
  372. // against a different tracked-change state. Merging ops with different
  373. // offsets would produce incorrect history positions, so we bail out.
  374. const firstHposOffset = (firstOp.hpos ?? firstOp.p) - firstOp.p
  375. const secondHposOffset = (secondOp.hpos ?? secondOp.p) - secondOp.p
  376. if (firstHposOffset !== secondHposOffset) {
  377. return [firstUpdate, secondUpdate]
  378. }
  379. // Two inserts
  380. if (
  381. firstOp.i != null &&
  382. secondOp.i != null &&
  383. secondOpInsideFirstOp &&
  384. combinedLengthUnderLimit &&
  385. insertOpsInsideSameComments(firstOp, secondOp)
  386. ) {
  387. return [
  388. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  389. ...firstOp,
  390. i: strInject(firstOp.i, secondOp.p - firstOp.p, secondOp.i),
  391. }),
  392. ]
  393. }
  394. // Two deletes
  395. if (
  396. firstOp.d != null &&
  397. secondOp.d != null &&
  398. firstOpInsideSecondOp &&
  399. combinedLengthUnderLimit &&
  400. firstUpdate.meta.tc == null &&
  401. secondUpdate.meta.tc == null
  402. ) {
  403. return [
  404. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  405. ...secondOp,
  406. d: strInject(secondOp.d, firstOp.p - secondOp.p, firstOp.d),
  407. }),
  408. ]
  409. }
  410. // An insert and then a delete
  411. if (
  412. firstOp.i != null &&
  413. secondOp.d != null &&
  414. secondOpInsideFirstOp &&
  415. firstUpdate.meta.tc == null &&
  416. secondUpdate.meta.tc == null
  417. ) {
  418. const offset = secondOp.p - firstOp.p
  419. const insertedText = firstOp.i.slice(offset, offset + secondOp.d.length)
  420. // Only trim the insert when the delete is fully contained within in it
  421. if (insertedText === secondOp.d) {
  422. const insert = strRemove(firstOp.i, offset, secondOp.d.length)
  423. if (insert === '') {
  424. return []
  425. } else {
  426. return [
  427. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  428. ...firstOp,
  429. i: insert,
  430. }),
  431. ]
  432. }
  433. } else {
  434. // This will only happen if the delete extends outside the insert
  435. return [firstUpdate, secondUpdate]
  436. }
  437. }
  438. // A delete then an insert at the same place, likely a copy-paste of a chunk of content
  439. if (
  440. firstOp.d != null &&
  441. secondOp.i != null &&
  442. firstOp.p === secondOp.p &&
  443. firstUpdate.meta.tc == null &&
  444. secondUpdate.meta.tc == null
  445. ) {
  446. const offset = firstOp.p
  447. const hoffset = firstOp.hpos
  448. const diffUpdates = diffAsShareJsOps(firstOp.d, secondOp.i).map(
  449. function (op) {
  450. // diffAsShareJsOps() returns ops with positions relative to the position
  451. // of the copy/paste. We need to adjust these positions so that they
  452. // apply to the whole document instead.
  453. const pos = op.p
  454. op.p = pos + offset
  455. if (hoffset != null) {
  456. op.hpos = pos + hoffset
  457. }
  458. if (firstOp.u && secondOp.u) {
  459. op.u = true
  460. }
  461. if ('i' in op && secondOp.commentIds != null) {
  462. // Make sure that commentIds metadata is propagated to inserts
  463. op.commentIds = secondOp.commentIds
  464. }
  465. const update = mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  466. // Set the doc hash only on the last update
  467. delete update.meta.doc_hash
  468. return update
  469. }
  470. )
  471. const docHash = secondUpdate.meta.doc_hash
  472. if (docHash != null && diffUpdates.length > 0) {
  473. diffUpdates[diffUpdates.length - 1].meta.doc_hash = docHash
  474. }
  475. // Doing a diff like this loses track of the doc lengths for each
  476. // update, so recalculate them
  477. let docLength =
  478. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  479. for (const update of diffUpdates) {
  480. update.meta.doc_length = docLength
  481. docLength = adjustLengthByOp(docLength, update.op, {
  482. tracked: update.meta.tc != null,
  483. })
  484. delete update.meta.history_doc_length
  485. }
  486. return diffUpdates
  487. }
  488. return [firstUpdate, secondUpdate]
  489. }
  490. /**
  491. * Return the diff between two strings
  492. *
  493. * @param {string} before
  494. * @param {string} after
  495. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  496. */
  497. export function diffAsShareJsOps(before, after) {
  498. const diffs = dmp.diff_main(before, after)
  499. dmp.diff_cleanupSemantic(diffs)
  500. const ops = []
  501. let position = 0
  502. for (const diff of diffs) {
  503. const [type, content] = diff
  504. if (type === ADDED) {
  505. ops.push({
  506. i: content,
  507. p: position,
  508. })
  509. position += content.length
  510. } else if (type === REMOVED) {
  511. ops.push({
  512. d: content,
  513. p: position,
  514. })
  515. } else if (type === UNCHANGED) {
  516. position += content.length
  517. } else {
  518. throw new Error('Unknown type')
  519. }
  520. }
  521. return ops
  522. }
  523. /**
  524. * Checks if two insert ops are inside the same comments
  525. *
  526. * @param {InsertOp} op1
  527. * @param {InsertOp} op2
  528. * @returns {boolean}
  529. */
  530. function insertOpsInsideSameComments(op1, op2) {
  531. const commentIds1 = op1.commentIds
  532. const commentIds2 = op2.commentIds
  533. if (commentIds1 == null && commentIds2 == null) {
  534. // None are inside comments
  535. return true
  536. }
  537. if (
  538. commentIds1 != null &&
  539. commentIds2 != null &&
  540. commentIds1.every(id => commentIds2.includes(id)) &&
  541. commentIds2.every(id => commentIds1.includes(id))
  542. ) {
  543. // Both are inside the same comments
  544. return true
  545. }
  546. return false
  547. }