UpdateCompressor.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. // Two inserts
  363. if (
  364. firstOp.i != null &&
  365. secondOp.i != null &&
  366. secondOpInsideFirstOp &&
  367. combinedLengthUnderLimit &&
  368. insertOpsInsideSameComments(firstOp, secondOp)
  369. ) {
  370. return [
  371. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  372. ...firstOp,
  373. i: strInject(firstOp.i, secondOp.p - firstOp.p, secondOp.i),
  374. }),
  375. ]
  376. }
  377. // Two deletes
  378. if (
  379. firstOp.d != null &&
  380. secondOp.d != null &&
  381. firstOpInsideSecondOp &&
  382. combinedLengthUnderLimit &&
  383. firstUpdate.meta.tc == null &&
  384. secondUpdate.meta.tc == null
  385. ) {
  386. return [
  387. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  388. ...secondOp,
  389. d: strInject(secondOp.d, firstOp.p - secondOp.p, firstOp.d),
  390. }),
  391. ]
  392. }
  393. // An insert and then a delete
  394. if (
  395. firstOp.i != null &&
  396. secondOp.d != null &&
  397. secondOpInsideFirstOp &&
  398. firstUpdate.meta.tc == null &&
  399. secondUpdate.meta.tc == null
  400. ) {
  401. const offset = secondOp.p - firstOp.p
  402. const insertedText = firstOp.i.slice(offset, offset + secondOp.d.length)
  403. // Only trim the insert when the delete is fully contained within in it
  404. if (insertedText === secondOp.d) {
  405. const insert = strRemove(firstOp.i, offset, secondOp.d.length)
  406. if (insert === '') {
  407. return []
  408. } else {
  409. return [
  410. mergeUpdatesWithOp(firstUpdate, secondUpdate, {
  411. ...firstOp,
  412. i: insert,
  413. }),
  414. ]
  415. }
  416. } else {
  417. // This will only happen if the delete extends outside the insert
  418. return [firstUpdate, secondUpdate]
  419. }
  420. }
  421. // A delete then an insert at the same place, likely a copy-paste of a chunk of content
  422. if (
  423. firstOp.d != null &&
  424. secondOp.i != null &&
  425. firstOp.p === secondOp.p &&
  426. firstUpdate.meta.tc == null &&
  427. secondUpdate.meta.tc == null
  428. ) {
  429. const offset = firstOp.p
  430. const hoffset = firstOp.hpos
  431. const diffUpdates = diffAsShareJsOps(firstOp.d, secondOp.i).map(
  432. function (op) {
  433. // diffAsShareJsOps() returns ops with positions relative to the position
  434. // of the copy/paste. We need to adjust these positions so that they
  435. // apply to the whole document instead.
  436. const pos = op.p
  437. op.p = pos + offset
  438. if (hoffset != null) {
  439. op.hpos = pos + hoffset
  440. }
  441. if (firstOp.u && secondOp.u) {
  442. op.u = true
  443. }
  444. if ('i' in op && secondOp.commentIds != null) {
  445. // Make sure that commentIds metadata is propagated to inserts
  446. op.commentIds = secondOp.commentIds
  447. }
  448. const update = mergeUpdatesWithOp(firstUpdate, secondUpdate, op)
  449. // Set the doc hash only on the last update
  450. delete update.meta.doc_hash
  451. return update
  452. }
  453. )
  454. const docHash = secondUpdate.meta.doc_hash
  455. if (docHash != null && diffUpdates.length > 0) {
  456. diffUpdates[diffUpdates.length - 1].meta.doc_hash = docHash
  457. }
  458. // Doing a diff like this loses track of the doc lengths for each
  459. // update, so recalculate them
  460. let docLength =
  461. firstUpdate.meta.history_doc_length ?? firstUpdate.meta.doc_length
  462. for (const update of diffUpdates) {
  463. update.meta.doc_length = docLength
  464. docLength = adjustLengthByOp(docLength, update.op, {
  465. tracked: update.meta.tc != null,
  466. })
  467. delete update.meta.history_doc_length
  468. }
  469. return diffUpdates
  470. }
  471. return [firstUpdate, secondUpdate]
  472. }
  473. /**
  474. * Return the diff between two strings
  475. *
  476. * @param {string} before
  477. * @param {string} after
  478. * @returns {(InsertOp | DeleteOp)[]} the ops that generate that diff
  479. */
  480. export function diffAsShareJsOps(before, after) {
  481. const diffs = dmp.diff_main(before, after)
  482. dmp.diff_cleanupSemantic(diffs)
  483. const ops = []
  484. let position = 0
  485. for (const diff of diffs) {
  486. const [type, content] = diff
  487. if (type === ADDED) {
  488. ops.push({
  489. i: content,
  490. p: position,
  491. })
  492. position += content.length
  493. } else if (type === REMOVED) {
  494. ops.push({
  495. d: content,
  496. p: position,
  497. })
  498. } else if (type === UNCHANGED) {
  499. position += content.length
  500. } else {
  501. throw new Error('Unknown type')
  502. }
  503. }
  504. return ops
  505. }
  506. /**
  507. * Checks if two insert ops are inside the same comments
  508. *
  509. * @param {InsertOp} op1
  510. * @param {InsertOp} op2
  511. * @returns {boolean}
  512. */
  513. function insertOpsInsideSameComments(op1, op2) {
  514. const commentIds1 = op1.commentIds
  515. const commentIds2 = op2.commentIds
  516. if (commentIds1 == null && commentIds2 == null) {
  517. // None are inside comments
  518. return true
  519. }
  520. if (
  521. commentIds1 != null &&
  522. commentIds2 != null &&
  523. commentIds1.every(id => commentIds2.includes(id)) &&
  524. commentIds2.every(id => commentIds1.includes(id))
  525. ) {
  526. // Both are inside the same comments
  527. return true
  528. }
  529. return false
  530. }