UpdateCompressor.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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.user_id !== secondUpdate.meta.user_id) {
  292. return [firstUpdate, secondUpdate]
  293. }
  294. if (
  295. (firstUpdate.meta.type === 'external' &&
  296. secondUpdate.meta.type !== 'external') ||
  297. (firstUpdate.meta.type !== 'external' &&
  298. secondUpdate.meta.type === 'external') ||
  299. (firstUpdate.meta.type === 'external' &&
  300. secondUpdate.meta.type === 'external' &&
  301. firstUpdate.meta.source !== secondUpdate.meta.source)
  302. ) {
  303. return [firstUpdate, secondUpdate]
  304. }
  305. if (secondUpdate.meta.ts - firstUpdate.meta.ts > MAX_TIME_BETWEEN_UPDATES) {
  306. return [firstUpdate, secondUpdate]
  307. }
  308. if (
  309. (firstUpdate.meta.tc == null && secondUpdate.meta.tc != null) ||
  310. (firstUpdate.meta.tc != null && secondUpdate.meta.tc == null)
  311. ) {
  312. // One update is tracking changes and the other isn't. Tracking changes
  313. // results in different behaviour in the history, so we need to keep these
  314. // two updates separate.
  315. return [firstUpdate, secondUpdate]
  316. }
  317. if (Boolean(firstUpdate.op.u) !== Boolean(secondUpdate.op.u)) {
  318. // One update is an undo and the other isn't. If we were to merge the two
  319. // updates, we would have to choose one value for the flag, which would be
  320. // partially incorrect. Moreover, a tracked delete that is also an undo is
  321. // treated as a tracked insert rejection by the history, so these updates
  322. // need to be well separated.
  323. return [firstUpdate, secondUpdate]
  324. }
  325. if (firstUpdateIsHistoryOT && secondUpdateIsHistoryOT) {
  326. const op1 = EditOperationBuilder.fromJSON(firstUpdate.op)
  327. const op2 = EditOperationBuilder.fromJSON(secondUpdate.op)
  328. if (!op1.canBeComposedWith(op2)) return [firstUpdate, secondUpdate]
  329. return [
  330. mergeUpdatesWithOp(firstUpdate, secondUpdate, op1.compose(op2).toJSON()),
  331. ]
  332. }
  333. if (
  334. firstUpdate.op.trackedDeleteRejection ||
  335. secondUpdate.op.trackedDeleteRejection
  336. ) {
  337. // Do not merge tracked delete rejections. Each tracked delete rejection is
  338. // a separate operation.
  339. return [firstUpdate, secondUpdate]
  340. }
  341. if (
  342. firstUpdate.op.trackedChanges != null ||
  343. secondUpdate.op.trackedChanges != null
  344. ) {
  345. // Do not merge ops that span tracked changes.
  346. // TODO: This could theoretically be handled, but it would be complex. One
  347. // would need to take tracked deletes into account when merging inserts and
  348. // deletes together.
  349. return [firstUpdate, secondUpdate]
  350. }
  351. const firstOp = firstUpdate.op
  352. const secondOp = secondUpdate.op
  353. const firstSize =
  354. (firstOp.i && firstOp.i.length) || (firstOp.d && firstOp.d.length)
  355. const secondSize =
  356. (secondOp.i && secondOp.i.length) || (secondOp.d && secondOp.d.length)
  357. const firstOpInsideSecondOp =
  358. secondOp.p <= firstOp.p && firstOp.p <= secondOp.p + secondSize
  359. const secondOpInsideFirstOp =
  360. firstOp.p <= secondOp.p && secondOp.p <= firstOp.p + firstSize
  361. const combinedLengthUnderLimit = firstSize + secondSize < MAX_UPDATE_SIZE
  362. // When ops come from a multi-component update, the history position offset
  363. // (hpos - p) may differ between ops because each component's hpos is computed
  364. // against a different tracked-change state. Merging ops with different
  365. // offsets would produce incorrect history positions, so we bail out.
  366. const firstHposOffset = (firstOp.hpos ?? firstOp.p) - firstOp.p
  367. const secondHposOffset = (secondOp.hpos ?? secondOp.p) - secondOp.p
  368. if (firstHposOffset !== secondHposOffset) {
  369. return [firstUpdate, secondUpdate]
  370. }
  371. // Two inserts
  372. if (
  373. firstOp.i != null &&
  374. secondOp.i != null &&
  375. secondOpInsideFirstOp &&
  376. combinedLengthUnderLimit &&
  377. insertOpsInsideSameComments(firstOp, secondOp)
  378. ) {
  379. return [
  380. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  381. ...firstOp,
  382. i: strInject(firstOp.i, secondOp.p - firstOp.p, secondOp.i),
  383. }),
  384. ]
  385. }
  386. // Two deletes
  387. if (
  388. firstOp.d != null &&
  389. secondOp.d != null &&
  390. firstOpInsideSecondOp &&
  391. combinedLengthUnderLimit &&
  392. firstUpdate.meta.tc == null &&
  393. secondUpdate.meta.tc == null
  394. ) {
  395. return [
  396. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  397. ...secondOp,
  398. d: strInject(secondOp.d, firstOp.p - secondOp.p, firstOp.d),
  399. }),
  400. ]
  401. }
  402. // An insert and then a delete
  403. if (
  404. firstOp.i != null &&
  405. secondOp.d != null &&
  406. secondOpInsideFirstOp &&
  407. firstUpdate.meta.tc == null &&
  408. secondUpdate.meta.tc == null
  409. ) {
  410. const offset = secondOp.p - firstOp.p
  411. const insertedText = firstOp.i.slice(offset, offset + secondOp.d.length)
  412. // Only trim the insert when the delete is fully contained within in it
  413. if (insertedText === secondOp.d) {
  414. const insert = strRemove(firstOp.i, offset, secondOp.d.length)
  415. if (insert === '') {
  416. return []
  417. } else {
  418. return [
  419. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  420. ...firstOp,
  421. i: insert,
  422. }),
  423. ]
  424. }
  425. } else {
  426. // This will only happen if the delete extends outside the insert
  427. return [firstUpdate, secondUpdate]
  428. }
  429. }
  430. // A delete then an insert at the same place, likely a copy-paste of a chunk of content
  431. if (
  432. firstOp.d != null &&
  433. secondOp.i != null &&
  434. firstOp.p === secondOp.p &&
  435. firstUpdate.meta.tc == null &&
  436. secondUpdate.meta.tc == null
  437. ) {
  438. const offset = firstOp.p
  439. const hoffset = firstOp.hpos
  440. const diffUpdates = diffAsShareJsOps(firstOp.d, secondOp.i).map(
  441. function (op) {
  442. // diffAsShareJsOps() returns ops with positions relative to the position
  443. // of the copy/paste. We need to adjust these positions so that they
  444. // apply to the whole document instead.
  445. const pos = op.p
  446. op.p = pos + offset
  447. if (hoffset != null) {
  448. op.hpos = pos + hoffset
  449. }
  450. if (firstOp.u && secondOp.u) {
  451. op.u = true
  452. }
  453. if ('i' in op && secondOp.commentIds != null) {
  454. // Make sure that commentIds metadata is propagated to inserts
  455. op.commentIds = secondOp.commentIds
  456. }
  457. const update = mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  458. // Set the doc hash only on the last update
  459. delete update.meta.doc_hash
  460. return update
  461. }
  462. )
  463. const docHash = secondUpdate.meta.doc_hash
  464. if (docHash != null && diffUpdates.length > 0) {
  465. diffUpdates[diffUpdates.length - 1].meta.doc_hash = docHash
  466. }
  467. // Doing a diff like this loses track of the doc lengths for each
  468. // update, so recalculate them
  469. let docLength =
  470. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  471. for (const update of diffUpdates) {
  472. update.meta.doc_length = docLength
  473. docLength = adjustLengthByOp(docLength, update.op, {
  474. tracked: update.meta.tc != null,
  475. })
  476. delete update.meta.history_doc_length
  477. }
  478. return diffUpdates
  479. }
  480. return [firstUpdate, secondUpdate]
  481. }
  482. /**
  483. * Return the diff between two strings
  484. *
  485. * @param {string} before
  486. * @param {string} after
  487. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  488. */
  489. export function diffAsShareJsOps(before, after) {
  490. const diffs = dmp.diff_main(before, after)
  491. dmp.diff_cleanupSemantic(diffs)
  492. const ops = []
  493. let position = 0
  494. for (const diff of diffs) {
  495. const [type, content] = diff
  496. if (type === ADDED) {
  497. ops.push({
  498. i: content,
  499. p: position,
  500. })
  501. position += content.length
  502. } else if (type === REMOVED) {
  503. ops.push({
  504. d: content,
  505. p: position,
  506. })
  507. } else if (type === UNCHANGED) {
  508. position += content.length
  509. } else {
  510. throw new Error('Unknown type')
  511. }
  512. }
  513. return ops
  514. }
  515. /**
  516. * Checks if two insert ops are inside the same comments
  517. *
  518. * @param {InsertOp} op1
  519. * @param {InsertOp} op2
  520. * @returns {boolean}
  521. */
  522. function insertOpsInsideSameComments(op1, op2) {
  523. const commentIds1 = op1.commentIds
  524. const commentIds2 = op2.commentIds
  525. if (commentIds1 == null && commentIds2 == null) {
  526. // None are inside comments
  527. return true
  528. }
  529. if (
  530. commentIds1 != null &&
  531. commentIds2 != null &&
  532. commentIds1.every(id => commentIds2.includes(id)) &&
  533. commentIds2.every(id => commentIds1.includes(id))
  534. ) {
  535. // Both are inside the same comments
  536. return true
  537. }
  538. return false
  539. }