RealTimeRedisManager.coffee 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. Settings = require('settings-sharelatex')
  2. rclient = require("redis-sharelatex").createClient(Settings.redis.realtime)
  3. Keys = Settings.redis.realtime.key_schema
  4. logger = require('logger-sharelatex')
  5. os = require "os"
  6. crypto = require "crypto"
  7. HOST = os.hostname()
  8. RND = crypto.randomBytes(4).toString('hex') # generate a random key for this process
  9. COUNT = 0
  10. MAX_OPS_PER_ITERATION = 8 # process a limited number of ops for safety
  11. module.exports = RealTimeRedisManager =
  12. getPendingUpdatesForDoc : (doc_id, callback)->
  13. multi = rclient.multi()
  14. multi.lrange Keys.pendingUpdates({doc_id}), 0, (MAX_OPS_PER_ITERATION-1)
  15. multi.ltrim Keys.pendingUpdates({doc_id}), MAX_OPS_PER_ITERATION, -1
  16. multi.exec (error, replys) ->
  17. return callback(error) if error?
  18. jsonUpdates = replys[0]
  19. updates = []
  20. for jsonUpdate in jsonUpdates
  21. try
  22. update = JSON.parse jsonUpdate
  23. catch e
  24. return callback e
  25. updates.push update
  26. callback error, updates
  27. getUpdatesLength: (doc_id, callback)->
  28. rclient.llen Keys.pendingUpdates({doc_id}), callback
  29. sendData: (data) ->
  30. # create a unique message id using a counter
  31. message_id = "doc:#{HOST}:#{RND}-#{COUNT++}"
  32. data?._id = message_id
  33. rclient.publish "applied-ops", JSON.stringify(data)