UpdateCompressor.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. ) {
  162. lastUpdate.op = lastUpdate.op.concat(update.op)
  163. if (update.meta.doc_hash == null) {
  164. delete lastUpdate.meta.doc_hash
  165. } else {
  166. lastUpdate.meta.doc_hash = update.meta.doc_hash
  167. }
  168. } else {
  169. concattedUpdates.push(update)
  170. }
  171. } else {
  172. concattedUpdates.push(update)
  173. }
  174. }
  175. return concattedUpdates
  176. }
  177. async function estimateStorage(updates) {
  178. const blob = JSON.stringify(updates)
  179. const bytes = Buffer.from(blob).byteLength
  180. const read = new ReadableString(blob)
  181. const compress = zlib.createGzip()
  182. const write = new WritableBuffer()
  183. await Stream.promises.pipeline(read, compress, write)
  184. const bytesGz = write.size()
  185. return { bytes, bytesGz, nUpdates: updates.length }
  186. }
  187. /**
  188. * @param {Update[]} rawUpdates
  189. * @param {string} projectId
  190. * @param {import("./Profiler").Profiler} profile
  191. * @return {Promise<Update[]>}
  192. */
  193. async function compressRawUpdatesWithMetrics(rawUpdates, projectId, profile) {
  194. if (100 * Math.random() > Settings.estimateCompressionSample) {
  195. return compressRawUpdatesWithProfile(rawUpdates, projectId, profile)
  196. }
  197. const before = await estimateStorage(rawUpdates)
  198. profile.log('estimateRawUpdatesSize')
  199. const updates = compressRawUpdatesWithProfile(rawUpdates, projectId, profile)
  200. const after = await estimateStorage(updates)
  201. for (const [path, values] of Object.entries({ before, after })) {
  202. for (const [method, v] of Object.entries(values)) {
  203. Metrics.summary('updates_compression_estimate', v, { path, method })
  204. }
  205. }
  206. for (const method of Object.keys(before)) {
  207. const percentage = Math.ceil(100 * (after[method] / before[method]))
  208. Metrics.summary('updates_compression_percentage', percentage, { method })
  209. }
  210. profile.log('estimateCompressedUpdatesSize')
  211. return updates
  212. }
  213. export const compressRawUpdatesWithMetricsCb = callbackify(
  214. compressRawUpdatesWithMetrics
  215. )
  216. /**
  217. * @param {Update[]} rawUpdates
  218. * @param {string} projectId
  219. * @param {import("./Profiler").Profiler} profile
  220. * @return {Update[]}
  221. */
  222. function compressRawUpdatesWithProfile(rawUpdates, projectId, profile) {
  223. const updates = compressRawUpdates(rawUpdates)
  224. const timeTaken = profile.log('compressRawUpdates').getTimeDelta()
  225. if (timeTaken >= 1000) {
  226. logger.debug(
  227. { projectId, updates: rawUpdates, timeTaken },
  228. 'slow compression of raw updates'
  229. )
  230. }
  231. return updates
  232. }
  233. export function compressRawUpdates(rawUpdates) {
  234. let updates = convertToSingleOpUpdates(rawUpdates)
  235. updates = compressUpdates(updates)
  236. updates = filterBlankUpdates(updates)
  237. updates = concatUpdatesWithSameVersion(updates)
  238. return updates
  239. }
  240. export function compressUpdates(updates) {
  241. if (updates.length === 0) {
  242. return []
  243. }
  244. let compressedUpdates = [updates.shift()]
  245. for (const update of updates) {
  246. const lastCompressedUpdate = compressedUpdates.pop()
  247. if (lastCompressedUpdate != null) {
  248. const newCompressedUpdates = _concatTwoUpdates(
  249. lastCompressedUpdate,
  250. update
  251. )
  252. compressedUpdates = compressedUpdates.concat(newCompressedUpdates)
  253. } else {
  254. compressedUpdates.push(update)
  255. }
  256. }
  257. return compressedUpdates
  258. }
  259. /**
  260. * If possible, merge two updates into a single update that has the same effect.
  261. *
  262. * It's useful to do some of this work at this point while we're dealing with
  263. * document-updater updates. The deletes, in particular include the deleted
  264. * text. This allows us to find pieces of inserts and deletes that cancel each
  265. * other out because they insert/delete the exact same text. This compression
  266. * makes the diff smaller.
  267. */
  268. function _concatTwoUpdates(firstUpdate, secondUpdate) {
  269. // Previously we cloned firstUpdate and secondUpdate at this point but we
  270. // can skip this step because whenever they are returned with
  271. // modification there is always a clone at that point via
  272. // mergeUpdatesWithOp.
  273. if (firstUpdate.op == null || secondUpdate.op == null) {
  274. // Project structure ops
  275. return [firstUpdate, secondUpdate]
  276. }
  277. const firstUpdateIsHistoryOT = EditOperationBuilder.isValid(firstUpdate.op)
  278. const secondUpdateIsHistoryOT = EditOperationBuilder.isValid(secondUpdate.op)
  279. if (firstUpdateIsHistoryOT !== secondUpdateIsHistoryOT) {
  280. // cannot merge mix of sharejs-text-op and history-ot, should not happen.
  281. return [firstUpdate, secondUpdate]
  282. }
  283. if (
  284. firstUpdate.doc !== secondUpdate.doc ||
  285. firstUpdate.pathname !== secondUpdate.pathname
  286. ) {
  287. return [firstUpdate, secondUpdate]
  288. }
  289. if (firstUpdate.meta.user_id !== secondUpdate.meta.user_id) {
  290. return [firstUpdate, secondUpdate]
  291. }
  292. if (
  293. (firstUpdate.meta.type === 'external' &&
  294. secondUpdate.meta.type !== 'external') ||
  295. (firstUpdate.meta.type !== 'external' &&
  296. secondUpdate.meta.type === 'external') ||
  297. (firstUpdate.meta.type === 'external' &&
  298. secondUpdate.meta.type === 'external' &&
  299. firstUpdate.meta.source !== secondUpdate.meta.source)
  300. ) {
  301. return [firstUpdate, secondUpdate]
  302. }
  303. if (secondUpdate.meta.ts - firstUpdate.meta.ts > MAX_TIME_BETWEEN_UPDATES) {
  304. return [firstUpdate, secondUpdate]
  305. }
  306. if (
  307. (firstUpdate.meta.tc == null && secondUpdate.meta.tc != null) ||
  308. (firstUpdate.meta.tc != null && secondUpdate.meta.tc == null)
  309. ) {
  310. // One update is tracking changes and the other isn't. Tracking changes
  311. // results in different behaviour in the history, so we need to keep these
  312. // two updates separate.
  313. return [firstUpdate, secondUpdate]
  314. }
  315. if (Boolean(firstUpdate.op.u) !== Boolean(secondUpdate.op.u)) {
  316. // One update is an undo and the other isn't. If we were to merge the two
  317. // updates, we would have to choose one value for the flag, which would be
  318. // partially incorrect. Moreover, a tracked delete that is also an undo is
  319. // treated as a tracked insert rejection by the history, so these updates
  320. // need to be well separated.
  321. return [firstUpdate, secondUpdate]
  322. }
  323. if (firstUpdateIsHistoryOT && secondUpdateIsHistoryOT) {
  324. const op1 = EditOperationBuilder.fromJSON(firstUpdate.op)
  325. const op2 = EditOperationBuilder.fromJSON(secondUpdate.op)
  326. if (!op1.canBeComposedWith(op2)) return [firstUpdate, secondUpdate]
  327. return [
  328. mergeUpdatesWithOp(firstUpdate, secondUpdate, op1.compose(op2).toJSON()),
  329. ]
  330. }
  331. if (
  332. firstUpdate.op.trackedDeleteRejection ||
  333. secondUpdate.op.trackedDeleteRejection
  334. ) {
  335. // Do not merge tracked delete rejections. Each tracked delete rejection is
  336. // a separate operation.
  337. return [firstUpdate, secondUpdate]
  338. }
  339. if (
  340. firstUpdate.op.trackedChanges != null ||
  341. secondUpdate.op.trackedChanges != null
  342. ) {
  343. // Do not merge ops that span tracked changes.
  344. // TODO: This could theoretically be handled, but it would be complex. One
  345. // would need to take tracked deletes into account when merging inserts and
  346. // deletes together.
  347. return [firstUpdate, secondUpdate]
  348. }
  349. const firstOp = firstUpdate.op
  350. const secondOp = secondUpdate.op
  351. const firstSize =
  352. (firstOp.i && firstOp.i.length) || (firstOp.d && firstOp.d.length)
  353. const secondSize =
  354. (secondOp.i && secondOp.i.length) || (secondOp.d && secondOp.d.length)
  355. const firstOpInsideSecondOp =
  356. secondOp.p <= firstOp.p && firstOp.p <= secondOp.p + secondSize
  357. const secondOpInsideFirstOp =
  358. firstOp.p <= secondOp.p && secondOp.p <= firstOp.p + firstSize
  359. const combinedLengthUnderLimit = firstSize + secondSize < MAX_UPDATE_SIZE
  360. // Two inserts
  361. if (
  362. firstOp.i != null &&
  363. secondOp.i != null &&
  364. secondOpInsideFirstOp &&
  365. combinedLengthUnderLimit &&
  366. insertOpsInsideSameComments(firstOp, secondOp)
  367. ) {
  368. return [
  369. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  370. ...firstOp,
  371. i: strInject(firstOp.i, secondOp.p - firstOp.p, secondOp.i),
  372. }),
  373. ]
  374. }
  375. // Two deletes
  376. if (
  377. firstOp.d != null &&
  378. secondOp.d != null &&
  379. firstOpInsideSecondOp &&
  380. combinedLengthUnderLimit &&
  381. firstUpdate.meta.tc == null &&
  382. secondUpdate.meta.tc == null
  383. ) {
  384. return [
  385. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  386. ...secondOp,
  387. d: strInject(secondOp.d, firstOp.p - secondOp.p, firstOp.d),
  388. }),
  389. ]
  390. }
  391. // An insert and then a delete
  392. if (
  393. firstOp.i != null &&
  394. secondOp.d != null &&
  395. secondOpInsideFirstOp &&
  396. firstUpdate.meta.tc == null &&
  397. secondUpdate.meta.tc == null
  398. ) {
  399. const offset = secondOp.p - firstOp.p
  400. const insertedText = firstOp.i.slice(offset, offset + secondOp.d.length)
  401. // Only trim the insert when the delete is fully contained within in it
  402. if (insertedText === secondOp.d) {
  403. const insert = strRemove(firstOp.i, offset, secondOp.d.length)
  404. if (insert === '') {
  405. return []
  406. } else {
  407. return [
  408. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  409. ...firstOp,
  410. i: insert,
  411. }),
  412. ]
  413. }
  414. } else {
  415. // This will only happen if the delete extends outside the insert
  416. return [firstUpdate, secondUpdate]
  417. }
  418. }
  419. // A delete then an insert at the same place, likely a copy-paste of a chunk of content
  420. if (
  421. firstOp.d != null &&
  422. secondOp.i != null &&
  423. firstOp.p === secondOp.p &&
  424. firstUpdate.meta.tc == null &&
  425. secondUpdate.meta.tc == null
  426. ) {
  427. const offset = firstOp.p
  428. const hoffset = firstOp.hpos
  429. const diffUpdates = diffAsShareJsOps(firstOp.d, secondOp.i).map(
  430. function (op) {
  431. // diffAsShareJsOps() returns ops with positions relative to the position
  432. // of the copy/paste. We need to adjust these positions so that they
  433. // apply to the whole document instead.
  434. const pos = op.p
  435. op.p = pos + offset
  436. if (hoffset != null) {
  437. op.hpos = pos + hoffset
  438. }
  439. if (firstOp.u && secondOp.u) {
  440. op.u = true
  441. }
  442. if ('i' in op && secondOp.commentIds != null) {
  443. // Make sure that commentIds metadata is propagated to inserts
  444. op.commentIds = secondOp.commentIds
  445. }
  446. const update = mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  447. // Set the doc hash only on the last update
  448. delete update.meta.doc_hash
  449. return update
  450. }
  451. )
  452. const docHash = secondUpdate.meta.doc_hash
  453. if (docHash != null && diffUpdates.length > 0) {
  454. diffUpdates[diffUpdates.length - 1].meta.doc_hash = docHash
  455. }
  456. // Doing a diff like this loses track of the doc lengths for each
  457. // update, so recalculate them
  458. let docLength =
  459. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  460. for (const update of diffUpdates) {
  461. update.meta.doc_length = docLength
  462. docLength = adjustLengthByOp(docLength, update.op, {
  463. tracked: update.meta.tc != null,
  464. })
  465. delete update.meta.history_doc_length
  466. }
  467. return diffUpdates
  468. }
  469. return [firstUpdate, secondUpdate]
  470. }
  471. /**
  472. * Return the diff between two strings
  473. *
  474. * @param {string} before
  475. * @param {string} after
  476. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  477. */
  478. export function diffAsShareJsOps(before, after) {
  479. const diffs = dmp.diff_main(before, after)
  480. dmp.diff_cleanupSemantic(diffs)
  481. const ops = []
  482. let position = 0
  483. for (const diff of diffs) {
  484. const [type, content] = diff
  485. if (type === ADDED) {
  486. ops.push({
  487. i: content,
  488. p: position,
  489. })
  490. position += content.length
  491. } else if (type === REMOVED) {
  492. ops.push({
  493. d: content,
  494. p: position,
  495. })
  496. } else if (type === UNCHANGED) {
  497. position += content.length
  498. } else {
  499. throw new Error('Unknown type')
  500. }
  501. }
  502. return ops
  503. }
  504. /**
  505. * Checks if two insert ops are inside the same comments
  506. *
  507. * @param {InsertOp} op1
  508. * @param {InsertOp} op2
  509. * @returns {boolean}
  510. */
  511. function insertOpsInsideSameComments(op1, op2) {
  512. const commentIds1 = op1.commentIds
  513. const commentIds2 = op2.commentIds
  514. if (commentIds1 == null && commentIds2 == null) {
  515. // None are inside comments
  516. return true
  517. }
  518. if (
  519. commentIds1 != null &&
  520. commentIds2 != null &&
  521. commentIds1.every(id => commentIds2.includes(id)) &&
  522. commentIds2.every(id => commentIds1.includes(id))
  523. ) {
  524. // Both are inside the same comments
  525. return true
  526. }
  527. return false
  528. }