UpdatesManager.coffee 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. MongoManager = require "./MongoManager"
  2. PackManager = require "./PackManager"
  3. RedisManager = require "./RedisManager"
  4. UpdateCompressor = require "./UpdateCompressor"
  5. LockManager = require "./LockManager"
  6. WebApiManager = require "./WebApiManager"
  7. UpdateTrimmer = require "./UpdateTrimmer"
  8. logger = require "logger-sharelatex"
  9. async = require "async"
  10. _ = require "underscore"
  11. Settings = require "settings-sharelatex"
  12. module.exports = UpdatesManager =
  13. compressAndSaveRawUpdates: (project_id, doc_id, rawUpdates, temporary, callback = (error) ->) ->
  14. length = rawUpdates.length
  15. if length == 0
  16. return callback()
  17. # FIXME: we no longer need the lastCompressedUpdate, so change functions not to need it
  18. # CORRECTION: we do use it to log the time in case of error
  19. MongoManager.peekLastCompressedUpdate doc_id, (error, lastCompressedUpdate, lastVersion) ->
  20. # lastCompressedUpdate is the most recent update in Mongo, and
  21. # lastVersion is its sharejs version number.
  22. #
  23. # The peekLastCompressedUpdate method may pass the update back
  24. # as 'null' (for example if the previous compressed update has
  25. # been archived). In this case it can still pass back the
  26. # lastVersion from the update to allow us to check consistency.
  27. return callback(error) if error?
  28. # Ensure that raw updates start where lastVersion left off
  29. if lastVersion?
  30. rawUpdates = rawUpdates.slice(0)
  31. while rawUpdates[0]? and rawUpdates[0].v <= lastVersion
  32. rawUpdates.shift()
  33. if rawUpdates[0]? and rawUpdates[0].v != lastVersion + 1
  34. ts = lastCompressedUpdate?.meta?.end_ts
  35. last_timestamp = if ts? then new Date(ts) else 'unknown time'
  36. error = new Error("Tried to apply raw op at version #{rawUpdates[0].v} to last compressed update with version #{lastVersion} from #{last_timestamp}")
  37. logger.error err: error, doc_id: doc_id, project_id: project_id, prev_end_ts: ts, "inconsistent doc versions"
  38. if Settings.trackchanges?.continueOnError and rawUpdates[0].v > lastVersion + 1
  39. # we have lost some ops - continue to write into the database, we can't recover at this point
  40. lastCompressedUpdate = null
  41. else
  42. return callback error
  43. if rawUpdates.length == 0
  44. return callback()
  45. # some old large ops in redis need to be rejected, they predate
  46. # the size limit that now prevents them going through the system
  47. REJECT_LARGE_OP_SIZE = 4 * 1024 * 1024
  48. for rawUpdate in rawUpdates
  49. opSizes = ((op.i?.length || op.d?.length) for op in rawUpdate?.op or [])
  50. size = _.max opSizes
  51. if size > REJECT_LARGE_OP_SIZE
  52. error = new Error("dropped op exceeding maximum allowed size of #{REJECT_LARGE_OP_SIZE}")
  53. logger.error err: error, doc_id: doc_id, project_id: project_id, size: size, rawUpdate: rawUpdate, "dropped op - too big"
  54. rawUpdate.op = []
  55. compressedUpdates = UpdateCompressor.compressRawUpdates null, rawUpdates
  56. PackManager.insertCompressedUpdates project_id, doc_id, lastCompressedUpdate, compressedUpdates, temporary, (error, result) ->
  57. return callback(error) if error?
  58. logger.log {project_id, doc_id, orig_v: lastCompressedUpdate?.v, new_v: result.v}, "inserted updates into pack" if result?
  59. callback()
  60. REDIS_READ_BATCH_SIZE: 100
  61. processUncompressedUpdates: (project_id, doc_id, callback = (error) ->) ->
  62. UpdateTrimmer.shouldTrimUpdates project_id, (error, temporary) ->
  63. return callback(error) if error?
  64. MongoManager.backportProjectId project_id, doc_id, (error) ->
  65. return callback(error) if error?
  66. # get the updates as strings from redis (so we can delete them after they are applied)
  67. RedisManager.getOldestDocUpdates doc_id, UpdatesManager.REDIS_READ_BATCH_SIZE, (error, docUpdates) ->
  68. return callback(error) if error?
  69. length = docUpdates.length
  70. # parse the redis strings into ShareJs updates
  71. RedisManager.expandDocUpdates docUpdates, (error, rawUpdates) ->
  72. return callback(error) if error?
  73. logger.log project_id: project_id, doc_id: doc_id, rawUpdates: rawUpdates, "retrieved raw updates from redis"
  74. UpdatesManager.compressAndSaveRawUpdates project_id, doc_id, rawUpdates, temporary, (error) ->
  75. return callback(error) if error?
  76. logger.log project_id: project_id, doc_id: doc_id, "compressed and saved doc updates"
  77. # delete the applied updates from redis
  78. RedisManager.deleteAppliedDocUpdates project_id, doc_id, docUpdates, (error) ->
  79. return callback(error) if error?
  80. if length == UpdatesManager.REDIS_READ_BATCH_SIZE
  81. # There might be more updates
  82. logger.log project_id: project_id, doc_id: doc_id, "continuing processing updates"
  83. setTimeout () ->
  84. UpdatesManager.processUncompressedUpdates project_id, doc_id, callback
  85. , 0
  86. else
  87. logger.log project_id: project_id, doc_id: doc_id, "all raw updates processed"
  88. callback()
  89. processUncompressedUpdatesWithLock: (project_id, doc_id, callback = (error) ->) ->
  90. LockManager.runWithLock(
  91. "HistoryLock:#{doc_id}",
  92. (releaseLock) ->
  93. UpdatesManager.processUncompressedUpdates project_id, doc_id, releaseLock
  94. callback
  95. )
  96. processUncompressedUpdatesForProject: (project_id, callback = (error) ->) ->
  97. RedisManager.getDocIdsWithHistoryOps project_id, (error, doc_ids) ->
  98. return callback(error) if error?
  99. jobs = []
  100. for doc_id in doc_ids
  101. do (doc_id) ->
  102. jobs.push (callback) ->
  103. UpdatesManager.processUncompressedUpdatesWithLock project_id, doc_id, callback
  104. async.parallelLimit jobs, 5, callback
  105. getDocUpdates: (project_id, doc_id, options = {}, callback = (error, updates) ->) ->
  106. UpdatesManager.processUncompressedUpdatesWithLock project_id, doc_id, (error) ->
  107. return callback(error) if error?
  108. #console.log "options", options
  109. PackManager.getOpsByVersionRange project_id, doc_id, options.from, options.to, (error, updates) ->
  110. return callback(error) if error?
  111. UpdatesManager.fillUserInfo updates, (err, results) ->
  112. return callback(err) if err?
  113. callback null, results
  114. getDocUpdatesWithUserInfo: (project_id, doc_id, options = {}, callback = (error, updates) ->) ->
  115. UpdatesManager.getDocUpdates project_id, doc_id, options, (error, updates) ->
  116. return callback(error) if error?
  117. UpdatesManager.fillUserInfo updates, (error, updates) ->
  118. return callback(error) if error?
  119. callback null, updates
  120. getSummarizedProjectUpdates: (project_id, options = {}, callback = (error, updates) ->) ->
  121. options.min_count ||= 25
  122. summarizedUpdates = []
  123. before = options.before
  124. nextBeforeTimestamp = null
  125. UpdatesManager.processUncompressedUpdatesForProject project_id, (error) ->
  126. return callback(error) if error?
  127. PackManager.makeProjectIterator project_id, before, (err, iterator) ->
  128. return callback(err) if err?
  129. # repeatedly get updates and pass them through the summariser to get an final output with user info
  130. async.whilst () ->
  131. #console.log "checking iterator.done", iterator.done()
  132. return summarizedUpdates.length < options.min_count and not iterator.done()
  133. , (cb) ->
  134. iterator.next (err, partialUpdates) ->
  135. return callback(err) if err?
  136. #logger.log {partialUpdates}, 'got partialUpdates'
  137. return cb() if partialUpdates.length is 0 ## FIXME should try to avoid this happening
  138. nextBeforeTimestamp = partialUpdates[partialUpdates.length - 1].meta.end_ts
  139. # add the updates to the summary list
  140. summarizedUpdates = UpdatesManager._summarizeUpdates partialUpdates, summarizedUpdates
  141. cb()
  142. , () ->
  143. # finally done all updates
  144. #console.log 'summarized Updates', summarizedUpdates
  145. UpdatesManager.fillSummarizedUserInfo summarizedUpdates, (err, results) ->
  146. return callback(err) if err?
  147. callback null, results, if not iterator.done() then nextBeforeTimestamp else undefined
  148. fetchUserInfo: (users, callback = (error, fetchedUserInfo) ->) ->
  149. jobs = []
  150. fetchedUserInfo = {}
  151. for user_id of users
  152. do (user_id) ->
  153. jobs.push (callback) ->
  154. WebApiManager.getUserInfo user_id, (error, userInfo) ->
  155. return callback(error) if error?
  156. fetchedUserInfo[user_id] = userInfo
  157. callback()
  158. async.series jobs, (err) ->
  159. return callback(err) if err?
  160. callback(null, fetchedUserInfo)
  161. fillUserInfo: (updates, callback = (error, updates) ->) ->
  162. users = {}
  163. for update in updates
  164. user_id = update.meta.user_id
  165. if UpdatesManager._validUserId(user_id)
  166. users[user_id] = true
  167. UpdatesManager.fetchUserInfo users, (error, fetchedUserInfo) ->
  168. return callback(error) if error?
  169. for update in updates
  170. user_id = update.meta.user_id
  171. delete update.meta.user_id
  172. if UpdatesManager._validUserId(user_id)
  173. update.meta.user = fetchedUserInfo[user_id]
  174. callback null, updates
  175. fillSummarizedUserInfo: (updates, callback = (error, updates) ->) ->
  176. users = {}
  177. for update in updates
  178. user_ids = update.meta.user_ids or []
  179. for user_id in user_ids
  180. if UpdatesManager._validUserId(user_id)
  181. users[user_id] = true
  182. UpdatesManager.fetchUserInfo users, (error, fetchedUserInfo) ->
  183. return callback(error) if error?
  184. for update in updates
  185. user_ids = update.meta.user_ids or []
  186. update.meta.users = []
  187. delete update.meta.user_ids
  188. for user_id in user_ids
  189. if UpdatesManager._validUserId(user_id)
  190. update.meta.users.push fetchedUserInfo[user_id]
  191. callback null, updates
  192. _validUserId: (user_id) ->
  193. if !user_id?
  194. return false
  195. else
  196. return !!user_id.match(/^[a-f0-9]{24}$/)
  197. TIME_BETWEEN_DISTINCT_UPDATES: fiveMinutes = 5 * 60 * 1000
  198. _summarizeUpdates: (updates, existingSummarizedUpdates = []) ->
  199. summarizedUpdates = existingSummarizedUpdates.slice()
  200. for update in updates
  201. earliestUpdate = summarizedUpdates[summarizedUpdates.length - 1]
  202. if earliestUpdate and earliestUpdate.meta.start_ts - update.meta.end_ts < @TIME_BETWEEN_DISTINCT_UPDATES
  203. # check if the user in this update is already present in the earliest update,
  204. # if not, add them to the users list of the earliest update
  205. earliestUpdate.meta.user_ids = _.union earliestUpdate.meta.user_ids, update.meta.user_id
  206. doc_id = update.doc_id.toString()
  207. doc = earliestUpdate.docs[doc_id]
  208. if doc?
  209. doc.fromV = Math.min(doc.fromV, update.v)
  210. doc.toV = Math.max(doc.toV, update.v)
  211. else
  212. earliestUpdate.docs[doc_id] =
  213. fromV: update.v
  214. toV: update.v
  215. earliestUpdate.meta.start_ts = Math.min(earliestUpdate.meta.start_ts, update.meta.start_ts)
  216. earliestUpdate.meta.end_ts = Math.max(earliestUpdate.meta.end_ts, update.meta.end_ts)
  217. else
  218. newUpdate =
  219. meta:
  220. user_ids: []
  221. start_ts: update.meta.start_ts
  222. end_ts: update.meta.end_ts
  223. docs: {}
  224. newUpdate.docs[update.doc_id.toString()] =
  225. fromV: update.v
  226. toV: update.v
  227. newUpdate.meta.user_ids.push update.meta.user_id
  228. summarizedUpdates.push newUpdate
  229. return summarizedUpdates