anycable / anycable-rails

AnyCable for Ruby on Rails applications
https://anycable.io
MIT License
499 stars 35 forks source link

Well, I have to say that it's impossible out-of-the-box with AnyCable. There is no a way to _ask_ AnyCable about anything (including the list of active streams). #153

Closed BlockerCambodia closed 3 years ago

BlockerCambodia commented 3 years ago

Well, I have to say that it's impossible out-of-the-box with AnyCable. There is no a way to ask AnyCable about anything (including the list of active streams).

On the other hand, I'd suggest to avoid Action Cable hacking too (i.e. accessing hidden internals, such as channels list) and implement streams tracking manually. For example, using Redis and subscription callbacks:

# pseudo-code
class PresenceTracker
  def self.page_users(page)
     redis.smembers(page)
  end

  def self.track(page, user_id)
     redis.sadd(page, user_id)
  end

  def self.untrack(page, user_id)
    redis.srem(page, user_id)
  end
end

class MyChannel < ApplicationCable::Channel
  after_subscribed :track_user
  after_unsubscribed :untrack_user

  def track_user
     PresenceTracker.track(params[:page], current_user.id)
  end

   def untrack_user
     PresenceTracker.untrack(params[:page], current_user.id)
  end
end

PresenceTracker.page_users("page_A").each { |user_id| ActionCable.broadcast("page_A_#{user_id}", ...)  }

Smth like that (but we have to deal with possible race conditions in Redis).

Originally posted by @palkan in https://github.com/anycable/anycable-rails/issues/12#issuecomment-319362658