SyncManager.js 40 KB

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