UpdatesManager.coffee 9.8 KB

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