Created
February 18, 2016 17:18
-
-
Save jlsync/ea499fa90a9abfe04fa9 to your computer and use it in GitHub Desktop.
StreamingController
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StreamingController < ApplicationController | |
include ActionController::Live | |
before_filter :require_user | |
def index | |
Rails.logger.info "streaming#index" | |
ActiveRecord::Base.connection_pool.release_connection # current_user already loaded in before filter | |
response.headers["Content-Type"] = "text/event-stream" | |
response.stream.write "retry: 2000\n\n" # every 2 seconds | |
#http://ngauthier.com/2013/02/rails-4-sse-notify-listen.html | |
#http://stackoverflow.com/questions/16405520/postgres-listen-notify-rails | |
pool = ActiveRecord::Base.connection_pool | |
conn = pool.checkout | |
channels = [ 'chat', "user_#{current_user.id}" ] | |
channels += current_user.played_games.map{|g| "game_#{g.id}"} | |
channels.each do |channel| | |
conn.execute "LISTEN #{channel}" | |
end | |
loop do | |
response.stream.write "event: status\n" | |
response.stream.write "data: " + {threads: Thread.list.count, db_pool: pool.size, db_cons: pool.connections.size, t: Time.now.strftime("%H:%M:%S")}.to_json + "\n\n" | |
conn.raw_connection.wait_for_notify(2) do |event, pid, message| | |
hash = JSON.parse(message) | |
response.stream.write "event: #{hash['event']}\n" | |
response.stream.write "data: #{message}\n\n" | |
end | |
end | |
rescue IOError => e | |
Rails.logger.info "Got an exception " + e.inspect | |
ensure | |
Rails.logger.info "ensuring stuff..." | |
if conn | |
conn.execute "UNLISTEN *" # unlisten to all channels | |
pool.checkin conn | |
end | |
#needed? ActiveRecord::Base.clear_active_connections! | |
response.stream.close | |
Rails.logger.info "...finished ensuring stuff." | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment