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 # Handle inbound subscribe or unsubscribe message.
103 def handle_message ws, event
105 # Parse event data as JSON
106 p = (Oj.load event.data).symbolize_keys
108 if p[:method] == 'subscribe'
109 # Handle subscribe event
112 # Set or reset the last_log_id. The event bus only reports events
113 # for rows that come after last_log_id.
114 ws.last_log_id = p[:last_log_id].to_i
117 if ws.filters.length < MAX_FILTERS
118 # Add a filter. This gets the :filters field which is the same
119 # format as used for regular index queries.
120 ws.filters << Filter.new(p)
121 ws.send ({status: 200, message: 'subscribe ok'}.to_json)
123 # Send any pending events
126 ws.send ({status: 403, message: "maximum of #{MAX_FILTERS} filters allowed per connection"}.to_json)
129 elsif p[:method] == 'unsubscribe'
130 # Handle unsubscribe event
132 len = ws.filters.length
133 ws.filters.select! { |f| not ((f.filters == p[:filters]) or (f.filters.empty? and p[:filters].nil?)) }
134 if ws.filters.length < len
135 ws.send ({status: 200, message: 'unsubscribe ok'}.to_json)
137 ws.send ({status: 404, message: 'filter not found'}.to_json)
141 ws.send ({status: 400, message: "missing or unrecognized method"}.to_json)
143 rescue Oj::Error => e
144 ws.send ({status: 400, message: "malformed request"}.to_json)
145 rescue Exception => e
146 puts "Error handling message: #{$!}"
147 puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
148 ws.send ({status: 500, message: 'error'}.to_json)
153 # Constant maximum number of filters, to avoid silly huge database queries.
156 # Called by RackSocket when a new websocket connection has been established.
159 # Disconnect if no valid API token.
160 # current_user is included from CurrentApiClient
162 ws.send ({status: 401, message: "Valid API token required"}.to_json)
167 # Initialize our custom fields on the websocket connection object.
168 ws.user = current_user
172 # Subscribe to internal postgres notifications through @channel. This will
173 # call push_events when a notification comes through.
174 sub = @channel.subscribe do |msg|
178 # Set up callback for inbound message dispatch.
179 ws.on :message do |event|
180 handle_message ws, event
183 # Set up socket close callback
184 ws.on :close do |event|
185 @channel.unsubscribe sub
189 # Start up thread to monitor the Postgres database, if none exists already.
194 # from http://stackoverflow.com/questions/16405520/postgres-listen-notify-rails
195 ActiveRecord::Base.connection_pool.with_connection do |connection|
196 conn = connection.instance_variable_get(:@connection)
198 conn.async_exec "LISTEN logs"
200 # wait_for_notify will block until there is a change
201 # notification from Postgres about the logs table, then push
202 # the notification into the EventMachine channel. Each
203 # websocket connection subscribes to the other end of the
204 # channel and calls #push_events to actually dispatch the
205 # events to the client.
206 conn.wait_for_notify do |channel, pid, payload|
207 @channel.push payload
211 # Don't want the connection to still be listening once we return
212 # it to the pool - could result in weird behavior for the next
213 # thread to check it out.
214 conn.async_exec "UNLISTEN *"
222 # Since EventMachine is an asynchronous event based dispatcher, #on_connect
223 # does not block but instead returns immediately after having set up the
224 # websocket and notification channel callbacks.