SyncManager.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. // @ts-check
  2. import _ from 'lodash'
  3. import { callbackify, promisify } from 'node:util'
  4. import { callbackifyMultiResult } from '@overleaf/promise-utils'
  5. import Settings from '@overleaf/settings'
  6. import logger from '@overleaf/logger'
  7. import Metrics from '@overleaf/metrics'
  8. import OError from '@overleaf/o-error'
  9. import { File, Range } from 'overleaf-editor-core'
  10. import { NeedFullProjectStructureResyncError, SyncError } from './Errors.js'
  11. import { db, ObjectId } from './mongodb.js'
  12. import * as SnapshotManager from './SnapshotManager.js'
  13. import * as LockManager from './LockManager.js'
  14. import * as UpdateTranslator from './UpdateTranslator.js'
  15. import * as UpdateCompressor from './UpdateCompressor.js'
  16. import * as WebApiManager from './WebApiManager.js'
  17. import * as ErrorRecorder from './ErrorRecorder.js'
  18. import * as RedisManager from './RedisManager.js'
  19. import * as HistoryStoreManager from './HistoryStoreManager.js'
  20. import * as HashManager from './HashManager.js'
  21. import { isInsert, isDelete } from './Utils.js'
  22. /**
  23. * @import { Comment as HistoryComment, TrackedChange as HistoryTrackedChange } from 'overleaf-editor-core'
  24. * @import { CommentRawData, TrackedChangeRawData } from 'overleaf-editor-core/lib/types'
  25. * @import { Comment, Entity, ResyncDocContentUpdate, RetainOp, TrackedChange } from './types'
  26. * @import { TrackedChangeTransition, TrackingDirective, TrackingType, Update } from './types'
  27. * @import { ProjectStructureUpdate } from './types'
  28. */
  29. const MAX_RESYNC_HISTORY_RECORDS = 100 // keep this many records of previous resyncs
  30. const EXPIRE_RESYNC_HISTORY_INTERVAL_MS = 90 * 24 * 3600 * 1000 // 90 days
  31. const keys = Settings.redis.lock.key_schema
  32. // db.projectHistorySyncState.ensureIndex({expiresAt: 1}, {expireAfterSeconds: 0, background: true})
  33. // To add expiresAt field to existing entries in collection (choose a suitable future expiry date):
  34. // db.projectHistorySyncState.updateMany({resyncProjectStructure: false, resyncDocContents: [], expiresAt: {$exists:false}}, {$set: {expiresAt: new Date("2019-07-01")}})
  35. async function startResync(projectId, options = {}) {
  36. // We have three options here
  37. //
  38. // 1. If we update mongo before making the call to web then there's a
  39. // chance we ignore all updates indefinitely (there's no foolproff way
  40. // to undo the change in mongo)
  41. //
  42. // 2. If we make the call to web first then there is a small race condition
  43. // where we could process the sync update and then only update mongo
  44. // after, causing all updates to be ignored from then on
  45. //
  46. // 3. We can wrap everything in a project lock
  47. Metrics.inc('project_history_resync')
  48. try {
  49. await LockManager.promises.runWithLock(
  50. keys.projectHistoryLock({ project_id: projectId }),
  51. async extendLock => {
  52. await startResyncWithoutLock(projectId, options)
  53. }
  54. )
  55. } catch (error) {
  56. // record error in starting sync ("sync ongoing")
  57. if (error instanceof Error) {
  58. await ErrorRecorder.promises.record(projectId, -1, error)
  59. }
  60. throw error
  61. }
  62. }
  63. async function startHardResync(projectId, options = {}) {
  64. Metrics.inc('project_history_hard_resync')
  65. try {
  66. await LockManager.promises.runWithLock(
  67. keys.projectHistoryLock({ project_id: projectId }),
  68. async extendLock => {
  69. await clearResyncState(projectId)
  70. await RedisManager.promises.clearFirstOpTimestamp(projectId)
  71. await RedisManager.promises.destroyDocUpdatesQueue(projectId)
  72. await startResyncWithoutLock(projectId, options)
  73. }
  74. )
  75. } catch (error) {
  76. // record error in starting sync ("sync ongoing")
  77. if (error instanceof Error) {
  78. await ErrorRecorder.promises.record(projectId, -1, error)
  79. }
  80. throw error
  81. }
  82. }
  83. // The caller must hold the lock and should record any errors via the ErrorRecorder.
  84. async function startResyncWithoutLock(projectId, options) {
  85. await ErrorRecorder.promises.recordSyncStart(projectId)
  86. const syncState = await _getResyncState(projectId)
  87. if (syncState.isSyncOngoing()) {
  88. throw new OError('sync ongoing')
  89. }
  90. syncState.setOrigin(options.origin || { kind: 'history-resync' })
  91. syncState.startProjectStructureSync()
  92. const webOpts = {}
  93. if (options.historyRangesMigration) {
  94. webOpts.historyRangesMigration = options.historyRangesMigration
  95. }
  96. if (options.resyncProjectStructureOnly) {
  97. webOpts.resyncProjectStructureOnly = options.resyncProjectStructureOnly
  98. }
  99. await WebApiManager.promises.requestResync(projectId, webOpts)
  100. await setResyncState(projectId, syncState)
  101. }
  102. async function _getResyncState(projectId) {
  103. const rawSyncState = await db.projectHistorySyncState.findOne({
  104. project_id: new ObjectId(projectId.toString()),
  105. })
  106. const syncState = SyncState.fromRaw(projectId, rawSyncState)
  107. return syncState
  108. }
  109. async function setResyncState(projectId, syncState) {
  110. // skip if syncState is null (i.e. unchanged)
  111. if (syncState == null) {
  112. return
  113. }
  114. const update = {
  115. $set: syncState.toRaw(),
  116. $push: {
  117. history: {
  118. $each: [{ syncState: syncState.toRaw(), timestamp: new Date() }],
  119. $position: 0,
  120. $slice: MAX_RESYNC_HISTORY_RECORDS,
  121. },
  122. },
  123. $currentDate: { lastUpdated: true },
  124. }
  125. // handle different cases
  126. if (syncState.isSyncOngoing()) {
  127. // starting a new sync; prevent the entry expiring while sync is in ongoing
  128. update.$inc = { resyncCount: 1 }
  129. update.$unset = { expiresAt: true }
  130. } else {
  131. // successful completion of existing sync; set the entry to expire in the
  132. // future
  133. update.$set.expiresAt = new Date(
  134. Date.now() + EXPIRE_RESYNC_HISTORY_INTERVAL_MS
  135. )
  136. }
  137. // apply the update
  138. await db.projectHistorySyncState.updateOne(
  139. { project_id: new ObjectId(projectId) },
  140. update,
  141. { upsert: true }
  142. )
  143. }
  144. async function clearResyncState(projectId) {
  145. await db.projectHistorySyncState.deleteOne({
  146. project_id: new ObjectId(projectId.toString()),
  147. })
  148. }
  149. /**
  150. * @param {string} projectId
  151. * @param {Date} date
  152. * @return {Promise<void>}
  153. */
  154. async function clearResyncStateIfAllAfter(projectId, date) {
  155. const rawSyncState = await db.projectHistorySyncState.findOne({
  156. project_id: new ObjectId(projectId.toString()),
  157. })
  158. if (!rawSyncState) return // already cleared
  159. const state = SyncState.fromRaw(projectId, rawSyncState)
  160. if (state.isSyncOngoing()) return // new sync started
  161. for (const { timestamp } of rawSyncState.history) {
  162. if (timestamp < date) return // preserve old resync states
  163. }
  164. // expiresAt is cleared when starting a sync and bumped when making changes.
  165. // Use expiresAt as read to ensure we only clear the confirmed state.
  166. await db.projectHistorySyncState.deleteOne({
  167. project_id: new ObjectId(projectId.toString()),
  168. expiresAt: rawSyncState.expiresAt,
  169. })
  170. }
  171. async function skipUpdatesDuringSync(projectId, updates) {
  172. const syncState = await _getResyncState(projectId)
  173. if (!syncState.isSyncOngoing()) {
  174. logger.debug({ projectId }, 'not skipping updates: no resync in progress')
  175. // don't return syncState when unchanged
  176. return { updates, syncState: null }
  177. }
  178. const filteredUpdates = []
  179. for (const update of updates) {
  180. syncState.updateState(update)
  181. const shouldSkipUpdate = syncState.shouldSkipUpdate(update)
  182. if (!shouldSkipUpdate) {
  183. filteredUpdates.push(update)
  184. } else {
  185. logger.debug({ projectId, update }, 'skipping update due to resync')
  186. }
  187. }
  188. return { updates: filteredUpdates, syncState }
  189. }
  190. /**
  191. * @param {string} projectId
  192. * @param {string} projectHistoryId
  193. * @param {{chunk: import('overleaf-editor-core/lib/types.js').RawChunk}} mostRecentChunk
  194. * @param {Array<Update>} updates
  195. * @param {() => Promise<void>} extendLock
  196. * @return {Promise<Array<Update>>}
  197. */
  198. async function expandSyncUpdates(
  199. projectId,
  200. projectHistoryId,
  201. mostRecentChunk,
  202. updates,
  203. extendLock
  204. ) {
  205. const areSyncUpdatesQueued =
  206. _.some(updates, 'resyncProjectStructure') ||
  207. _.some(updates, 'resyncDocContent')
  208. if (!areSyncUpdatesQueued) {
  209. logger.debug({ projectId }, 'no resync updates to expand')
  210. return updates
  211. }
  212. const syncState = await _getResyncState(projectId)
  213. // compute the current snapshot from the most recent chunk
  214. const snapshotFiles =
  215. await SnapshotManager.promises.getLatestSnapshotFilesForChunk(
  216. projectHistoryId,
  217. mostRecentChunk
  218. )
  219. // check if snapshot files are valid
  220. const invalidFiles = _.pickBy(
  221. snapshotFiles,
  222. (v, k) => v == null || typeof v.isEditable !== 'function'
  223. )
  224. if (_.size(invalidFiles) > 0) {
  225. throw new SyncError('file is missing isEditable method', {
  226. projectId,
  227. invalidFiles,
  228. })
  229. }
  230. const expander = new SyncUpdateExpander(
  231. projectId,
  232. snapshotFiles,
  233. syncState.origin
  234. )
  235. // expand updates asynchronously to avoid blocking
  236. for (const update of updates) {
  237. await expander.expandUpdate(update)
  238. await extendLock()
  239. }
  240. return expander.getExpandedUpdates()
  241. }
  242. class SyncState {
  243. constructor(projectId, resyncProjectStructure, resyncDocContents, origin) {
  244. this.projectId = projectId
  245. this.resyncProjectStructure = resyncProjectStructure
  246. this.resyncDocContents = resyncDocContents
  247. this.origin = origin
  248. }
  249. static fromRaw(projectId, rawSyncState) {
  250. rawSyncState = rawSyncState || {}
  251. const resyncProjectStructure = rawSyncState.resyncProjectStructure || false
  252. const resyncDocContents = new Set(rawSyncState.resyncDocContents || [])
  253. const origin = rawSyncState.origin
  254. return new SyncState(
  255. projectId,
  256. resyncProjectStructure,
  257. resyncDocContents,
  258. origin
  259. )
  260. }
  261. toRaw() {
  262. return {
  263. resyncProjectStructure: this.resyncProjectStructure,
  264. resyncDocContents: Array.from(this.resyncDocContents),
  265. origin: this.origin,
  266. }
  267. }
  268. updateState(update) {
  269. if (update.resyncProjectStructure != null) {
  270. if (!this.isProjectStructureSyncing()) {
  271. throw new SyncError('unexpected resyncProjectStructure update', {
  272. projectId: this.projectId,
  273. resyncProjectStructure: this.resyncProjectStructure,
  274. })
  275. }
  276. if (this.isAnyDocContentSyncing()) {
  277. throw new SyncError('unexpected resyncDocContents update', {
  278. projectId: this.projectId,
  279. resyncDocContents: this.resyncDocContents,
  280. })
  281. }
  282. if (!update.resyncProjectStructureOnly) {
  283. for (const doc of update.resyncProjectStructure.docs) {
  284. this.startDocContentSync(doc.path)
  285. }
  286. }
  287. this.stopProjectStructureSync()
  288. } else if (update.resyncDocContent != null) {
  289. if (this.isProjectStructureSyncing()) {
  290. throw new SyncError('unexpected resyncDocContent update', {
  291. projectId: this.projectId,
  292. resyncProjectStructure: this.resyncProjectStructure,
  293. })
  294. }
  295. if (!this.isDocContentSyncing(update.path)) {
  296. throw new SyncError('unexpected resyncDocContent update', {
  297. projectId: this.projectId,
  298. resyncDocContents: this.resyncDocContents,
  299. path: update.path,
  300. })
  301. }
  302. this.stopDocContentSync(update.path)
  303. }
  304. }
  305. setOrigin(origin) {
  306. this.origin = origin
  307. }
  308. shouldSkipUpdate(update) {
  309. // don't skip sync updates
  310. if (
  311. update.resyncProjectStructure != null ||
  312. update.resyncDocContent != null
  313. ) {
  314. return false
  315. }
  316. // if syncing project structure skip update
  317. if (this.isProjectStructureSyncing()) {
  318. return true
  319. }
  320. // skip text updates for a docs being synced
  321. if (UpdateTranslator.isTextUpdate(update)) {
  322. if (this.isDocContentSyncing(update.meta.pathname)) {
  323. return true
  324. }
  325. }
  326. // preserve all other updates
  327. return false
  328. }
  329. startProjectStructureSync() {
  330. this.resyncProjectStructure = true
  331. this.resyncDocContents = new Set([])
  332. }
  333. stopProjectStructureSync() {
  334. this.resyncProjectStructure = false
  335. }
  336. stopDocContentSync(pathname) {
  337. this.resyncDocContents.delete(pathname)
  338. }
  339. startDocContentSync(pathname) {
  340. this.resyncDocContents.add(pathname)
  341. }
  342. isProjectStructureSyncing() {
  343. return this.resyncProjectStructure
  344. }
  345. isDocContentSyncing(pathname) {
  346. return this.resyncDocContents.has(pathname)
  347. }
  348. isAnyDocContentSyncing() {
  349. return this.resyncDocContents.size > 0
  350. }
  351. isSyncOngoing() {
  352. return this.isProjectStructureSyncing() || this.isAnyDocContentSyncing()
  353. }
  354. }
  355. class SyncUpdateExpander {
  356. /**
  357. * Build a SyncUpdateExpander
  358. *
  359. * @param {string} projectId
  360. * @param {Record<string, File>} snapshotFiles
  361. * @param {string} origin
  362. */
  363. constructor(projectId, snapshotFiles, origin) {
  364. this.projectId = projectId
  365. this.files = snapshotFiles
  366. this.expandedUpdates = /** @type ProjectStructureUpdate[] */ []
  367. this.origin = origin
  368. }
  369. // If there's an expected *file* with the same path and either the same hash
  370. // or no hash, treat this as not editable even if history thinks it is.
  371. isEditable(filePath, file, expectedFiles) {
  372. if (!file.isEditable()) {
  373. return false
  374. }
  375. const fileHash = _.get(file, ['data', 'hash'])
  376. const matchedExpectedFile = expectedFiles.some(item => {
  377. const expectedFileHash = item._hash
  378. if (expectedFileHash && fileHash !== expectedFileHash) {
  379. // expected file has a hash and it doesn't match
  380. return false
  381. }
  382. return UpdateTranslator._convertPathname(item.path) === filePath
  383. })
  384. // consider editable file in history as binary, since it matches a binary file in the project
  385. return !matchedExpectedFile
  386. }
  387. /**
  388. * @param {Update} update
  389. */
  390. async expandUpdate(update) {
  391. if ('resyncProjectStructure' in update) {
  392. logger.debug(
  393. { projectId: this.projectId, update },
  394. 'expanding resyncProjectStructure update'
  395. )
  396. const persistedNonBinaryFileEntries = _.pickBy(this.files, (v, k) =>
  397. this.isEditable(k, v, update.resyncProjectStructure.files)
  398. )
  399. const persistedNonBinaryFiles = _.map(
  400. Object.keys(persistedNonBinaryFileEntries),
  401. path => ({
  402. path,
  403. })
  404. )
  405. const persistedBinaryFileEntries = _.omitBy(this.files, (v, k) =>
  406. this.isEditable(k, v, update.resyncProjectStructure.files)
  407. )
  408. // preserve file properties on binary files, for future comparison.
  409. const persistedBinaryFiles = _.map(
  410. persistedBinaryFileEntries,
  411. (entity, key) => Object.assign({}, entity, { path: key })
  412. )
  413. const expectedNonBinaryFiles = _.map(
  414. update.resyncProjectStructure.docs,
  415. entity =>
  416. Object.assign({}, entity, {
  417. path: UpdateTranslator._convertPathname(entity.path),
  418. })
  419. )
  420. const expectedBinaryFiles = _.map(
  421. update.resyncProjectStructure.files,
  422. entity =>
  423. Object.assign({}, entity, {
  424. path: UpdateTranslator._convertPathname(entity.path),
  425. })
  426. )
  427. // We need to detect and fix consistency issues where web and
  428. // history-store disagree on whether an entity is binary or not. Thus we
  429. // need to remove and add the two separately.
  430. this.queueRemoveOpsForUnexpectedFiles(
  431. update,
  432. expectedBinaryFiles,
  433. persistedBinaryFiles
  434. )
  435. this.queueRemoveOpsForUnexpectedFiles(
  436. update,
  437. expectedNonBinaryFiles,
  438. persistedNonBinaryFiles
  439. )
  440. this.queueAddOpsForMissingFiles(
  441. update,
  442. expectedBinaryFiles,
  443. persistedBinaryFiles
  444. )
  445. this.queueAddOpsForMissingFiles(
  446. update,
  447. expectedNonBinaryFiles,
  448. persistedNonBinaryFiles
  449. )
  450. this.queueUpdateForOutOfSyncBinaryFiles(
  451. update,
  452. expectedBinaryFiles,
  453. persistedBinaryFiles
  454. )
  455. this.queueSetMetadataOpsForLinkedFiles(update)
  456. if (update.resyncProjectStructureOnly) {
  457. const docPaths = new Set()
  458. for (const entity of update.resyncProjectStructure.docs) {
  459. const path = UpdateTranslator._convertPathname(entity.path)
  460. docPaths.add(path)
  461. }
  462. for (const expandedUpdate of this.expandedUpdates) {
  463. if (docPaths.has(expandedUpdate.pathname)) {
  464. // Clear the resync state and queue entry, we need to start over.
  465. this.expandedUpdates = []
  466. await clearResyncState(this.projectId)
  467. await RedisManager.promises.deleteAppliedDocUpdate(
  468. this.projectId,
  469. update
  470. )
  471. throw new NeedFullProjectStructureResyncError(
  472. 'aborting partial resync: touched doc'
  473. )
  474. }
  475. }
  476. }
  477. } else if ('resyncDocContent' in update) {
  478. logger.debug(
  479. { projectId: this.projectId, update },
  480. 'expanding resyncDocContent update'
  481. )
  482. await this.expandResyncDocContentUpdate(update)
  483. } else {
  484. this.expandedUpdates.push(update)
  485. }
  486. }
  487. getExpandedUpdates() {
  488. return this.expandedUpdates
  489. }
  490. /**
  491. * @param {Entity[]} expectedFiles
  492. * @param {{ path: string }[]} persistedFiles
  493. */
  494. queueRemoveOpsForUnexpectedFiles(update, expectedFiles, persistedFiles) {
  495. const unexpectedFiles = _.differenceBy(
  496. persistedFiles,
  497. expectedFiles,
  498. 'path'
  499. )
  500. for (const entity of unexpectedFiles) {
  501. update = {
  502. pathname: entity.path,
  503. new_pathname: '',
  504. meta: {
  505. resync: true,
  506. origin: this.origin,
  507. ts: update.meta.ts,
  508. },
  509. }
  510. this.expandedUpdates.push(update)
  511. Metrics.inc('project_history_resync_operation', 1, {
  512. status: 'remove unexpected file',
  513. })
  514. }
  515. }
  516. /**
  517. * @param {Entity[]} expectedFiles
  518. * @param {{ path: string }[]} persistedFiles
  519. */
  520. queueAddOpsForMissingFiles(update, expectedFiles, persistedFiles) {
  521. const missingFiles = _.differenceBy(expectedFiles, persistedFiles, 'path')
  522. for (const entity of missingFiles) {
  523. update = {
  524. pathname: entity.path,
  525. meta: {
  526. resync: true,
  527. origin: this.origin,
  528. ts: update.meta.ts,
  529. },
  530. }
  531. if ('doc' in entity) {
  532. update.doc = entity.doc
  533. update.docLines = ''
  534. // we have to create a dummy entry here because later we will need the content in the diff computation
  535. this.files[update.pathname] = File.fromString('')
  536. } else {
  537. update.file = entity.file
  538. if (entity.url) update.url = entity.url
  539. if (entity._hash) update.hash = entity._hash
  540. if (entity.createdBlob) update.createdBlob = entity.createdBlob
  541. if (entity.metadata) update.metadata = entity.metadata
  542. }
  543. this.expandedUpdates.push(update)
  544. Metrics.inc('project_history_resync_operation', 1, {
  545. status: 'add missing file',
  546. })
  547. }
  548. }
  549. queueSetMetadataOpsForLinkedFiles(update) {
  550. const allEntities = update.resyncProjectStructure.docs.concat(
  551. update.resyncProjectStructure.files
  552. )
  553. for (const file of allEntities) {
  554. const pathname = UpdateTranslator._convertPathname(file.path)
  555. const matchingAddFileOperation = this.expandedUpdates.some(
  556. // Look for an addFile operation that already syncs the metadata.
  557. u => u.pathname === pathname && u.metadata === file.metadata
  558. )
  559. if (matchingAddFileOperation) continue
  560. const metaData = this.files[pathname].getMetadata()
  561. let shouldUpdate = false
  562. if (file.metadata) {
  563. // check for in place update of linked-file
  564. shouldUpdate = Object.entries(file.metadata).some(
  565. ([k, v]) => metaData[k] !== v
  566. )
  567. } else if (metaData.provider) {
  568. // overwritten by non-linked-file with same hash
  569. // or overwritten by doc
  570. shouldUpdate = true
  571. }
  572. if (!shouldUpdate) continue
  573. this.expandedUpdates.push({
  574. pathname,
  575. meta: {
  576. resync: true,
  577. origin: this.origin,
  578. ts: update.meta.ts,
  579. },
  580. metadata: file.metadata || {},
  581. })
  582. Metrics.inc('project_history_resync_operation', 1, {
  583. status: 'update metadata',
  584. })
  585. }
  586. }
  587. queueUpdateForOutOfSyncBinaryFiles(update, expectedFiles, persistedFiles) {
  588. // create a map to lookup persisted files by their path
  589. const persistedFileMap = new Map(persistedFiles.map(x => [x.path, x]))
  590. // now search for files with same path but different hash values
  591. const differentFiles = expectedFiles.filter(expected => {
  592. // check for a persisted file at the same path
  593. const expectedPath = expected.path
  594. const persistedFileAtSamePath = persistedFileMap.get(expectedPath)
  595. if (!persistedFileAtSamePath) return false
  596. // check if the persisted file at the same path has a different hash
  597. const expectedHash = _.get(expected, '_hash')
  598. const persistedHash = _.get(persistedFileAtSamePath, ['data', 'hash'])
  599. const hashesPresent = expectedHash && persistedHash
  600. return hashesPresent && persistedHash !== expectedHash
  601. })
  602. for (const entity of differentFiles) {
  603. // remove the outdated persisted file
  604. const removeUpdate = {
  605. pathname: entity.path,
  606. new_pathname: '',
  607. meta: {
  608. resync: true,
  609. origin: this.origin,
  610. ts: update.meta.ts,
  611. },
  612. }
  613. this.expandedUpdates.push(removeUpdate)
  614. // add the new file content
  615. const addUpdate = {
  616. pathname: entity.path,
  617. meta: {
  618. resync: true,
  619. origin: this.origin,
  620. ts: update.meta.ts,
  621. },
  622. file: entity.file,
  623. }
  624. if (entity.url) addUpdate.url = entity.url
  625. if (entity._hash) addUpdate.hash = entity._hash
  626. if (entity.createdBlob) addUpdate.createdBlob = entity.createdBlob
  627. if (entity.metadata) addUpdate.metadata = entity.metadata
  628. this.expandedUpdates.push(addUpdate)
  629. Metrics.inc('project_history_resync_operation', 1, {
  630. status: 'update binary file contents',
  631. })
  632. }
  633. }
  634. /**
  635. * Expand a resyncDocContentUpdate
  636. *
  637. * @param {ResyncDocContentUpdate} update
  638. */
  639. async expandResyncDocContentUpdate(update) {
  640. const pathname = UpdateTranslator._convertPathname(update.path)
  641. const snapshotFile = this.files[pathname]
  642. const expectedFile = update.resyncDocContent
  643. const expectedContent = expectedFile.content
  644. if (!snapshotFile) {
  645. throw new OError('unrecognised file: not in snapshot')
  646. }
  647. // Compare hashes to see if the persisted file matches the expected content.
  648. // The hash of the persisted files is stored in the snapshot.
  649. // Note getHash() returns the hash only when the persisted file has
  650. // no changes in the snapshot, the hash is null if there are changes
  651. // that apply to it.
  652. let hashesMatch = false
  653. const persistedHash = snapshotFile.getHash()
  654. if (persistedHash != null) {
  655. const expectedHash = HashManager._getBlobHashFromString(expectedContent)
  656. if (persistedHash === expectedHash) {
  657. logger.debug(
  658. { projectId: this.projectId, persistedHash, expectedHash },
  659. 'skipping diff because hashes match and persisted file has no ops'
  660. )
  661. hashesMatch = true
  662. }
  663. } else {
  664. logger.debug('cannot compare hashes, will retrieve content')
  665. }
  666. // compute the difference between the expected and persisted content
  667. const historyId = await WebApiManager.promises.getHistoryId(this.projectId)
  668. const file = await snapshotFile.load(
  669. 'eager',
  670. HistoryStoreManager.getBlobStore(historyId)
  671. )
  672. const persistedContent = file.getContent()
  673. if (persistedContent == null) {
  674. // This should not happen given that we loaded the file eagerly. We could
  675. // probably refine the types in overleaf-editor-core so that this check
  676. // wouldn't be necessary.
  677. throw new Error('File was not properly loaded')
  678. }
  679. if (!hashesMatch) {
  680. const expandedUpdate = await this.queueUpdateForOutOfSyncContent(
  681. update,
  682. pathname,
  683. persistedContent,
  684. expectedContent
  685. )
  686. if (expandedUpdate != null) {
  687. // Adjust the ranges for the changes that have been made to the content
  688. for (const op of expandedUpdate.op) {
  689. if (isInsert(op)) {
  690. file.getComments().applyInsert(new Range(op.p, op.i.length))
  691. file.getTrackedChanges().applyInsert(op.p, op.i)
  692. } else if (isDelete(op)) {
  693. file.getComments().applyDelete(new Range(op.p, op.d.length))
  694. file.getTrackedChanges().applyDelete(op.p, op.d.length)
  695. }
  696. }
  697. }
  698. }
  699. const persistedComments = file.getComments().toArray()
  700. if (update.resyncDocContent.historyOTRanges) {
  701. this.queueUpdatesForOutOfSyncCommentsHistoryOT(
  702. update,
  703. pathname,
  704. file.getComments().toRaw()
  705. )
  706. } else {
  707. await this.queueUpdatesForOutOfSyncComments(
  708. update,
  709. pathname,
  710. persistedComments
  711. )
  712. }
  713. const persistedChanges = file.getTrackedChanges().asSorted()
  714. await this.queueUpdatesForOutOfSyncTrackedChanges(
  715. update,
  716. pathname,
  717. persistedChanges
  718. )
  719. }
  720. /**
  721. * Queue update for out of sync content
  722. *
  723. * @param {ResyncDocContentUpdate} update
  724. * @param {string} pathname
  725. * @param {string} persistedContent
  726. * @param {string} expectedContent
  727. */
  728. async queueUpdateForOutOfSyncContent(
  729. update,
  730. pathname,
  731. persistedContent,
  732. expectedContent
  733. ) {
  734. logger.debug(
  735. { projectId: this.projectId, persistedContent, expectedContent },
  736. 'diffing doc contents'
  737. )
  738. const op = UpdateCompressor.diffAsShareJsOps(
  739. persistedContent,
  740. expectedContent
  741. )
  742. if (op.length === 0) {
  743. return null
  744. }
  745. const expandedUpdate = {
  746. doc: update.doc,
  747. op,
  748. meta: {
  749. resync: true,
  750. origin: this.origin,
  751. ts: update.meta.ts,
  752. pathname,
  753. doc_length: persistedContent.length,
  754. },
  755. }
  756. logger.debug(
  757. { projectId: this.projectId, diffCount: op.length },
  758. 'doc contents differ'
  759. )
  760. this.expandedUpdates.push(expandedUpdate)
  761. Metrics.inc('project_history_resync_operation', 1, {
  762. status: 'update text file contents',
  763. })
  764. return expandedUpdate
  765. }
  766. /**
  767. * Queue updates for out of sync comments
  768. *
  769. * @param {ResyncDocContentUpdate} update
  770. * @param {string} pathname
  771. * @param {CommentRawData[]} persistedComments
  772. */
  773. queueUpdatesForOutOfSyncCommentsHistoryOT(
  774. update,
  775. pathname,
  776. persistedComments
  777. ) {
  778. const expectedComments =
  779. update.resyncDocContent.historyOTRanges?.comments ?? []
  780. const expectedCommentsById = new Map(
  781. expectedComments.map(comment => [comment.id, comment])
  782. )
  783. const persistedCommentsById = new Map(
  784. persistedComments.map(comment => [comment.id, comment])
  785. )
  786. // Delete any persisted comment that is not in the expected comment list.
  787. for (const persistedComment of persistedComments) {
  788. if (!expectedCommentsById.has(persistedComment.id)) {
  789. this.expandedUpdates.push({
  790. doc: update.doc,
  791. op: [{ deleteComment: persistedComment.id }],
  792. meta: {
  793. pathname,
  794. resync: true,
  795. origin: this.origin,
  796. ts: update.meta.ts,
  797. },
  798. })
  799. }
  800. }
  801. for (const expectedComment of expectedComments) {
  802. const persistedComment = persistedCommentsById.get(expectedComment.id)
  803. if (
  804. persistedComment &&
  805. commentRangesAreInSyncHistoryOT(persistedComment, expectedComment)
  806. ) {
  807. if (expectedComment.resolved === persistedComment.resolved) {
  808. // Both comments are identical; do nothing
  809. } else {
  810. // Only the resolved state differs
  811. this.expandedUpdates.push({
  812. doc: update.doc,
  813. op: [
  814. {
  815. commentId: expectedComment.id,
  816. resolved: expectedComment.resolved,
  817. },
  818. ],
  819. meta: {
  820. pathname,
  821. resync: true,
  822. origin: this.origin,
  823. ts: update.meta.ts,
  824. },
  825. })
  826. }
  827. } else {
  828. // New comment or ranges differ
  829. this.expandedUpdates.push({
  830. doc: update.doc,
  831. op: [
  832. {
  833. commentId: expectedComment.id,
  834. ranges: expectedComment.ranges,
  835. resolved: expectedComment.resolved,
  836. },
  837. ],
  838. meta: {
  839. pathname,
  840. resync: true,
  841. origin: this.origin,
  842. ts: update.meta.ts,
  843. },
  844. })
  845. }
  846. }
  847. }
  848. /**
  849. * Queue updates for out of sync comments
  850. *
  851. * @param {ResyncDocContentUpdate} update
  852. * @param {string} pathname
  853. * @param {HistoryComment[]} persistedComments
  854. */
  855. async queueUpdatesForOutOfSyncComments(update, pathname, persistedComments) {
  856. const expectedContent = update.resyncDocContent.content
  857. const expectedComments = update.resyncDocContent.ranges?.comments ?? []
  858. const resolvedCommentIds = new Set(
  859. update.resyncDocContent.resolvedCommentIds ?? []
  860. )
  861. const expectedCommentsById = new Map(
  862. expectedComments.map(comment => [comment.id, comment])
  863. )
  864. const persistedCommentsById = new Map(
  865. persistedComments.map(comment => [comment.id, comment])
  866. )
  867. // Delete any persisted comment that is not in the expected comment list.
  868. for (const persistedComment of persistedComments) {
  869. if (!expectedCommentsById.has(persistedComment.id)) {
  870. this.expandedUpdates.push({
  871. pathname,
  872. deleteComment: persistedComment.id,
  873. meta: {
  874. resync: true,
  875. origin: this.origin,
  876. ts: update.meta.ts,
  877. },
  878. })
  879. }
  880. }
  881. for (const expectedComment of expectedComments) {
  882. const persistedComment = persistedCommentsById.get(expectedComment.id)
  883. const expectedCommentResolved = resolvedCommentIds.has(expectedComment.id)
  884. if (
  885. persistedComment != null &&
  886. commentRangesAreInSync(persistedComment, expectedComment)
  887. ) {
  888. if (expectedCommentResolved === persistedComment.resolved) {
  889. // Both comments are identical; do nothing
  890. } else {
  891. // Only the resolved state differs
  892. this.expandedUpdates.push({
  893. pathname,
  894. commentId: expectedComment.id,
  895. resolved: expectedCommentResolved,
  896. meta: {
  897. resync: true,
  898. origin: this.origin,
  899. ts: update.meta.ts,
  900. },
  901. })
  902. }
  903. } else {
  904. const op = { ...expectedComment.op, resolved: expectedCommentResolved }
  905. // New comment or ranges differ
  906. this.expandedUpdates.push({
  907. doc: update.doc,
  908. op: [op],
  909. meta: {
  910. resync: true,
  911. origin: this.origin,
  912. ts: update.meta.ts,
  913. pathname,
  914. doc_length: expectedContent.length,
  915. },
  916. })
  917. }
  918. }
  919. }
  920. /**
  921. * Queue updates for out of sync tracked changes
  922. *
  923. * @param {ResyncDocContentUpdate} update
  924. * @param {string} pathname
  925. * @param {readonly HistoryTrackedChange[]} persistedChanges
  926. */
  927. async queueUpdatesForOutOfSyncTrackedChanges(
  928. update,
  929. pathname,
  930. persistedChanges
  931. ) {
  932. const expectedChanges = update.resyncDocContent.ranges?.changes ?? []
  933. const expectedContent = update.resyncDocContent.content
  934. /**
  935. * A cursor on the expected content
  936. */
  937. let cursor = 0
  938. /**
  939. * The persisted tracking at cursor
  940. *
  941. * @type {TrackingDirective}
  942. */
  943. let persistedTracking = { type: 'none' }
  944. /**
  945. * The expected tracking at cursor
  946. *
  947. * @type {TrackingDirective}
  948. */
  949. let expectedTracking = { type: 'none' }
  950. /**
  951. * The retain ops for the update
  952. *
  953. * @type {RetainOp[]}
  954. */
  955. const ops = []
  956. /**
  957. * The retain op being built
  958. *
  959. * @type {RetainOp | null}
  960. */
  961. let currentOp = null
  962. for (const transition of getTrackedChangesTransitions(
  963. persistedChanges,
  964. expectedChanges,
  965. update.resyncDocContent.historyOTRanges?.trackedChanges || [],
  966. expectedContent.length
  967. )) {
  968. if (transition.pos > cursor) {
  969. // The next transition will move the cursor. Decide what to do with the interval.
  970. if (trackingDirectivesEqual(expectedTracking, persistedTracking)) {
  971. // Expected tracking and persisted tracking are in sync. Emit the
  972. // current op and skip this interval.
  973. if (currentOp != null) {
  974. ops.push(currentOp)
  975. currentOp = null
  976. }
  977. } else {
  978. // Expected tracking and persisted tracking are different.
  979. const retainedText = expectedContent.slice(cursor, transition.pos)
  980. if (
  981. currentOp?.tracking != null &&
  982. trackingDirectivesEqual(expectedTracking, currentOp.tracking)
  983. ) {
  984. // The current op has the right tracking. Extend it.
  985. currentOp.r += retainedText
  986. } else {
  987. // The current op doesn't have the right tracking. Emit the current
  988. // op and start a new one.
  989. if (currentOp != null) {
  990. ops.push(currentOp)
  991. }
  992. currentOp = {
  993. r: retainedText,
  994. p: cursor,
  995. tracking: expectedTracking,
  996. }
  997. }
  998. }
  999. // Advance cursor
  1000. cursor = transition.pos
  1001. }
  1002. // Update the expected and persisted tracking
  1003. if (transition.stage === 'persisted') {
  1004. persistedTracking = transition.tracking
  1005. } else {
  1006. expectedTracking = transition.tracking
  1007. }
  1008. }
  1009. // Emit the last op
  1010. if (currentOp != null) {
  1011. ops.push(currentOp)
  1012. }
  1013. if (ops.length > 0) {
  1014. this.expandedUpdates.push({
  1015. doc: update.doc,
  1016. op: ops,
  1017. meta: {
  1018. resync: true,
  1019. origin: this.origin,
  1020. ts: update.meta.ts,
  1021. pathname,
  1022. doc_length: expectedContent.length,
  1023. },
  1024. })
  1025. }
  1026. }
  1027. }
  1028. /**
  1029. * Compares the ranges in the persisted and expected comments
  1030. *
  1031. * @param {CommentRawData} persistedComment
  1032. * @param {CommentRawData} expectedComment
  1033. */
  1034. function commentRangesAreInSyncHistoryOT(persistedComment, expectedComment) {
  1035. if (persistedComment.ranges.length !== expectedComment.ranges.length) {
  1036. return false
  1037. }
  1038. for (let i = 0; i < persistedComment.ranges.length; i++) {
  1039. const persistedRange = persistedComment.ranges[i]
  1040. const expectedRange = expectedComment.ranges[i]
  1041. if (persistedRange.pos !== expectedRange.pos) return false
  1042. if (persistedRange.length !== expectedRange.length) return false
  1043. }
  1044. return true
  1045. }
  1046. /**
  1047. * Compares the ranges in the persisted and expected comments
  1048. *
  1049. * @param {HistoryComment} persistedComment
  1050. * @param {Comment} expectedComment
  1051. */
  1052. function commentRangesAreInSync(persistedComment, expectedComment) {
  1053. const expectedPos = expectedComment.op.hpos ?? expectedComment.op.p
  1054. const expectedLength = expectedComment.op.hlen ?? expectedComment.op.c.length
  1055. if (expectedLength === 0) {
  1056. // A zero length comment from RangesManager is a detached comment in history
  1057. return persistedComment.ranges.length === 0
  1058. }
  1059. if (persistedComment.ranges.length !== 1) {
  1060. // The editor only supports single range comments
  1061. return false
  1062. }
  1063. const persistedRange = persistedComment.ranges[0]
  1064. return (
  1065. persistedRange.pos === expectedPos &&
  1066. persistedRange.length === expectedLength
  1067. )
  1068. }
  1069. /**
  1070. * Iterates through expected tracked changes and persisted tracked changes and
  1071. * returns all transitions, sorted by position.
  1072. *
  1073. * @param {readonly HistoryTrackedChange[]} persistedChanges
  1074. * @param {TrackedChange[]} expectedChanges
  1075. * @param {TrackedChangeRawData[]} persistedChangesHistoryOT
  1076. * @param {number} docLength
  1077. */
  1078. function getTrackedChangesTransitions(
  1079. persistedChanges,
  1080. expectedChanges,
  1081. persistedChangesHistoryOT,
  1082. docLength
  1083. ) {
  1084. /** @type {TrackedChangeTransition[]} */
  1085. const transitions = []
  1086. for (const change of persistedChanges) {
  1087. transitions.push({
  1088. stage: 'persisted',
  1089. pos: change.range.start,
  1090. tracking: {
  1091. type: change.tracking.type,
  1092. userId: change.tracking.userId,
  1093. ts: change.tracking.ts.toISOString(),
  1094. },
  1095. })
  1096. transitions.push({
  1097. stage: 'persisted',
  1098. pos: change.range.end,
  1099. tracking: { type: 'none' },
  1100. })
  1101. }
  1102. for (const change of persistedChangesHistoryOT) {
  1103. transitions.push({
  1104. stage: 'expected',
  1105. pos: change.range.pos,
  1106. tracking: change.tracking,
  1107. })
  1108. transitions.push({
  1109. stage: 'expected',
  1110. pos: change.range.pos + change.range.length,
  1111. tracking: { type: 'none' },
  1112. })
  1113. }
  1114. for (const change of expectedChanges) {
  1115. const op = change.op
  1116. const pos = op.hpos ?? op.p
  1117. if (isInsert(op)) {
  1118. transitions.push({
  1119. stage: 'expected',
  1120. pos,
  1121. tracking: {
  1122. type: 'insert',
  1123. userId: change.metadata.user_id,
  1124. ts: change.metadata.ts,
  1125. },
  1126. })
  1127. transitions.push({
  1128. stage: 'expected',
  1129. pos: pos + op.i.length,
  1130. tracking: { type: 'none' },
  1131. })
  1132. } else {
  1133. transitions.push({
  1134. stage: 'expected',
  1135. pos,
  1136. tracking: {
  1137. type: 'delete',
  1138. userId: change.metadata.user_id,
  1139. ts: change.metadata.ts,
  1140. },
  1141. })
  1142. transitions.push({
  1143. stage: 'expected',
  1144. pos: pos + op.d.length,
  1145. tracking: { type: 'none' },
  1146. })
  1147. }
  1148. }
  1149. transitions.push({
  1150. stage: 'expected',
  1151. pos: docLength,
  1152. tracking: { type: 'none' },
  1153. })
  1154. transitions.sort((a, b) => {
  1155. if (a.pos < b.pos) {
  1156. return -1
  1157. } else if (a.pos > b.pos) {
  1158. return 1
  1159. } else if (a.tracking.type === 'none' && b.tracking.type !== 'none') {
  1160. // none type comes before other types so that it can be overridden at the
  1161. // same position
  1162. return -1
  1163. } else if (a.tracking.type !== 'none' && b.tracking.type === 'none') {
  1164. // none type comes before other types so that it can be overridden at the
  1165. // same position
  1166. return 1
  1167. } else {
  1168. return 0
  1169. }
  1170. })
  1171. return transitions
  1172. }
  1173. /**
  1174. * Returns true if both tracking directives are equal
  1175. *
  1176. * @param {TrackingDirective} a
  1177. * @param {TrackingDirective} b
  1178. */
  1179. function trackingDirectivesEqual(a, b) {
  1180. if (a.type === 'none') {
  1181. return b.type === 'none'
  1182. } else {
  1183. return a.type === b.type && a.userId === b.userId && a.ts === b.ts
  1184. }
  1185. }
  1186. // EXPORTS
  1187. const startResyncCb = callbackify(startResync)
  1188. const startResyncWithoutLockCb = callbackify(startResyncWithoutLock)
  1189. const startHardResyncCb = callbackify(startHardResync)
  1190. const setResyncStateCb = callbackify(setResyncState)
  1191. const clearResyncStateCb = callbackify(clearResyncState)
  1192. const skipUpdatesDuringSyncCb = callbackifyMultiResult(skipUpdatesDuringSync, [
  1193. 'updates',
  1194. 'syncState',
  1195. ])
  1196. /**
  1197. * @param {string} projectId
  1198. * @param {string} projectHistoryId
  1199. * @param {{chunk: import('overleaf-editor-core/lib/types.js').RawChunk}} mostRecentChunk
  1200. * @param {Array<Update>} updates
  1201. * @param {() => void} extendLock
  1202. * @param {(err: Error | null, updates?: Array<Update>) => void} callback
  1203. */
  1204. const expandSyncUpdatesCb = (
  1205. projectId,
  1206. projectHistoryId,
  1207. mostRecentChunk,
  1208. updates,
  1209. extendLock,
  1210. callback
  1211. ) => {
  1212. const extendLockPromises = promisify(extendLock)
  1213. expandSyncUpdates(
  1214. projectId,
  1215. projectHistoryId,
  1216. mostRecentChunk,
  1217. updates,
  1218. extendLockPromises
  1219. )
  1220. .then(result => {
  1221. callback(null, result)
  1222. })
  1223. .catch(err => {
  1224. callback(err)
  1225. })
  1226. }
  1227. export {
  1228. startResyncCb as startResync,
  1229. startResyncWithoutLockCb as startResyncWithoutLock,
  1230. startHardResyncCb as startHardResync,
  1231. setResyncStateCb as setResyncState,
  1232. clearResyncStateCb as clearResyncState,
  1233. skipUpdatesDuringSyncCb as skipUpdatesDuringSync,
  1234. expandSyncUpdatesCb as expandSyncUpdates,
  1235. }
  1236. export const promises = {
  1237. startResync,
  1238. startResyncWithoutLock,
  1239. startHardResync,
  1240. setResyncState,
  1241. clearResyncState,
  1242. clearResyncStateIfAllAfter,
  1243. skipUpdatesDuringSync,
  1244. expandSyncUpdates,
  1245. }