ChannelManager.coffee 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. logger = require 'logger-sharelatex'
  2. metrics = require "metrics-sharelatex"
  3. settings = require "settings-sharelatex"
  4. ClientMap = new Map() # for each redis client, store a Map of subscribed channels (channelname -> subscribe promise)
  5. # Manage redis pubsub subscriptions for individual projects and docs, ensuring
  6. # that we never subscribe to a channel multiple times. The socket.io side is
  7. # handled by RoomManager.
  8. module.exports = ChannelManager =
  9. getClientMapEntry: (rclient) ->
  10. # return the per-client channel map if it exists, otherwise create and
  11. # return an empty map for the client.
  12. ClientMap.get(rclient) || ClientMap.set(rclient, new Map()).get(rclient)
  13. subscribe: (rclient, baseChannel, id) ->
  14. clientChannelMap = @getClientMapEntry(rclient)
  15. channel = "#{baseChannel}:#{id}"
  16. # we track pending subscribes because we want to be sure that the
  17. # channel is active before letting the client join the doc or project,
  18. # so that events are not lost.
  19. if clientChannelMap.has(channel)
  20. logger.warn {channel}, "subscribe already actioned"
  21. # return the existing subscribe promise, so we can wait for it to resolve
  22. return clientChannelMap.get(channel)
  23. else
  24. # get the subscribe promise and return it, the actual subscribe
  25. # completes in the background
  26. subscribePromise = rclient.subscribe channel
  27. clientChannelMap.set(channel, subscribePromise)
  28. logger.log {channel}, "subscribed to new channel"
  29. metrics.inc "subscribe.#{baseChannel}"
  30. return subscribePromise
  31. unsubscribe: (rclient, baseChannel, id) ->
  32. clientChannelMap = @getClientMapEntry(rclient)
  33. channel = "#{baseChannel}:#{id}"
  34. # we don't need to track pending unsubscribes, because we there is no
  35. # harm if events continue to arrive on the channel while the unsubscribe
  36. # command in pending.
  37. if !clientChannelMap.has(channel)
  38. logger.error {channel}, "not subscribed - shouldn't happen"
  39. else
  40. rclient.unsubscribe channel # completes in the background
  41. clientChannelMap.delete(channel)
  42. logger.log {channel}, "unsubscribed from channel"
  43. metrics.inc "unsubscribe.#{baseChannel}"
  44. publish: (rclient, baseChannel, id, data) ->
  45. if id is 'all' or !settings.publishOnIndividualChannels
  46. channel = baseChannel
  47. else
  48. channel = "#{baseChannel}:#{id}"
  49. # we publish on a different client to the subscribe, so we can't
  50. # check for the channel existing here
  51. rclient.publish channel, data