UpdatesManager.coffee 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. _ = 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. MongoManager.peekLastCompressedUpdate doc_id, (error, lastCompressedUpdate, lastVersion) ->
  18. # lastCompressedUpdate is the most recent update in Mongo.
  19. #
  20. # The peekLastCompressedUpdate method may pass it back as 'null'
  21. # to force the start of a new compressed update, even when there
  22. # was a previous compressed update in Mongo. In this case it
  23. # passes back the lastVersion from the update to check
  24. # consistency.
  25. # when lastVersion is not provided, default to lastCompressedUpdate.v
  26. lastVersion ?= lastCompressedUpdate?.v
  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. error = new Error("Tried to apply raw op at version #{rawUpdates[0].v} to last compressed update with version #{lastVersion}")
  35. logger.error err: error, doc_id: doc_id, project_id: project_id, "inconsistent doc versions"
  36. if Settings.trackchanges?.continueOnError and rawUpdates[0].v > lastVersion + 1
  37. # we have lost some ops - continue to write into the database, we can't recover at this point
  38. lastCompressedUpdate = null
  39. else
  40. return callback error
  41. compressedUpdates = UpdateCompressor.compressRawUpdates lastCompressedUpdate, rawUpdates
  42. if not lastCompressedUpdate?
  43. # no existing update, insert everything
  44. updateToModify = null
  45. updatesToInsert = compressedUpdates
  46. else
  47. # there are existing updates, see what happens when we
  48. # compress them together with the new ones
  49. [firstUpdate, additionalUpdates...] = compressedUpdates
  50. if firstUpdate.v == lastCompressedUpdate.v and _.isEqual(firstUpdate, lastCompressedUpdate)
  51. # first update version hasn't changed, skip it and insert remaining updates
  52. # this is an optimisation, we could update the existing op with itself
  53. updateToModify = null
  54. updatesToInsert = additionalUpdates
  55. else
  56. # first update version did changed, modify it and insert remaining updates
  57. updateToModify = firstUpdate
  58. updatesToInsert = additionalUpdates
  59. MongoManager.modifyCompressedUpdate lastCompressedUpdate, updateToModify, (error, result) ->
  60. return callback(error) if error?
  61. logger.log {project_id, doc_id, orig_v: lastCompressedUpdate.v, new_v: result.v}, "applied update in-place" if result?
  62. MongoManager.insertCompressedUpdates project_id, doc_id, updatesToInsert, temporary,(error) ->
  63. return callback(error) if error?
  64. logger.log project_id: project_id, doc_id: doc_id, rawUpdatesLength: length, compressedUpdatesLength: compressedUpdates.length, "compressed doc updates"
  65. callback()
  66. REDIS_READ_BATCH_SIZE: 100
  67. processUncompressedUpdates: (project_id, doc_id, callback = (error) ->) ->
  68. UpdateTrimmer.shouldTrimUpdates project_id, (error, temporary) ->
  69. return callback(error) if error?
  70. MongoManager.backportProjectId project_id, doc_id, (error) ->
  71. return callback(error) if error?
  72. # get the updates as strings from redis (so we can delete them after they are applied)
  73. RedisManager.getOldestDocUpdates doc_id, UpdatesManager.REDIS_READ_BATCH_SIZE, (error, docUpdates) ->
  74. return callback(error) if error?
  75. length = docUpdates.length
  76. # parse the redis strings into ShareJs updates
  77. RedisManager.expandDocUpdates docUpdates, (error, rawUpdates) ->
  78. return callback(error) if error?
  79. UpdatesManager.compressAndSaveRawUpdates project_id, doc_id, rawUpdates, temporary, (error) ->
  80. return callback(error) if error?
  81. logger.log project_id: project_id, doc_id: doc_id, "compressed and saved doc updates"
  82. # delete the applied updates from redis
  83. RedisManager.deleteAppliedDocUpdates project_id, doc_id, docUpdates, (error) ->
  84. return callback(error) if error?
  85. if length == UpdatesManager.REDIS_READ_BATCH_SIZE
  86. # There might be more updates
  87. logger.log project_id: project_id, doc_id: doc_id, "continuing processing updates"
  88. setTimeout () ->
  89. UpdatesManager.processUncompressedUpdates project_id, doc_id, callback
  90. , 0
  91. else
  92. logger.log project_id: project_id, doc_id: doc_id, "all raw updates processed"
  93. callback()
  94. processUncompressedUpdatesWithLock: (project_id, doc_id, callback = (error) ->) ->
  95. LockManager.runWithLock(
  96. "HistoryLock:#{doc_id}",
  97. (releaseLock) ->
  98. UpdatesManager.processUncompressedUpdates project_id, doc_id, releaseLock
  99. callback
  100. )
  101. processUncompressedUpdatesForProject: (project_id, callback = (error) ->) ->
  102. RedisManager.getDocIdsWithHistoryOps project_id, (error, doc_ids) ->
  103. return callback(error) if error?
  104. jobs = []
  105. for doc_id in doc_ids
  106. do (doc_id) ->
  107. jobs.push (callback) ->
  108. UpdatesManager.processUncompressedUpdatesWithLock project_id, doc_id, callback
  109. async.parallelLimit jobs, 5, callback
  110. getDocUpdates: (project_id, doc_id, options = {}, callback = (error, updates) ->) ->
  111. UpdatesManager.processUncompressedUpdatesWithLock project_id, doc_id, (error) ->
  112. return callback(error) if error?
  113. MongoManager.getDocUpdates doc_id, options, callback
  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. getProjectUpdates: (project_id, options = {}, callback = (error, updates) ->) ->
  121. UpdatesManager.processUncompressedUpdatesForProject project_id, (error) ->
  122. return callback(error) if error?
  123. MongoManager.getProjectUpdates project_id, options, (error, updates) ->
  124. jobs = []
  125. for update in updates
  126. if update.inS3
  127. do (update) ->
  128. jobs.push (callback) -> DocArchiveManager.unArchiveDocChanges update.project_id, update.doc_id, callback
  129. if jobs.length?
  130. async.series jobs, (err) ->
  131. MongoManager.getProjectUpdates project_id, options, callback
  132. else
  133. callback(error, updates)
  134. getProjectUpdatesWithUserInfo: (project_id, options = {}, callback = (error, updates) ->) ->
  135. UpdatesManager.getProjectUpdates project_id, options, (error, updates) ->
  136. return callback(error) if error?
  137. UpdatesManager.fillUserInfo updates, (error, updates) ->
  138. return callback(error) if error?
  139. callback null, updates
  140. getSummarizedProjectUpdates: (project_id, options = {}, callback = (error, updates) ->) ->
  141. options.min_count ||= 25
  142. summarizedUpdates = []
  143. before = options.before
  144. do fetchNextBatch = () ->
  145. UpdatesManager._extendBatchOfSummarizedUpdates project_id, summarizedUpdates, before, options.min_count, (error, updates, nextBeforeUpdate) ->
  146. return callback(error) if error?
  147. if !nextBeforeUpdate? or updates.length >= options.min_count
  148. callback null, updates, nextBeforeUpdate
  149. else
  150. before = nextBeforeUpdate
  151. summarizedUpdates = updates
  152. fetchNextBatch()
  153. _extendBatchOfSummarizedUpdates: (
  154. project_id,
  155. existingSummarizedUpdates,
  156. before, desiredLength,
  157. callback = (error, summarizedUpdates, endOfDatabase) ->
  158. ) ->
  159. UpdatesManager.getProjectUpdatesWithUserInfo project_id, { before: before, limit: 3 * desiredLength }, (error, updates) ->
  160. return callback(error) if error?
  161. # Suppose in this request we have fetch the solid updates. In the next request we need
  162. # to fetch the dotted updates. These are defined by having an end timestamp less than
  163. # the last update's end timestamp (updates are ordered by descending end_ts). I.e.
  164. # start_ts--v v--end_ts
  165. # doc1: |......| |...| |-------|
  166. # doc2: |------------------|
  167. # ^----- Next time, fetch all updates with an
  168. # end_ts less than this
  169. #
  170. if updates? and updates.length > 0
  171. nextBeforeTimestamp = updates[updates.length - 1].meta.end_ts
  172. if nextBeforeTimestamp >= before
  173. error = new Error("history order is broken")
  174. logger.error err: error, project_id:project_id, nextBeforeTimestamp: nextBeforeTimestamp, before:before, "error in project history"
  175. return callback(error)
  176. else
  177. nextBeforeTimestamp = null
  178. summarizedUpdates = UpdatesManager._summarizeUpdates(
  179. updates, existingSummarizedUpdates
  180. )
  181. callback null,
  182. summarizedUpdates,
  183. nextBeforeTimestamp
  184. fillUserInfo: (updates, callback = (error, updates) ->) ->
  185. users = {}
  186. for update in updates
  187. if UpdatesManager._validUserId(update.meta.user_id)
  188. users[update.meta.user_id] = true
  189. jobs = []
  190. for user_id of users
  191. do (user_id) ->
  192. jobs.push (callback) ->
  193. WebApiManager.getUserInfo user_id, (error, userInfo) ->
  194. return callback(error) if error?
  195. users[user_id] = userInfo
  196. callback()
  197. async.series jobs, (error) ->
  198. return callback(error) if error?
  199. for update in updates
  200. user_id = update.meta.user_id
  201. delete update.meta.user_id
  202. if UpdatesManager._validUserId(user_id)
  203. update.meta.user = users[user_id]
  204. callback null, updates
  205. _validUserId: (user_id) ->
  206. if !user_id?
  207. return false
  208. else
  209. return !!user_id.match(/^[a-f0-9]{24}$/)
  210. TIME_BETWEEN_DISTINCT_UPDATES: fiveMinutes = 5 * 60 * 1000
  211. _summarizeUpdates: (updates, existingSummarizedUpdates = []) ->
  212. summarizedUpdates = existingSummarizedUpdates.slice()
  213. for update in updates
  214. earliestUpdate = summarizedUpdates[summarizedUpdates.length - 1]
  215. if earliestUpdate and earliestUpdate.meta.start_ts - update.meta.end_ts < @TIME_BETWEEN_DISTINCT_UPDATES
  216. # check if the user in this update is already present in the earliest update,
  217. # if not, add them to the users list of the earliest update
  218. userExists = false
  219. for user in earliestUpdate.meta.users
  220. if (!user and !update.meta.user) or (user?.id == update.meta.user?.id)
  221. userExists = true
  222. break
  223. if !userExists
  224. earliestUpdate.meta.users.push update.meta.user
  225. doc_id = update.doc_id.toString()
  226. doc = earliestUpdate.docs[doc_id]
  227. if doc?
  228. doc.fromV = Math.min(doc.fromV, update.v)
  229. doc.toV = Math.max(doc.toV, update.v)
  230. else
  231. earliestUpdate.docs[doc_id] =
  232. fromV: update.v
  233. toV: update.v
  234. earliestUpdate.meta.start_ts = Math.min(earliestUpdate.meta.start_ts, update.meta.start_ts)
  235. earliestUpdate.meta.end_ts = Math.max(earliestUpdate.meta.end_ts, update.meta.end_ts)
  236. else
  237. newUpdate =
  238. meta:
  239. users: []
  240. start_ts: update.meta.start_ts
  241. end_ts: update.meta.end_ts
  242. docs: {}
  243. newUpdate.docs[update.doc_id.toString()] =
  244. fromV: update.v
  245. toV: update.v
  246. newUpdate.meta.users.push update.meta.user
  247. summarizedUpdates.push newUpdate
  248. return summarizedUpdates