3 require 'faye/websocket'
4 require 'record_filters'
7 # Patch in user, last_log_id and filters fields into the Faye::Websocket class.
11 attr_accessor :last_log_id
12 attr_accessor :filters
16 # Store the filters supplied by the user that will be applied to the logs table
17 # to determine which events to return to the listener.
21 attr_accessor :filters
33 # Manages websocket connections, accepts subscription messages and publishes
36 include CurrentApiClient
39 # used in RecordFilters
44 # Initialize EventBus. Takes no parameters.
46 @channel = EventMachine::Channel.new
51 # Push out any pending events to the connection +ws+
52 # +id+ the id of the most recent row in the log table, may be nil
53 def push_events ws, id = nil
55 # Must have at least one filter set up to receive events
56 if ws.filters.length > 0
57 # Start with log rows readable by user, sorted in ascending order
58 logs = Log.readable_by(ws.user).order("id asc")
61 # Client is only interested in log rows that are newer than the
62 # last log row seen by the client.
63 logs = logs.where("logs.id > ?", ws.last_log_id)
65 # No last log id, so only look at the most recently changed row
66 logs = logs.where("logs.id = ?", id.to_i)
71 # Now process filters provided by client
74 ws.filters.each do |filter|
75 ft = record_filters filter.filters, Log.table_name
76 cond_out += ft[:cond_out]
77 param_out += ft[:param_out]
80 # Add filters to query
82 logs = logs.where(cond_out.join(' OR '), *param_out)
85 # Finally execute query and actually send the matching log rows
87 ws.send(l.as_api_response.to_json)
91 # No filters set up, so just record the sequence number
92 ws.last_log_id = id.to_i
95 puts "Error publishing event: #{$!}"
96 puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
97 ws.send ({status: 500, message: 'error'}.to_json)
102 # Constant maximum number of filters, to avoid silly huge database queries.
105 # Called by RackSocket when a new websocket connection has been established.
108 # Disconnect if no valid API token.
109 # current_user is included from CurrentApiClient
111 ws.send ({status: 401, message: "Valid API token required"}.to_json)
116 # Initialize our custom fields on the websocket connection object.
117 ws.user = current_user
121 # Subscribe to internal postgres notifications through @channel. This will
122 # call push_events when a notification comes through.
123 sub = @channel.subscribe do |msg|
127 # Set up callback for inbound message dispatch.
128 ws.on :message do |event|
130 # Parse event data as JSON
131 p = (Oj.load event.data).symbolize_keys
133 if p[:method] == 'subscribe'
134 # Handle subscribe event
137 # Set or reset the last_log_id. The event bus only reports events
138 # for rows that come after last_log_id.
139 ws.last_log_id = p[:last_log_id].to_i
142 if ws.filters.length < MAX_FILTERS
143 # Add a filter. This gets the :filters field which is the same
144 # format as used for regular index queries.
145 ws.filters << Filter.new(p)
146 ws.send ({status: 200, message: 'subscribe ok'}.to_json)
148 # Send any pending events
151 ws.send ({status: 403, message: "maximum of #{MAX_FILTERS} filters allowed per connection"}.to_json)
154 elsif p[:method] == 'unsubscribe'
155 # Handle unsubscribe event
157 len = ws.filters.length
158 ws.filters.select! { |f| not ((f.filters == p[:filters]) or (f.filters.empty? and p[:filters].nil?)) }
159 if ws.filters.length < len
160 ws.send ({status: 200, message: 'unsubscribe ok'}.to_json)
162 ws.send ({status: 404, message: 'filter not found'}.to_json)
166 ws.send ({status: 400, message: "missing or unrecognized method"}.to_json)
168 rescue Oj::Error => e
169 ws.send ({status: 400, message: "malformed request"}.to_json)
170 rescue Exception => e
171 puts "Error handling message: #{$!}"
172 puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
173 ws.send ({status: 500, message: 'error'}.to_json)
178 # Set up socket close callback
179 ws.on :close do |event|
180 @channel.unsubscribe sub
184 # Start up thread to monitor the Postgres database, if none exists already.
189 # from http://stackoverflow.com/questions/16405520/postgres-listen-notify-rails
190 ActiveRecord::Base.connection_pool.with_connection do |connection|
191 conn = connection.instance_variable_get(:@connection)
193 conn.async_exec "LISTEN logs"
195 # wait_for_notify will block until there is a change
196 # notification from Postgres about the logs table, then push
197 # the notification into the EventMachine channel. Each
198 # websocket connection subscribes to the other end of the
199 # channel and calls #push_events to actually dispatch the
200 # events to the client.
201 conn.wait_for_notify do |channel, pid, payload|
202 @channel.push payload
206 # Don't want the connection to still be listening once we return
207 # it to the pool - could result in weird behavior for the next
208 # thread to check it out.
209 conn.async_exec "UNLISTEN *"
216 # Since EventMachine is an asynchronous event based dispatcher, #on_connect
217 # does not block but instead returns immediately after having set up the
218 # websocket and notification channel callbacks.