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'
13 # Patch in user, last_log_id and filters fields into the Faye::Websocket class.
17 attr_accessor :last_log_id
18 attr_accessor :filters
19 attr_accessor :sent_ids
21 attr_accessor :frame_mtx
29 alias_method :_write, :write
32 # Most of the sending activity will be from the thread set up in
33 # on_connect. However, there is also some automatic activity in the
34 # form of ping/pong messages, so ensure that the write method used to
35 # send one complete message to the underlying socket can only be
36 # called by one thread at a time.
37 self.frame_mtx.synchronize do
45 # Store the filters supplied by the user that will be applied to the logs table
46 # to determine which events to return to the listener.
50 attr_accessor :filters
62 # Manages websocket connections, accepts subscription messages and publishes
65 include CurrentApiClient
68 # used in RecordFilters
73 # Initialize EventBus. Takes no parameters.
75 @channel = EventMachine::Channel.new
81 def send_message(ws, obj)
82 ws.send(Oj.dump(obj, mode: :compat))
85 # Push out any pending events to the connection +ws+
86 # +notify_id+ the id of the most recent row in the log table, may be nil
88 # This accepts a websocket and a notify_id (this is the row id from Postgres
89 # LISTEN/NOTIFY, it may be nil if called from somewhere else)
91 # It queries the database for log rows that are either
92 # a) greater than ws.last_log_id, which is the last log id which was a candidate to be sent out
93 # b) if ws.last_log_id is nil, then it queries the row notify_id
95 # Regular Arvados permissions are applied using readable_by() and filters using record_filters().
96 def push_events ws, notify_id
98 # Must have at least one filter set up to receive events
99 if ws.filters.length > 0
100 # Start with log rows readable by user
101 logs = Log.readable_by(ws.user)
107 if not ws.last_log_id.nil?
108 # We are catching up from some starting point.
109 cond_id = "logs.id > ?"
110 param_out << ws.last_log_id
111 elsif not notify_id.nil?
112 # Get next row being notified.
113 cond_id = "logs.id = ?"
114 param_out << notify_id
116 # No log id to start from, nothing to do, return
120 # Now build filters provided by client
121 ws.filters.each do |filter|
122 ft = record_filters filter.filters, Log
123 if ft[:cond_out].any?
124 # Join the clauses within a single subscription filter with AND
125 # so it is consistent with regular queries
126 cond_out << "(#{ft[:cond_out].join ') AND ('})"
127 param_out += ft[:param_out]
131 # Add filters to query
133 # Join subscriptions with OR
134 logs = logs.where(cond_id + " AND ((#{cond_out.join ') OR ('}))", *param_out)
136 logs = logs.where(cond_id, *param_out)
139 # Execute query and actually send the matching log rows. Load
140 # the full log records only when we're ready to send them,
141 # though: otherwise, (1) postgres has to build the whole
142 # result set and return it to us before we can send the first
143 # event, and (2) we store lots of records in memory while
144 # waiting to spool them out to the client. Both of these are
145 # troublesome when log records are large (e.g., a collection
146 # update contains both old and new manifest_text).
148 # Note: find_each implies order('id asc'), which is what we
150 logs.select('logs.id').find_each do |l|
151 if not ws.sent_ids.include?(l.id)
152 # only send if not a duplicate
153 send_message(ws, Log.find(l.id).as_api_response)
155 if not ws.last_log_id.nil?
156 # record ids only when sending "catchup" messages, not notifies
162 rescue ArgumentError => e
163 # There was some kind of user error.
164 Rails.logger.warn "Error publishing event: #{$!}"
165 send_message(ws, {status: 500, message: $!})
168 Rails.logger.warn "Error publishing event: #{$!}"
169 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
170 send_message(ws, {status: 500, message: $!})
172 # These exceptions typically indicate serious server trouble:
173 # out of memory issues, database connection problems, etc. Go ahead and
174 # crash; we expect that a supervisor service like runit will restart us.
179 # Handle inbound subscribe or unsubscribe message.
180 def handle_message ws, event
183 # Parse event data as JSON
184 p = (Oj.strict_load event.data).symbolize_keys
185 filter = Filter.new(p)
186 rescue Oj::Error => e
187 send_message(ws, {status: 400, message: "malformed request"})
191 if p[:method] == 'subscribe'
192 # Handle subscribe event
195 # Set or reset the last_log_id. The event bus only reports events
196 # for rows that come after last_log_id.
197 ws.last_log_id = p[:last_log_id].to_i
198 # Reset sent_ids for consistency
199 # (always re-deliver all matching messages following last_log_id)
200 ws.sent_ids = Set.new
203 if ws.filters.length < Rails.configuration.websocket_max_filters
204 # Add a filter. This gets the :filters field which is the same
205 # format as used for regular index queries.
207 send_message(ws, {status: 200, message: 'subscribe ok', filter: p})
209 # Send any pending events
212 send_message(ws, {status: 403, message: "maximum of #{Rails.configuration.websocket_max_filters} filters allowed per connection"})
215 elsif p[:method] == 'unsubscribe'
216 # Handle unsubscribe event
218 len = ws.filters.length
219 ws.filters.select! { |f| not ((f.filters == p[:filters]) or (f.filters.empty? and p[:filters].nil?)) }
220 if ws.filters.length < len
221 send_message(ws, {status: 200, message: 'unsubscribe ok'})
223 send_message(ws, {status: 404, message: 'filter not found'})
227 send_message(ws, {status: 400, message: "missing or unrecognized method"})
230 Rails.logger.warn "Error handling message: #{$!}"
231 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
232 send_message(ws, {status: 500, message: 'error'})
239 @connection_count >= Rails.configuration.websocket_max_connections
243 # Called by RackSocket when a new websocket connection has been established.
245 # Disconnect if no valid API token.
246 # current_user is included from CurrentApiClient
248 send_message(ws, {status: 401, message: "Valid API token required"})
249 # Wait for the handshake to complete before closing the
250 # socket. Otherwise, nginx responds with HTTP 502 Bad gateway,
251 # and the client never sees our real error message.
252 ws.on :open do |event|
258 # Initialize our custom fields on the websocket connection object.
259 ws.user = current_user
262 ws.sent_ids = Set.new
264 ws.frame_mtx = Mutex.new
267 @connection_count += 1
270 # Subscribe to internal postgres notifications through @channel and
271 # forward them to the thread associated with the connection.
272 sub = @channel.subscribe do |msg|
273 if ws.queue.length > Rails.configuration.websocket_max_notify_backlog
274 send_message(ws, {status: 500, message: 'Notify backlog too long'})
276 @channel.unsubscribe sub
279 ws.queue << [:notify, msg]
283 # Set up callback for inbound message dispatch.
284 ws.on :message do |event|
285 ws.queue << [:message, event]
288 # Set up socket close callback
289 ws.on :close do |event|
290 @channel.unsubscribe sub
292 ws.queue << [:close, nil]
295 # Spin off a new thread to handle sending events to the client. We need a
296 # separate thread per connection so that a slow client doesn't interfere
297 # with other clients.
299 # We don't want the loop in the request thread because on a TERM signal,
300 # Puma waits for outstanding requests to complete, and long-lived websocket
301 # connections may not complete in a timely manner.
303 # Loop and react to socket events.
306 eventType, msg = ws.queue.pop
307 if eventType == :message
308 handle_message ws, msg
309 elsif eventType == :notify
311 elsif eventType == :close
317 @connection_count -= 1
319 ActiveRecord::Base.connection.close
323 # Start up thread to monitor the Postgres database, if none exists already.
328 # from http://stackoverflow.com/questions/16405520/postgres-listen-notify-rails
329 ActiveRecord::Base.connection_pool.with_connection do |connection|
330 conn = connection.instance_variable_get(:@connection)
332 conn.async_exec "LISTEN logs"
334 # wait_for_notify will block until there is a change
335 # notification from Postgres about the logs table, then push
336 # the notification into the EventMachine channel. Each
337 # websocket connection subscribes to the other end of the
338 # channel and calls #push_events to actually dispatch the
339 # events to the client.
340 conn.wait_for_notify do |channel, pid, payload|
341 @channel.push payload.to_i
345 # Don't want the connection to still be listening once we return
346 # it to the pool - could result in weird behavior for the next
347 # thread to check it out.
348 conn.async_exec "UNLISTEN *"