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")
65 # Client is only interested in log rows that are newer than the
66 # last log row seen by the client.
67 cond_id = "logs.id > ?"
68 param_out << ws.last_log_id
70 # No last log id, so only look at the most recently changed row
71 cond_id = "logs.id = ?"
77 # Now process filters provided by client
78 ws.filters.each do |filter|
79 ft = record_filters filter.filters, Log
81 # Join the clauses within a single subscription filter with AND
82 # so it is consistent with regular queries
83 cond_out << "(#{ft[:cond_out].join ') AND ('})"
84 param_out += ft[:param_out]
88 # Add filters to query
90 # Join subscriptions with OR
91 logs = logs.where(cond_id + " AND ((#{cond_out.join ') OR ('}))", *param_out)
93 logs = logs.where(cond_id, *param_out)
96 # Finally execute query and actually send the matching log rows
98 ws.send(l.as_api_response.to_json)
102 # No filters set up, so just record the sequence number
103 ws.last_log_id = id.to_i
105 rescue Exception => e
106 Rails.logger.warn "Error publishing event: #{$!}"
107 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
108 ws.send ({status: 500, message: 'error'}.to_json)
113 # Handle inbound subscribe or unsubscribe message.
114 def handle_message ws, event
116 # Parse event data as JSON
117 p = (Oj.load event.data).symbolize_keys
119 if p[:method] == 'subscribe'
120 # Handle subscribe event
123 # Set or reset the last_log_id. The event bus only reports events
124 # for rows that come after last_log_id.
125 ws.last_log_id = p[:last_log_id].to_i
128 if ws.filters.length < MAX_FILTERS
129 # Add a filter. This gets the :filters field which is the same
130 # format as used for regular index queries.
131 ws.filters << Filter.new(p)
132 ws.send ({status: 200, message: 'subscribe ok'}.to_json)
134 # Send any pending events
137 ws.send ({status: 403, message: "maximum of #{MAX_FILTERS} filters allowed per connection"}.to_json)
140 elsif p[:method] == 'unsubscribe'
141 # Handle unsubscribe event
143 len = ws.filters.length
144 ws.filters.select! { |f| not ((f.filters == p[:filters]) or (f.filters.empty? and p[:filters].nil?)) }
145 if ws.filters.length < len
146 ws.send ({status: 200, message: 'unsubscribe ok'}.to_json)
148 ws.send ({status: 404, message: 'filter not found'}.to_json)
152 ws.send ({status: 400, message: "missing or unrecognized method"}.to_json)
154 rescue Oj::Error => e
155 ws.send ({status: 400, message: "malformed request"}.to_json)
156 rescue Exception => e
157 Rails.logger.warn "Error handling message: #{$!}"
158 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
159 ws.send ({status: 500, message: 'error'}.to_json)
164 # Constant maximum number of filters, to avoid silly huge database queries.
167 # Called by RackSocket when a new websocket connection has been established.
170 # Disconnect if no valid API token.
171 # current_user is included from CurrentApiClient
173 ws.send ({status: 401, message: "Valid API token required"}.to_json)
178 # Initialize our custom fields on the websocket connection object.
179 ws.user = current_user
183 # Subscribe to internal postgres notifications through @channel. This will
184 # call push_events when a notification comes through.
185 sub = @channel.subscribe do |msg|
189 # Set up callback for inbound message dispatch.
190 ws.on :message do |event|
191 handle_message ws, event
194 # Set up socket close callback
195 ws.on :close do |event|
196 @channel.unsubscribe sub
200 # Start up thread to monitor the Postgres database, if none exists already.
205 # from http://stackoverflow.com/questions/16405520/postgres-listen-notify-rails
206 ActiveRecord::Base.connection_pool.with_connection do |connection|
207 conn = connection.instance_variable_get(:@connection)
209 conn.async_exec "LISTEN logs"
211 # wait_for_notify will block until there is a change
212 # notification from Postgres about the logs table, then push
213 # the notification into the EventMachine channel. Each
214 # websocket connection subscribes to the other end of the
215 # channel and calls #push_events to actually dispatch the
216 # events to the client.
217 conn.wait_for_notify do |channel, pid, payload|
218 @channel.push payload
222 # Don't want the connection to still be listening once we return
223 # it to the pool - could result in weird behavior for the next
224 # thread to check it out.
225 conn.async_exec "UNLISTEN *"
233 # Since EventMachine is an asynchronous event based dispatcher, #on_connect
234 # does not block but instead returns immediately after having set up the
235 # websocket and notification channel callbacks.