1 # If any threads raise an unhandled exception, make them all die.
2 # We trust a supervisor like runit to restart the server in this case.
3 Thread.abort_on_exception = true
7 require 'faye/websocket'
8 require 'record_filters'
12 # Patch in user, last_log_id and filters fields into the Faye::Websocket class.
16 attr_accessor :last_log_id
17 attr_accessor :filters
18 attr_accessor :sent_ids
22 # Store the filters supplied by the user that will be applied to the logs table
23 # to determine which events to return to the listener.
27 attr_accessor :filters
39 # Manages websocket connections, accepts subscription messages and publishes
42 include CurrentApiClient
45 # used in RecordFilters
50 # Initialize EventBus. Takes no parameters.
52 @channel = EventMachine::Channel.new
57 # Push out any pending events to the connection +ws+
58 # +notify_id+ the id of the most recent row in the log table, may be nil
60 # This accepts a websocket and a notify_id (this is the row id from Postgres
61 # LISTEN/NOTIFY, it may be nil if called from somewhere else)
63 # It queries the database for log rows that are either
64 # a) greater than ws.last_log_id, which is the last log id which was a candidate to be sent out
65 # b) if ws.last_log_id is nil, then it queries rows starting with notify_id
67 # Regular Arvados permissions are applied using readable_by() and filters using record_filters()
68 # To avoid clogging up the database, queries are limited to batches of 100. It will schedule a new
69 # push_events call if there are more log rows to send.
70 def push_events ws, notify_id
72 # Must have at least one filter set up to receive events
73 if ws.filters.length > 0
74 # Start with log rows readable by user, sorted in ascending order
75 logs = Log.readable_by(ws.user).order("id asc")
81 if !ws.last_log_id.nil?
82 # We are catching up from some starting point.
83 cond_id = "logs.id > ?"
84 param_out << ws.last_log_id
86 # Get new row being notified.
87 cond_id = "logs.id = ?"
88 param_out << notify_id
90 # No log id to start from, nothing to do, return
94 # Now build filters provided by client
95 ws.filters.each do |filter|
96 ft = record_filters filter.filters, Log
98 # Join the clauses within a single subscription filter with AND
99 # so it is consistent with regular queries
100 cond_out << "(#{ft[:cond_out].join ') AND ('})"
101 param_out += ft[:param_out]
105 # Add filters to query
107 # Join subscriptions with OR
108 logs = logs.where(cond_id + " AND ((#{cond_out.join ') OR ('}))", *param_out)
110 logs = logs.where(cond_id, *param_out)
113 # Execute query and actually send the matching log rows
118 logs.limit(limit).each do |l|
119 if ws.sent_ids.add?(l.id) != nil
120 ws.send(l.as_api_response.to_json)
127 # Number of rows returned was capped by limit(), we need to schedule
128 # another query to get more logs (will start from last_log_id
129 # reported by current query)
130 ws.last_log_id = lastid
131 EventMachine::next_tick do
132 push_events ws, notify_id
134 elsif !ws.last_log_id.nil?
138 elsif !notify_id.nil?
139 # No filters set up, so just record the sequence number
140 ws.last_log_id = notify_id
142 rescue ArgumentError => e
143 # There was some kind of user error.
144 Rails.logger.warn "Error publishing event: #{$!}"
145 ws.send ({status: 500, message: $!}.to_json)
148 Rails.logger.warn "Error publishing event: #{$!}"
149 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
150 ws.send ({status: 500, message: $!}.to_json)
152 # These exceptions typically indicate serious server trouble:
153 # out of memory issues, database connection problems, etc. Go ahead and
154 # crash; we expect that a supervisor service like runit will restart us.
159 # Handle inbound subscribe or unsubscribe message.
160 def handle_message ws, event
163 # Parse event data as JSON
164 p = (Oj.strict_load event.data).symbolize_keys
165 filter = Filter.new(p)
166 rescue Oj::Error => e
167 ws.send ({status: 400, message: "malformed request"}.to_json)
171 if p[:method] == 'subscribe'
172 # Handle subscribe event
175 # Set or reset the last_log_id. The event bus only reports events
176 # for rows that come after last_log_id.
177 ws.last_log_id = p[:last_log_id].to_i
180 if ws.filters.length < MAX_FILTERS
181 # Add a filter. This gets the :filters field which is the same
182 # format as used for regular index queries.
184 ws.send ({status: 200, message: 'subscribe ok', filter: p}.to_json)
186 # Send any pending events
189 ws.send ({status: 403, message: "maximum of #{MAX_FILTERS} filters allowed per connection"}.to_json)
192 elsif p[:method] == 'unsubscribe'
193 # Handle unsubscribe event
195 len = ws.filters.length
196 ws.filters.select! { |f| not ((f.filters == p[:filters]) or (f.filters.empty? and p[:filters].nil?)) }
197 if ws.filters.length < len
198 ws.send ({status: 200, message: 'unsubscribe ok'}.to_json)
200 ws.send ({status: 404, message: 'filter not found'}.to_json)
204 ws.send ({status: 400, message: "missing or unrecognized method"}.to_json)
207 Rails.logger.warn "Error handling message: #{$!}"
208 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
209 ws.send ({status: 500, message: 'error'}.to_json)
214 # Constant maximum number of filters, to avoid silly huge database queries.
217 # Called by RackSocket when a new websocket connection has been established.
220 # Disconnect if no valid API token.
221 # current_user is included from CurrentApiClient
223 ws.send ({status: 401, message: "Valid API token required"}.to_json)
228 # Initialize our custom fields on the websocket connection object.
229 ws.user = current_user
232 ws.sent_ids = Set.new
234 # Subscribe to internal postgres notifications through @channel. This will
235 # call push_events when a notification comes through.
236 sub = @channel.subscribe do |msg|
240 # Set up callback for inbound message dispatch.
241 ws.on :message do |event|
242 handle_message ws, event
245 # Set up socket close callback
246 ws.on :close do |event|
247 @channel.unsubscribe sub
251 # Start up thread to monitor the Postgres database, if none exists already.
256 # from http://stackoverflow.com/questions/16405520/postgres-listen-notify-rails
257 ActiveRecord::Base.connection_pool.with_connection do |connection|
258 conn = connection.instance_variable_get(:@connection)
260 conn.async_exec "LISTEN logs"
262 # wait_for_notify will block until there is a change
263 # notification from Postgres about the logs table, then push
264 # the notification into the EventMachine channel. Each
265 # websocket connection subscribes to the other end of the
266 # channel and calls #push_events to actually dispatch the
267 # events to the client.
268 conn.wait_for_notify do |channel, pid, payload|
269 @channel.push payload.to_i
273 # Don't want the connection to still be listening once we return
274 # it to the pool - could result in weird behavior for the next
275 # thread to check it out.
276 conn.async_exec "UNLISTEN *"
284 # Since EventMachine is an asynchronous event based dispatcher, #on_connect
285 # does not block but instead returns immediately after having set up the
286 # websocket and notification channel callbacks.