This is not necessarily the best solution, but I created the message queue as follows: I created a new table ("SSE") in my database, and in the model I wanted to watch, I added callbacks
class MyModel < ActiveRecord::Base after_save :queue_sse after_delete :queue_sse
Then in watch action:
def watch connected_users << current_user # pseudo for a mutex-synched accessor self.response.headers["Content-Type"] = "text/event-stream" self.response.headers["Last-Modified"] = Time.now.ctime.to_json self.response_body = Enumerator.new do |y| loop do sleep 5 ActiveRecord::Base.uncached do updates = SSE.find_all_by_user_id(current_user) updates.each do |update| puts "update found: #{update.id}\n" y << ["event: message", "data: #{update.id}\n\n"].join("\n") update.destroy end end end end # TODO add error catching, and on IOError, remove the current_user end
This very often gets into the database. It should probably be built on memcached, a mutex class variable or similar.
(NB - requires streaming, for example, config.threadsafe! And a streaming server, of course.)
Zachb source share