SyncManager.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. // @ts-check
  2. import _ from 'lodash'
  3. import { callbackify, promisify } from '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 } from 'overleaf-editor-core'
  10. import { 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. /**
  22. * @typedef {import('overleaf-editor-core').Comment} HistoryComment
  23. * @typedef {import('./types').Comment} Comment
  24. * @typedef {import('./types').Entity} Entity
  25. * @typedef {import('./types').ResyncDocContentUpdate} ResyncDocContentUpdate
  26. * @typedef {import('./types').Update} Update
  27. */
  28. const MAX_RESYNC_HISTORY_RECORDS = 100 // keep this many records of previous resyncs
  29. const EXPIRE_RESYNC_HISTORY_INTERVAL_MS = 90 * 24 * 3600 * 1000 // 90 days
  30. const keys = Settings.redis.lock.key_schema
  31. // db.projectHistorySyncState.ensureIndex({expiresAt: 1}, {expireAfterSeconds: 0, background: true})
  32. // To add expiresAt field to existing entries in collection (choose a suitable future expiry date):
  33. // db.projectHistorySyncState.updateMany({resyncProjectStructure: false, resyncDocContents: [], expiresAt: {$exists:false}}, {$set: {expiresAt: new Date("2019-07-01")}})
  34. async function startResync(projectId, options = {}) {
  35. // We have three options here
  36. //
  37. // 1. If we update mongo before making the call to web then there's a
  38. // chance we ignore all updates indefinitely (there's no foolproff way
  39. // to undo the change in mongo)
  40. //
  41. // 2. If we make the call to web first then there is a small race condition
  42. // where we could process the sync update and then only update mongo
  43. // after, causing all updates to be ignored from then on
  44. //
  45. // 3. We can wrap everything in a project lock
  46. Metrics.inc('project_history_resync')
  47. try {
  48. await LockManager.promises.runWithLock(
  49. keys.projectHistoryLock({ project_id: projectId }),
  50. async extendLock => {
  51. await _startResyncWithoutLock(projectId, options)
  52. }
  53. )
  54. } catch (error) {
  55. // record error in starting sync ("sync ongoing")
  56. try {
  57. await ErrorRecorder.promises.record(projectId, -1, error)
  58. } catch (err) {
  59. // swallow any error thrown by ErrorRecorder.record()
  60. }
  61. throw error
  62. }
  63. }
  64. async function startHardResync(projectId, options = {}) {
  65. Metrics.inc('project_history_hard_resync')
  66. try {
  67. await LockManager.promises.runWithLock(
  68. keys.projectHistoryLock({ project_id: projectId }),
  69. async extendLock => {
  70. await clearResyncState(projectId)
  71. await RedisManager.promises.clearFirstOpTimestamp(projectId)
  72. await RedisManager.promises.destroyDocUpdatesQueue(projectId)
  73. await _startResyncWithoutLock(projectId, options)
  74. }
  75. )
  76. } catch (error) {
  77. // record error in starting sync ("sync ongoing")
  78. await ErrorRecorder.promises.record(projectId, -1, error)
  79. throw error
  80. }
  81. }
  82. async function _startResyncWithoutLock(projectId, options) {
  83. await ErrorRecorder.promises.recordSyncStart(projectId)
  84. const syncState = await _getResyncState(projectId)
  85. if (syncState.isSyncOngoing()) {
  86. throw new OError('sync ongoing')
  87. }
  88. syncState.setOrigin(options.origin || { kind: 'history-resync' })
  89. syncState.startProjectStructureSync()
  90. await WebApiManager.promises.requestResync(projectId)
  91. await setResyncState(projectId, syncState)
  92. }
  93. async function _getResyncState(projectId) {
  94. const rawSyncState = await db.projectHistorySyncState.findOne({
  95. project_id: new ObjectId(projectId.toString()),
  96. })
  97. const syncState = SyncState.fromRaw(projectId, rawSyncState)
  98. return syncState
  99. }
  100. async function setResyncState(projectId, syncState) {
  101. // skip if syncState is null (i.e. unchanged)
  102. if (syncState == null) {
  103. return
  104. }
  105. const update = {
  106. $set: syncState.toRaw(),
  107. $push: {
  108. history: {
  109. $each: [{ syncState: syncState.toRaw(), timestamp: new Date() }],
  110. $position: 0,
  111. $slice: MAX_RESYNC_HISTORY_RECORDS,
  112. },
  113. },
  114. $currentDate: { lastUpdated: true },
  115. }
  116. // handle different cases
  117. if (syncState.isSyncOngoing()) {
  118. // starting a new sync; prevent the entry expiring while sync is in ongoing
  119. update.$inc = { resyncCount: 1 }
  120. update.$unset = { expiresAt: true }
  121. } else {
  122. // successful completion of existing sync; set the entry to expire in the
  123. // future
  124. update.$set.expiresAt = new Date(
  125. Date.now() + EXPIRE_RESYNC_HISTORY_INTERVAL_MS
  126. )
  127. }
  128. // apply the update
  129. await db.projectHistorySyncState.updateOne(
  130. { project_id: new ObjectId(projectId) },
  131. update,
  132. { upsert: true }
  133. )
  134. }
  135. async function clearResyncState(projectId) {
  136. await db.projectHistorySyncState.deleteOne({
  137. project_id: new ObjectId(projectId.toString()),
  138. })
  139. }
  140. async function skipUpdatesDuringSync(projectId, updates) {
  141. const syncState = await _getResyncState(projectId)
  142. if (!syncState.isSyncOngoing()) {
  143. logger.debug({ projectId }, 'not skipping updates: no resync in progress')
  144. // don't return syncState when unchanged
  145. return { updates, syncState: null }
  146. }
  147. const filteredUpdates = []
  148. for (const update of updates) {
  149. syncState.updateState(update)
  150. const shouldSkipUpdate = syncState.shouldSkipUpdate(update)
  151. if (!shouldSkipUpdate) {
  152. filteredUpdates.push(update)
  153. } else {
  154. logger.debug({ projectId, update }, 'skipping update due to resync')
  155. }
  156. }
  157. return { updates: filteredUpdates, syncState }
  158. }
  159. async function expandSyncUpdates(
  160. projectId,
  161. projectHistoryId,
  162. updates,
  163. extendLock
  164. ) {
  165. const areSyncUpdatesQueued =
  166. _.some(updates, 'resyncProjectStructure') ||
  167. _.some(updates, 'resyncDocContent')
  168. if (!areSyncUpdatesQueued) {
  169. logger.debug({ projectId }, 'no resync updates to expand')
  170. return updates
  171. }
  172. const syncState = await _getResyncState(projectId)
  173. // compute the current snapshot from the most recent chunk
  174. const snapshotFiles = await SnapshotManager.promises.getLatestSnapshot(
  175. projectId,
  176. projectHistoryId
  177. )
  178. // check if snapshot files are valid
  179. const invalidFiles = _.pickBy(
  180. snapshotFiles,
  181. (v, k) => v == null || typeof v.isEditable !== 'function'
  182. )
  183. if (_.size(invalidFiles) > 0) {
  184. throw new SyncError('file is missing isEditable method', {
  185. projectId,
  186. invalidFiles,
  187. })
  188. }
  189. const expander = new SyncUpdateExpander(
  190. projectId,
  191. snapshotFiles,
  192. syncState.origin
  193. )
  194. // expand updates asynchronously to avoid blocking
  195. for (const update of updates) {
  196. await expander.expandUpdate(update)
  197. await extendLock()
  198. }
  199. return expander.getExpandedUpdates()
  200. }
  201. class SyncState {
  202. constructor(projectId, resyncProjectStructure, resyncDocContents, origin) {
  203. this.projectId = projectId
  204. this.resyncProjectStructure = resyncProjectStructure
  205. this.resyncDocContents = resyncDocContents
  206. this.origin = origin
  207. }
  208. static fromRaw(projectId, rawSyncState) {
  209. rawSyncState = rawSyncState || {}
  210. const resyncProjectStructure = rawSyncState.resyncProjectStructure || false
  211. const resyncDocContents = new Set(rawSyncState.resyncDocContents || [])
  212. const origin = rawSyncState.origin
  213. return new SyncState(
  214. projectId,
  215. resyncProjectStructure,
  216. resyncDocContents,
  217. origin
  218. )
  219. }
  220. toRaw() {
  221. return {
  222. resyncProjectStructure: this.resyncProjectStructure,
  223. resyncDocContents: Array.from(this.resyncDocContents),
  224. origin: this.origin,
  225. }
  226. }
  227. updateState(update) {
  228. if (update.resyncProjectStructure != null) {
  229. if (!this.isProjectStructureSyncing()) {
  230. throw new SyncError('unexpected resyncProjectStructure update', {
  231. projectId: this.projectId,
  232. resyncProjectStructure: this.resyncProjectStructure,
  233. })
  234. }
  235. if (this.isAnyDocContentSyncing()) {
  236. throw new SyncError('unexpected resyncDocContents update', {
  237. projectId: this.projectId,
  238. resyncDocContents: this.resyncDocContents,
  239. })
  240. }
  241. for (const doc of update.resyncProjectStructure.docs) {
  242. this.startDocContentSync(doc.path)
  243. }
  244. this.stopProjectStructureSync()
  245. } else if (update.resyncDocContent != null) {
  246. if (this.isProjectStructureSyncing()) {
  247. throw new SyncError('unexpected resyncDocContent update', {
  248. projectId: this.projectId,
  249. resyncProjectStructure: this.resyncProjectStructure,
  250. })
  251. }
  252. if (!this.isDocContentSyncing(update.path)) {
  253. throw new SyncError('unexpected resyncDocContent update', {
  254. projectId: this.projectId,
  255. resyncDocContents: this.resyncDocContents,
  256. path: update.path,
  257. })
  258. }
  259. this.stopDocContentSync(update.path)
  260. }
  261. }
  262. setOrigin(origin) {
  263. this.origin = origin
  264. }
  265. shouldSkipUpdate(update) {
  266. // don't skip sync updates
  267. if (
  268. update.resyncProjectStructure != null ||
  269. update.resyncDocContent != null
  270. ) {
  271. return false
  272. }
  273. // if syncing project structure skip update
  274. if (this.isProjectStructureSyncing()) {
  275. return true
  276. }
  277. // skip text updates for a docs being synced
  278. if (UpdateTranslator.isTextUpdate(update)) {
  279. if (this.isDocContentSyncing(update.meta.pathname)) {
  280. return true
  281. }
  282. }
  283. // preserve all other updates
  284. return false
  285. }
  286. startProjectStructureSync() {
  287. this.resyncProjectStructure = true
  288. this.resyncDocContents = new Set([])
  289. }
  290. stopProjectStructureSync() {
  291. this.resyncProjectStructure = false
  292. }
  293. stopDocContentSync(pathname) {
  294. this.resyncDocContents.delete(pathname)
  295. }
  296. startDocContentSync(pathname) {
  297. this.resyncDocContents.add(pathname)
  298. }
  299. isProjectStructureSyncing() {
  300. return this.resyncProjectStructure
  301. }
  302. isDocContentSyncing(pathname) {
  303. return this.resyncDocContents.has(pathname)
  304. }
  305. isAnyDocContentSyncing() {
  306. return this.resyncDocContents.size > 0
  307. }
  308. isSyncOngoing() {
  309. return this.isProjectStructureSyncing() || this.isAnyDocContentSyncing()
  310. }
  311. }
  312. class SyncUpdateExpander {
  313. /**
  314. * Build a SyncUpdateExpander
  315. *
  316. * @param {string} projectId
  317. * @param {Record<string, File>} snapshotFiles
  318. * @param {string} origin
  319. */
  320. constructor(projectId, snapshotFiles, origin) {
  321. this.projectId = projectId
  322. this.files = snapshotFiles
  323. this.expandedUpdates = []
  324. this.origin = origin
  325. }
  326. // If there's an expected *file* with the same path and either the same hash
  327. // or no hash, treat this as not editable even if history thinks it is.
  328. isEditable(filePath, file, expectedFiles) {
  329. if (!file.isEditable()) {
  330. return false
  331. }
  332. const fileHash = _.get(file, ['data', 'hash'])
  333. const matchedExpectedFile = expectedFiles.some(item => {
  334. const expectedFileHash = item._hash
  335. if (expectedFileHash && fileHash !== expectedFileHash) {
  336. // expected file has a hash and it doesn't match
  337. return false
  338. }
  339. return UpdateTranslator._convertPathname(item.path) === filePath
  340. })
  341. // consider editable file in history as binary, since it matches a binary file in the project
  342. return !matchedExpectedFile
  343. }
  344. /**
  345. * @param {Update} update
  346. */
  347. async expandUpdate(update) {
  348. if ('resyncProjectStructure' in update) {
  349. logger.debug(
  350. { projectId: this.projectId, update },
  351. 'expanding resyncProjectStructure update'
  352. )
  353. const persistedNonBinaryFileEntries = _.pickBy(this.files, (v, k) =>
  354. this.isEditable(k, v, update.resyncProjectStructure.files)
  355. )
  356. const persistedNonBinaryFiles = _.map(
  357. Object.keys(persistedNonBinaryFileEntries),
  358. path => ({
  359. path,
  360. })
  361. )
  362. const persistedBinaryFileEntries = _.omitBy(this.files, (v, k) =>
  363. this.isEditable(k, v, update.resyncProjectStructure.files)
  364. )
  365. // preserve file properties on binary files, for future comparison.
  366. const persistedBinaryFiles = _.map(
  367. persistedBinaryFileEntries,
  368. (entity, key) => Object.assign({}, entity, { path: key })
  369. )
  370. const expectedNonBinaryFiles = _.map(
  371. update.resyncProjectStructure.docs,
  372. entity =>
  373. Object.assign({}, entity, {
  374. path: UpdateTranslator._convertPathname(entity.path),
  375. })
  376. )
  377. const expectedBinaryFiles = _.map(
  378. update.resyncProjectStructure.files,
  379. entity =>
  380. Object.assign({}, entity, {
  381. path: UpdateTranslator._convertPathname(entity.path),
  382. })
  383. )
  384. // We need to detect and fix consistency issues where web and
  385. // history-store disagree on whether an entity is binary or not. Thus we
  386. // need to remove and add the two separately.
  387. this.queueRemoveOpsForUnexpectedFiles(
  388. update,
  389. expectedBinaryFiles,
  390. persistedBinaryFiles
  391. )
  392. this.queueRemoveOpsForUnexpectedFiles(
  393. update,
  394. expectedNonBinaryFiles,
  395. persistedNonBinaryFiles
  396. )
  397. this.queueAddOpsForMissingFiles(
  398. update,
  399. expectedBinaryFiles,
  400. persistedBinaryFiles
  401. )
  402. this.queueAddOpsForMissingFiles(
  403. update,
  404. expectedNonBinaryFiles,
  405. persistedNonBinaryFiles
  406. )
  407. this.queueUpdateForOutOfSyncBinaryFiles(
  408. update,
  409. expectedBinaryFiles,
  410. persistedBinaryFiles
  411. )
  412. } else if ('resyncDocContent' in update) {
  413. logger.debug(
  414. { projectId: this.projectId, update },
  415. 'expanding resyncDocContent update'
  416. )
  417. await this.expandResyncDocContentUpdate(update)
  418. } else {
  419. this.expandedUpdates.push(update)
  420. }
  421. }
  422. getExpandedUpdates() {
  423. return this.expandedUpdates
  424. }
  425. /**
  426. * @param {Entity[]} expectedFiles
  427. * @param {{ path: string }[]} persistedFiles
  428. */
  429. queueRemoveOpsForUnexpectedFiles(update, expectedFiles, persistedFiles) {
  430. const unexpectedFiles = _.differenceBy(
  431. persistedFiles,
  432. expectedFiles,
  433. 'path'
  434. )
  435. for (const entity of unexpectedFiles) {
  436. update = {
  437. pathname: entity.path,
  438. new_pathname: '',
  439. meta: {
  440. resync: true,
  441. origin: this.origin,
  442. ts: update.meta.ts,
  443. },
  444. }
  445. this.expandedUpdates.push(update)
  446. Metrics.inc('project_history_resync_operation', 1, {
  447. status: 'remove unexpected file',
  448. })
  449. }
  450. }
  451. /**
  452. * @param {Entity[]} expectedFiles
  453. * @param {{ path: string }[]} persistedFiles
  454. */
  455. queueAddOpsForMissingFiles(update, expectedFiles, persistedFiles) {
  456. const missingFiles = _.differenceBy(expectedFiles, persistedFiles, 'path')
  457. for (const entity of missingFiles) {
  458. update = {
  459. pathname: entity.path,
  460. meta: {
  461. resync: true,
  462. origin: this.origin,
  463. ts: update.meta.ts,
  464. },
  465. }
  466. if ('doc' in entity) {
  467. update.doc = entity.doc
  468. update.docLines = ''
  469. // we have to create a dummy entry here because later we will need the content in the diff computation
  470. this.files[update.pathname] = File.fromString('')
  471. } else {
  472. update.file = entity.file
  473. update.url = entity.url
  474. }
  475. this.expandedUpdates.push(update)
  476. Metrics.inc('project_history_resync_operation', 1, {
  477. status: 'add missing file',
  478. })
  479. }
  480. }
  481. queueUpdateForOutOfSyncBinaryFiles(update, expectedFiles, persistedFiles) {
  482. // create a map to lookup persisted files by their path
  483. const persistedFileMap = new Map(persistedFiles.map(x => [x.path, x]))
  484. // now search for files with same path but different hash values
  485. const differentFiles = expectedFiles.filter(expected => {
  486. // check for a persisted file at the same path
  487. const expectedPath = expected.path
  488. const persistedFileAtSamePath = persistedFileMap.get(expectedPath)
  489. if (!persistedFileAtSamePath) return false
  490. // check if the persisted file at the same path has a different hash
  491. const expectedHash = _.get(expected, '_hash')
  492. const persistedHash = _.get(persistedFileAtSamePath, ['data', 'hash'])
  493. const hashesPresent = expectedHash && persistedHash
  494. return hashesPresent && persistedHash !== expectedHash
  495. })
  496. for (const entity of differentFiles) {
  497. // remove the outdated persisted file
  498. const removeUpdate = {
  499. pathname: entity.path,
  500. new_pathname: '',
  501. meta: {
  502. resync: true,
  503. origin: this.origin,
  504. ts: update.meta.ts,
  505. },
  506. }
  507. this.expandedUpdates.push(removeUpdate)
  508. // add the new file content
  509. const addUpdate = {
  510. pathname: entity.path,
  511. meta: {
  512. resync: true,
  513. origin: this.origin,
  514. ts: update.meta.ts,
  515. },
  516. file: entity.file,
  517. url: entity.url,
  518. }
  519. this.expandedUpdates.push(addUpdate)
  520. Metrics.inc('project_history_resync_operation', 1, {
  521. status: 'update binary file contents',
  522. })
  523. }
  524. }
  525. /**
  526. * Expand a resyncDocContentUpdate
  527. *
  528. * @param {ResyncDocContentUpdate} update
  529. */
  530. async expandResyncDocContentUpdate(update) {
  531. const pathname = UpdateTranslator._convertPathname(update.path)
  532. const snapshotFile = this.files[pathname]
  533. const expectedFile = update.resyncDocContent
  534. const expectedContent = expectedFile.content
  535. if (!snapshotFile) {
  536. throw new OError('unrecognised file: not in snapshot')
  537. }
  538. // Compare hashes to see if the persisted file matches the expected content.
  539. // The hash of the persisted files is stored in the snapshot.
  540. // Note getHash() returns the hash only when the persisted file has
  541. // no changes in the snapshot, the hash is null if there are changes
  542. // that apply to it.
  543. let hashesMatch = false
  544. const persistedHash = snapshotFile.getHash()
  545. if (persistedHash != null) {
  546. const expectedHash = HashManager._getBlobHashFromString(expectedContent)
  547. if (persistedHash === expectedHash) {
  548. logger.debug(
  549. { projectId: this.projectId, persistedHash, expectedHash },
  550. 'skipping diff because hashes match and persisted file has no ops'
  551. )
  552. hashesMatch = true
  553. }
  554. } else {
  555. logger.debug('cannot compare hashes, will retrieve content')
  556. }
  557. // compute the difference between the expected and persisted content
  558. const historyId = await WebApiManager.promises.getHistoryId(this.projectId)
  559. const file = await snapshotFile.load(
  560. 'eager',
  561. HistoryStoreManager.getBlobStore(historyId)
  562. )
  563. const persistedContent = file.getContent()
  564. if (persistedContent == null) {
  565. // This should not happen given that we loaded the file eagerly. We could
  566. // probably refine the types in overleaf-editor-core so that this check
  567. // wouldn't be necessary.
  568. throw new Error('File was not properly loaded')
  569. }
  570. if (!hashesMatch) {
  571. await this.queueUpdateForOutOfSyncContent(
  572. update,
  573. pathname,
  574. persistedContent,
  575. expectedContent
  576. )
  577. }
  578. const persistedComments = file.getComments().toArray()
  579. await this.queueUpdateForOutOfSyncComments(
  580. update,
  581. pathname,
  582. persistedContent,
  583. persistedComments
  584. )
  585. }
  586. /**
  587. * Queue update for out of sync content
  588. *
  589. * @param {ResyncDocContentUpdate} update
  590. * @param {string} pathname
  591. * @param {string} persistedContent
  592. * @param {string} expectedContent
  593. */
  594. async queueUpdateForOutOfSyncContent(
  595. update,
  596. pathname,
  597. persistedContent,
  598. expectedContent
  599. ) {
  600. logger.debug(
  601. { projectId: this.projectId, persistedContent, expectedContent },
  602. 'diffing doc contents'
  603. )
  604. const op = UpdateCompressor.diffAsShareJsOps(
  605. persistedContent,
  606. expectedContent
  607. )
  608. if (op.length === 0) {
  609. return
  610. }
  611. const expandedUpdate = {
  612. doc: update.doc,
  613. op,
  614. meta: {
  615. resync: true,
  616. origin: this.origin,
  617. ts: update.meta.ts,
  618. pathname,
  619. doc_length: persistedContent.length,
  620. },
  621. }
  622. logger.debug(
  623. { projectId: this.projectId, diffCount: op.length },
  624. 'doc contents differ'
  625. )
  626. this.expandedUpdates.push(expandedUpdate)
  627. Metrics.inc('project_history_resync_operation', 1, {
  628. status: 'update text file contents',
  629. })
  630. }
  631. /**
  632. * Queue update for out of sync comments
  633. *
  634. * @param {ResyncDocContentUpdate} update
  635. * @param {string} pathname
  636. * @param {string} persistedContent
  637. * @param {HistoryComment[]} persistedComments
  638. */
  639. async queueUpdateForOutOfSyncComments(
  640. update,
  641. pathname,
  642. persistedContent,
  643. persistedComments
  644. ) {
  645. const expectedComments = update.resyncDocContent.ranges?.comments ?? []
  646. const resolvedComments = new Set(
  647. update.resyncDocContent.resolvedComments ?? []
  648. )
  649. const expectedCommentsById = new Map(
  650. expectedComments.map(comment => [comment.id, comment])
  651. )
  652. const persistedCommentsById = new Map(
  653. persistedComments.map(comment => [comment.id, comment])
  654. )
  655. // Delete any persisted comment that is not in the expected comment list.
  656. for (const persistedComment of persistedComments) {
  657. if (!expectedCommentsById.has(persistedComment.id)) {
  658. this.expandedUpdates.push({
  659. pathname,
  660. deleteComment: persistedComment.id,
  661. meta: {
  662. resync: true,
  663. origin: this.origin,
  664. ts: update.meta.ts,
  665. },
  666. })
  667. }
  668. }
  669. for (const expectedComment of expectedComments) {
  670. const persistedComment = persistedCommentsById.get(expectedComment.id)
  671. if (
  672. persistedComment != null &&
  673. commentRangesAreInSync(persistedComment, expectedComment)
  674. ) {
  675. const expectedCommentResolved = resolvedComments.has(expectedComment.id)
  676. if (expectedCommentResolved === persistedComment.resolved) {
  677. // Both comments are identical; do nothing
  678. } else {
  679. // Only the resolved state differs
  680. this.expandedUpdates.push({
  681. pathname,
  682. commentId: expectedComment.id,
  683. resolved: expectedCommentResolved,
  684. })
  685. }
  686. } else {
  687. // New comment or ranges differ
  688. this.expandedUpdates.push({
  689. doc: update.doc,
  690. op: [expectedComment.op],
  691. meta: {
  692. resync: true,
  693. origin: this.origin,
  694. ts: update.meta.ts,
  695. pathname,
  696. doc_length: persistedContent.length,
  697. },
  698. })
  699. }
  700. }
  701. }
  702. }
  703. /**
  704. * Compares the ranges in the persisted and expected comments
  705. *
  706. * @param {HistoryComment} persistedComment
  707. * @param {Comment} expectedComment
  708. */
  709. function commentRangesAreInSync(persistedComment, expectedComment) {
  710. if (persistedComment.ranges.length !== 1) {
  711. // The editor only supports single range comments
  712. return false
  713. }
  714. const persistedRange = persistedComment.ranges[0]
  715. const expectedPos = expectedComment.op.hpos ?? expectedComment.op.p
  716. const expectedLength = expectedComment.op.hlen ?? expectedComment.op.c.length
  717. return (
  718. persistedRange.pos === expectedPos &&
  719. persistedRange.length === expectedLength
  720. )
  721. }
  722. // EXPORTS
  723. const startResyncCb = callbackify(startResync)
  724. const startHardResyncCb = callbackify(startHardResync)
  725. const setResyncStateCb = callbackify(setResyncState)
  726. const clearResyncStateCb = callbackify(clearResyncState)
  727. const skipUpdatesDuringSyncCb = callbackifyMultiResult(skipUpdatesDuringSync, [
  728. 'updates',
  729. 'syncState',
  730. ])
  731. const expandSyncUpdatesCb = (
  732. projectId,
  733. projectHistoryId,
  734. updates,
  735. extendLock,
  736. callback
  737. ) => {
  738. const extendLockPromises = promisify(extendLock)
  739. expandSyncUpdates(projectId, projectHistoryId, updates, extendLockPromises)
  740. .then(result => {
  741. callback(null, result)
  742. })
  743. .catch(err => {
  744. callback(err)
  745. })
  746. }
  747. export {
  748. startResyncCb as startResync,
  749. startHardResyncCb as startHardResync,
  750. setResyncStateCb as setResyncState,
  751. clearResyncStateCb as clearResyncState,
  752. skipUpdatesDuringSyncCb as skipUpdatesDuringSync,
  753. expandSyncUpdatesCb as expandSyncUpdates,
  754. }
  755. export const promises = {
  756. startResync,
  757. startHardResync,
  758. setResyncState,
  759. clearResyncState,
  760. skipUpdatesDuringSync,
  761. expandSyncUpdates,
  762. }