SummarizedUpdatesManager.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import _ from 'lodash'
  2. import async from 'async'
  3. import logger from '@overleaf/logger'
  4. import OError from '@overleaf/o-error'
  5. import * as ChunkTranslator from './ChunkTranslator.js'
  6. import * as HistoryApiManager from './HistoryApiManager.js'
  7. import * as HistoryStoreManager from './HistoryStoreManager.js'
  8. import * as LabelsManager from './LabelsManager.js'
  9. import * as UpdatesProcessor from './UpdatesProcessor.js'
  10. import * as WebApiManager from './WebApiManager.js'
  11. const MAX_CHUNK_REQUESTS = 5
  12. const TIME_BETWEEN_DISTINCT_UPDATES = 5 * 60 * 1000 // five minutes
  13. export function getSummarizedProjectUpdates(projectId, options, callback) {
  14. // Some notes on versions:
  15. //
  16. // Versions of the project are like the fenceposts between updates.
  17. // An update applies to a certain version of the project, and gives us the
  18. // next version.
  19. //
  20. // When we ask for updates 'before' a version, this includes the update
  21. // that created the version equal to 'before'.
  22. //
  23. // A chunk in OL has a 'startVersion', which is the version of the project
  24. // before any of the updates in it were applied. This is the same version as
  25. // the last update in the previous chunk would have created.
  26. //
  27. // If we ask the OL history store for the chunk with version that is the end of one
  28. // chunk and the start of another, it will return the older chunk, i.e.
  29. // the chunk with the updates that led up to that version.
  30. //
  31. // So once we read in the updates from a chunk, and want to get the updates from
  32. // the previous chunk, we ask OL for the chunk with the version equal to the
  33. // 'startVersion' of the newer chunk we just read.
  34. let nextVersionToRequest
  35. if (options == null) {
  36. options = {}
  37. }
  38. if (!options.min_count) {
  39. options.min_count = 25
  40. }
  41. if (options.before != null) {
  42. // The version is of the doc, so we want the updates before that version,
  43. // which includes the update that created that version.
  44. nextVersionToRequest = options.before
  45. } else {
  46. // Return the latest updates first if no nextVersionToRequest is set.
  47. nextVersionToRequest = null
  48. }
  49. UpdatesProcessor.processUpdatesForProject(projectId, function (error) {
  50. if (error) {
  51. return callback(OError.tag(error))
  52. }
  53. LabelsManager.getLabels(projectId, function (error, labels) {
  54. if (error) {
  55. return callback(OError.tag(error))
  56. }
  57. const labelsByVersion = {}
  58. for (const label of labels) {
  59. if (labelsByVersion[label.version] == null) {
  60. labelsByVersion[label.version] = []
  61. }
  62. labelsByVersion[label.version].push(label)
  63. }
  64. WebApiManager.getHistoryId(projectId, function (error, historyId) {
  65. if (error) return callback(error)
  66. let chunksRequested = 0
  67. let summarizedUpdates = []
  68. const shouldRequestMoreUpdates = cb => {
  69. return cb(
  70. null,
  71. chunksRequested < MAX_CHUNK_REQUESTS &&
  72. (nextVersionToRequest == null || nextVersionToRequest > 0) &&
  73. summarizedUpdates.length < options.min_count
  74. )
  75. }
  76. const getNextBatchOfUpdates = cb =>
  77. _getProjectUpdates(
  78. projectId,
  79. historyId,
  80. nextVersionToRequest,
  81. function (error, updateSet, startVersion) {
  82. if (error) {
  83. return cb(OError.tag(error))
  84. }
  85. // Updates are returned in time order, but we want to go back in time
  86. updateSet.reverse()
  87. updateSet = discardUnwantedUpdates(updateSet)
  88. summarizedUpdates = _summarizeUpdates(
  89. updateSet,
  90. labelsByVersion,
  91. summarizedUpdates
  92. )
  93. nextVersionToRequest = startVersion
  94. chunksRequested += 1
  95. cb()
  96. }
  97. )
  98. function discardUnwantedUpdates(updateSet) {
  99. // We're getting whole chunks from the OL history store, but we might
  100. // only want updates from before a certain version
  101. if (options.before == null) {
  102. return updateSet
  103. } else {
  104. return updateSet.filter(u => u.v < options.before)
  105. }
  106. }
  107. // If the project doesn't have a history then we can bail out here
  108. HistoryApiManager.shouldUseProjectHistory(
  109. projectId,
  110. function (error, shouldUseProjectHistory) {
  111. if (error) {
  112. return callback(OError.tag(error))
  113. }
  114. if (shouldUseProjectHistory) {
  115. async.whilst(
  116. shouldRequestMoreUpdates,
  117. getNextBatchOfUpdates,
  118. function (error) {
  119. if (error) {
  120. return callback(OError.tag(error))
  121. }
  122. callback(
  123. null,
  124. summarizedUpdates,
  125. nextVersionToRequest > 0 ? nextVersionToRequest : undefined
  126. )
  127. }
  128. )
  129. } else {
  130. logger.debug(
  131. { projectId },
  132. 'returning no updates as project does not use history'
  133. )
  134. callback(null, [])
  135. }
  136. }
  137. )
  138. })
  139. })
  140. })
  141. }
  142. function _getProjectUpdates(projectId, historyId, version, callback) {
  143. function getChunk(cb) {
  144. if (version != null) {
  145. HistoryStoreManager.getChunkAtVersion(projectId, historyId, version, cb)
  146. } else {
  147. HistoryStoreManager.getMostRecentChunk(projectId, historyId, cb)
  148. }
  149. }
  150. getChunk(function (error, chunk) {
  151. if (error) {
  152. return callback(OError.tag(error))
  153. }
  154. const oldestVersion = chunk.chunk.startVersion
  155. ChunkTranslator.convertToSummarizedUpdates(
  156. chunk,
  157. function (error, updateSet) {
  158. if (error) {
  159. return callback(OError.tag(error))
  160. }
  161. callback(error, updateSet, oldestVersion)
  162. }
  163. )
  164. })
  165. }
  166. function _summarizeUpdates(updates, labels, existingSummarizedUpdates) {
  167. if (existingSummarizedUpdates == null) {
  168. existingSummarizedUpdates = []
  169. }
  170. const summarizedUpdates = existingSummarizedUpdates.slice()
  171. for (const update of updates) {
  172. // The client needs to know the exact version that a delete happened, in order
  173. // to be able to restore. So even when summarizing, retain the version that each
  174. // projectOp happened at.
  175. for (const projectOp of update.project_ops) {
  176. projectOp.atV = update.v
  177. }
  178. const summarizedUpdate = summarizedUpdates[summarizedUpdates.length - 1]
  179. const labelsForVersion = labels[update.v + 1] || []
  180. if (
  181. summarizedUpdate &&
  182. _shouldMergeUpdate(update, summarizedUpdate, labelsForVersion)
  183. ) {
  184. _mergeUpdate(update, summarizedUpdate)
  185. } else {
  186. const newUpdate = {
  187. fromV: update.v,
  188. toV: update.v + 1,
  189. meta: {
  190. users: update.meta.users,
  191. start_ts: update.meta.start_ts,
  192. end_ts: update.meta.end_ts,
  193. },
  194. labels: labelsForVersion,
  195. pathnames: new Set(update.pathnames),
  196. project_ops: update.project_ops.slice(), // Clone since we'll modify
  197. }
  198. if (update.meta.origin) {
  199. newUpdate.meta.origin = update.meta.origin
  200. }
  201. summarizedUpdates.push(newUpdate)
  202. }
  203. }
  204. return summarizedUpdates
  205. }
  206. /**
  207. * Given an update, the latest summarized update, and the labels that apply to
  208. * the update, figure out if we can merge the update into the summarized
  209. * update.
  210. */
  211. function _shouldMergeUpdate(update, summarizedUpdate, labels) {
  212. // Split updates on labels
  213. if (labels.length > 0) {
  214. return false
  215. }
  216. // Split updates on origin
  217. if (update.meta.origin) {
  218. if (summarizedUpdate.meta.origin) {
  219. if (update.meta.origin.kind !== summarizedUpdate.meta.origin.kind) {
  220. return false
  221. }
  222. } else {
  223. return false
  224. }
  225. } else if (summarizedUpdate.meta.origin) {
  226. return false
  227. }
  228. // Split updates if it's been too long since the last update. We're going
  229. // backwards in time through the updates, so the update comes before the summarized update.
  230. if (
  231. summarizedUpdate.meta.end_ts - update.meta.start_ts >=
  232. TIME_BETWEEN_DISTINCT_UPDATES
  233. ) {
  234. return false
  235. }
  236. // Do not merge text operations and file operations, except for history resyncs
  237. const updateHasTextOps = update.pathnames.length > 0
  238. const updateHasFileOps = update.project_ops.length > 0
  239. const summarizedUpdateHasTextOps = summarizedUpdate.pathnames.size > 0
  240. const summarizedUpdateHasFileOps = summarizedUpdate.project_ops.length > 0
  241. const isHistoryResync =
  242. update.meta.origin &&
  243. ['history-resync', 'history-migration'].includes(update.meta.origin.kind)
  244. if (
  245. !isHistoryResync &&
  246. ((updateHasTextOps && summarizedUpdateHasFileOps) ||
  247. (updateHasFileOps && summarizedUpdateHasTextOps))
  248. ) {
  249. return false
  250. }
  251. return true
  252. }
  253. /**
  254. * Merge an update into a summarized update.
  255. *
  256. * This mutates the summarized update.
  257. */
  258. function _mergeUpdate(update, summarizedUpdate) {
  259. // check if the user in this update is already present in the earliest update,
  260. // if not, add them to the users list of the earliest update
  261. summarizedUpdate.meta.users = _.uniqBy(
  262. _.union(summarizedUpdate.meta.users, update.meta.users),
  263. function (user) {
  264. if (user == null) {
  265. return null
  266. }
  267. if (user.id == null) {
  268. return user
  269. }
  270. return user.id
  271. }
  272. )
  273. summarizedUpdate.fromV = Math.min(summarizedUpdate.fromV, update.v)
  274. summarizedUpdate.toV = Math.max(summarizedUpdate.toV, update.v + 1)
  275. summarizedUpdate.meta.start_ts = Math.min(
  276. summarizedUpdate.meta.start_ts,
  277. update.meta.start_ts
  278. )
  279. summarizedUpdate.meta.end_ts = Math.max(
  280. summarizedUpdate.meta.end_ts,
  281. update.meta.end_ts
  282. )
  283. // Add file operations
  284. for (const op of update.project_ops || []) {
  285. summarizedUpdate.project_ops.push(op)
  286. if (op.add) {
  287. // Merging a file creation. Remove any corresponding edit since that's redundant.
  288. summarizedUpdate.pathnames.delete(op.add.pathname)
  289. }
  290. }
  291. // Add edit operations
  292. for (const pathname of update.pathnames || []) {
  293. summarizedUpdate.pathnames.add(pathname)
  294. }
  295. }