UpdatesManager.coffee 10.0 KB

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