UpdatesManager.coffee 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. MongoManager = require "./MongoManager"
  2. RedisManager = require "./RedisManager"
  3. UpdateCompressor = require "./UpdateCompressor"
  4. LockManager = require "./LockManager"
  5. WebApiManager = require "./WebApiManager"
  6. UpdateTrimmer = require "./UpdateTrimmer"
  7. logger = require "logger-sharelatex"
  8. async = require "async"
  9. DocArchiveManager = require "./DocArchiveManager"
  10. module.exports = UpdatesManager =
  11. compressAndSaveRawUpdates: (project_id, doc_id, rawUpdates, temporary, callback = (error) ->) ->
  12. length = rawUpdates.length
  13. if length == 0
  14. return callback()
  15. MongoManager.popLastCompressedUpdate doc_id, (error, lastCompressedUpdate, lastVersion) ->
  16. # lastCompressedUpdate is the most recent update in Mongo.
  17. #
  18. # The popLastCompressedUpdate method may pass it back as 'null'
  19. # to force the start of a new compressed update, even when there
  20. # was a previous compressed update in Mongo. In this case it
  21. # passes back the lastVersion from the update to check
  22. # consistency.
  23. # when lastVersion is not provided, default to lastCompressedUpdate.v
  24. lastVersion ?= lastCompressedUpdate?.v
  25. return callback(error) if error?
  26. # Ensure that raw updates start where lastVersion left off
  27. if lastVersion?
  28. rawUpdates = rawUpdates.slice(0)
  29. while rawUpdates[0]? and rawUpdates[0].v <= lastVersion
  30. rawUpdates.shift()
  31. if rawUpdates[0]? and rawUpdates[0].v != lastVersion + 1
  32. error = new Error("Tried to apply raw op at version #{rawUpdates[0].v} to last compressed update with version #{lastVersion}")
  33. logger.error err: error, doc_id: doc_id, project_id: project_id, "inconsistent doc versions"
  34. # Push the update back into Mongo - if it was present - catching errors at this
  35. # point is useless, we're already bailing
  36. if lastCompressedUpdate?
  37. MongoManager.insertCompressedUpdates project_id, doc_id, [lastCompressedUpdate], temporary, () ->
  38. return callback error
  39. else
  40. return callback error
  41. compressedUpdates = UpdateCompressor.compressRawUpdates lastCompressedUpdate, rawUpdates
  42. MongoManager.insertCompressedUpdates project_id, doc_id, compressedUpdates, temporary,(error) ->
  43. return callback(error) if error?
  44. logger.log project_id: project_id, doc_id: doc_id, rawUpdatesLength: length, compressedUpdatesLength: compressedUpdates.length, "compressed doc updates"
  45. callback()
  46. REDIS_READ_BATCH_SIZE: 100
  47. processUncompressedUpdates: (project_id, doc_id, callback = (error) ->) ->
  48. UpdateTrimmer.shouldTrimUpdates project_id, (error, temporary) ->
  49. return callback(error) if error?
  50. MongoManager.backportProjectId project_id, doc_id, (error) ->
  51. return callback(error) if error?
  52. RedisManager.getOldestRawUpdates doc_id, UpdatesManager.REDIS_READ_BATCH_SIZE, (error, rawUpdates) ->
  53. return callback(error) if error?
  54. length = rawUpdates.length
  55. UpdatesManager.compressAndSaveRawUpdates project_id, doc_id, rawUpdates, temporary, (error) ->
  56. return callback(error) if error?
  57. logger.log project_id: project_id, doc_id: doc_id, "compressed and saved doc updates"
  58. RedisManager.deleteOldestRawUpdates project_id, doc_id, length, (error) ->
  59. return callback(error) if error?
  60. if length == UpdatesManager.REDIS_READ_BATCH_SIZE
  61. # There might be more updates
  62. logger.log project_id: project_id, doc_id: doc_id, "continuing processing updates"
  63. setTimeout () ->
  64. UpdatesManager.processUncompressedUpdates project_id, doc_id, callback
  65. , 0
  66. else
  67. logger.log project_id: project_id, doc_id: doc_id, "all raw updates processed"
  68. callback()
  69. processUncompressedUpdatesWithLock: (project_id, doc_id, callback = (error) ->) ->
  70. LockManager.runWithLock(
  71. "HistoryLock:#{doc_id}",
  72. (releaseLock) ->
  73. UpdatesManager.processUncompressedUpdates project_id, doc_id, releaseLock
  74. callback
  75. )
  76. processUncompressedUpdatesForProject: (project_id, callback = (error) ->) ->
  77. RedisManager.getDocIdsWithHistoryOps project_id, (error, doc_ids) ->
  78. return callback(error) if error?
  79. jobs = []
  80. for doc_id in doc_ids
  81. do (doc_id) ->
  82. jobs.push (callback) ->
  83. UpdatesManager.processUncompressedUpdatesWithLock project_id, doc_id, callback
  84. async.parallelLimit jobs, 5, callback
  85. getDocUpdates: (project_id, doc_id, options = {}, callback = (error, updates) ->) ->
  86. UpdatesManager.processUncompressedUpdatesWithLock project_id, doc_id, (error) ->
  87. return callback(error) if error?
  88. MongoManager.getDocUpdates doc_id, options, callback
  89. getDocUpdatesWithUserInfo: (project_id, doc_id, options = {}, callback = (error, updates) ->) ->
  90. UpdatesManager.getDocUpdates project_id, doc_id, options, (error, updates) ->
  91. return callback(error) if error?
  92. UpdatesManager.fillUserInfo updates, (error, updates) ->
  93. return callback(error) if error?
  94. callback null, updates
  95. getProjectUpdates: (project_id, options = {}, callback = (error, updates) ->) ->
  96. UpdatesManager.processUncompressedUpdatesForProject project_id, (error) ->
  97. return callback(error) if error?
  98. MongoManager.getProjectUpdates project_id, options, (error, updates) ->
  99. jobs = []
  100. for update in updates
  101. if update.inS3
  102. do (update) ->
  103. jobs.push (callback) -> DocArchiveManager.unArchiveDocChanges update.project_id, update.doc_id, callback
  104. if jobs.length?
  105. async.series jobs, (err) ->
  106. MongoManager.getProjectUpdates project_id, options, callback
  107. else
  108. callback(error, updates)
  109. getProjectUpdatesWithUserInfo: (project_id, options = {}, callback = (error, updates) ->) ->
  110. UpdatesManager.getProjectUpdates project_id, options, (error, updates) ->
  111. return callback(error) if error?
  112. UpdatesManager.fillUserInfo updates, (error, updates) ->
  113. return callback(error) if error?
  114. callback null, updates
  115. getSummarizedProjectUpdates: (project_id, options = {}, callback = (error, updates) ->) ->
  116. options.min_count ||= 25
  117. summarizedUpdates = []
  118. before = options.before
  119. do fetchNextBatch = () ->
  120. UpdatesManager._extendBatchOfSummarizedUpdates project_id, summarizedUpdates, before, options.min_count, (error, updates, nextBeforeUpdate) ->
  121. return callback(error) if error?
  122. if !nextBeforeUpdate? or updates.length >= options.min_count
  123. callback null, updates, nextBeforeUpdate
  124. else
  125. before = nextBeforeUpdate
  126. summarizedUpdates = updates
  127. fetchNextBatch()
  128. _extendBatchOfSummarizedUpdates: (
  129. project_id,
  130. existingSummarizedUpdates,
  131. before, desiredLength,
  132. callback = (error, summarizedUpdates, endOfDatabase) ->
  133. ) ->
  134. UpdatesManager.getProjectUpdatesWithUserInfo project_id, { before: before, limit: 3 * desiredLength }, (error, updates) ->
  135. return callback(error) if error?
  136. # Suppose in this request we have fetch the solid updates. In the next request we need
  137. # to fetch the dotted updates. These are defined by having an end timestamp less than
  138. # the last update's end timestamp (updates are ordered by descending end_ts). I.e.
  139. # start_ts--v v--end_ts
  140. # doc1: |......| |...| |-------|
  141. # doc2: |------------------|
  142. # ^----- Next time, fetch all updates with an
  143. # end_ts less than this
  144. #
  145. if updates? and updates.length > 0
  146. nextBeforeTimestamp = updates[updates.length - 1].meta.end_ts
  147. if nextBeforeTimestamp >= before
  148. error = new Error("history order is broken")
  149. logger.error err: error, project_id:project_id, nextBeforeTimestamp: nextBeforeTimestamp, before:before, "error in project history"
  150. return callback(error)
  151. else
  152. nextBeforeTimestamp = null
  153. summarizedUpdates = UpdatesManager._summarizeUpdates(
  154. updates, existingSummarizedUpdates
  155. )
  156. callback null,
  157. summarizedUpdates,
  158. nextBeforeTimestamp
  159. fillUserInfo: (updates, callback = (error, updates) ->) ->
  160. users = {}
  161. for update in updates
  162. if UpdatesManager._validUserId(update.meta.user_id)
  163. users[update.meta.user_id] = true
  164. jobs = []
  165. for user_id of users
  166. do (user_id) ->
  167. jobs.push (callback) ->
  168. WebApiManager.getUserInfo user_id, (error, userInfo) ->
  169. return callback(error) if error?
  170. users[user_id] = userInfo
  171. callback()
  172. async.series jobs, (error) ->
  173. return callback(error) if error?
  174. for update in updates
  175. user_id = update.meta.user_id
  176. delete update.meta.user_id
  177. if UpdatesManager._validUserId(user_id)
  178. update.meta.user = users[user_id]
  179. callback null, updates
  180. _validUserId: (user_id) ->
  181. if !user_id?
  182. return false
  183. else
  184. return !!user_id.match(/^[a-f0-9]{24}$/)
  185. TIME_BETWEEN_DISTINCT_UPDATES: fiveMinutes = 5 * 60 * 1000
  186. _summarizeUpdates: (updates, existingSummarizedUpdates = []) ->
  187. summarizedUpdates = existingSummarizedUpdates.slice()
  188. for update in updates
  189. earliestUpdate = summarizedUpdates[summarizedUpdates.length - 1]
  190. if earliestUpdate and earliestUpdate.meta.start_ts - update.meta.end_ts < @TIME_BETWEEN_DISTINCT_UPDATES
  191. # check if the user in this update is already present in the earliest update,
  192. # if not, add them to the users list of the earliest update
  193. userExists = false
  194. for user in earliestUpdate.meta.users
  195. if (!user and !update.meta.user) or (user?.id == update.meta.user?.id)
  196. userExists = true
  197. break
  198. if !userExists
  199. earliestUpdate.meta.users.push update.meta.user
  200. doc_id = update.doc_id.toString()
  201. doc = earliestUpdate.docs[doc_id]
  202. if doc?
  203. doc.fromV = Math.min(doc.fromV, update.v)
  204. doc.toV = Math.max(doc.toV, update.v)
  205. else
  206. earliestUpdate.docs[doc_id] =
  207. fromV: update.v
  208. toV: update.v
  209. earliestUpdate.meta.start_ts = Math.min(earliestUpdate.meta.start_ts, update.meta.start_ts)
  210. earliestUpdate.meta.end_ts = Math.max(earliestUpdate.meta.end_ts, update.meta.end_ts)
  211. else
  212. newUpdate =
  213. meta:
  214. users: []
  215. start_ts: update.meta.start_ts
  216. end_ts: update.meta.end_ts
  217. docs: {}
  218. newUpdate.docs[update.doc_id.toString()] =
  219. fromV: update.v
  220. toV: update.v
  221. newUpdate.meta.users.push update.meta.user
  222. summarizedUpdates.push newUpdate
  223. return summarizedUpdates