UpdatesManager.coffee 9.0 KB

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