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 # +notify_id+ the id of the most recent row in the log table, may be nil
54 # This accepts a websocket and a notify_id (this is the row id from Postgres LISTEN/NOTIFY, it may nil)
55 # It queries the database for log rows that are either
56 # a) greater than ws.last_log_id, which is the last log id which was a candidate to be sent out
57 # b) if ws.last_log_id is nil, then it queries rows starting with notify_id
59 # Regular Arvados permissions are applied using readable_by() and filters using record_filters()
60 # To avoid clogging up the database, queries are limited to batches of 100. It will schedule a new
61 # push_events call if there are more log rows to send.
62 def push_events ws, notify_id
64 if !notify_id.nil? and !ws.last_log_id.nil? and notify_id <= ws.last_log_id
65 # This notify is for a row we've handled already.
69 # Must have at least one filter set up to receive events
70 if ws.filters.length > 0
71 # Start with log rows readable by user, sorted in ascending order
72 logs = Log.readable_by(ws.user).order("id asc")
78 if !ws.last_log_id.nil?
79 # Client is only interested in log rows that are newer than the
80 # last log row seen by the client.
81 cond_id = "logs.id > ?"
82 param_out << ws.last_log_id
84 # No last log id, so look at rows starting with notify id
85 cond_id = "logs.id >= ?"
86 param_out << notify_id
88 # No log id to start from, nothing to do, return
92 # Now build filters provided by client
93 ws.filters.each do |filter|
94 ft = record_filters filter.filters, Log
96 # Join the clauses within a single subscription filter with AND
97 # so it is consistent with regular queries
98 cond_out << "(#{ft[:cond_out].join ') AND ('})"
99 param_out += ft[:param_out]
103 # Add filters to query
105 # Join subscriptions with OR
106 logs = logs.where(cond_id + " AND ((#{cond_out.join ') OR ('}))", *param_out)
108 logs = logs.where(cond_id, *param_out)
111 # Execute query and actually send the matching log rows
115 logs.limit(limit).each do |l|
116 ws.send(l.as_api_response.to_json)
117 ws.last_log_id = l.id
122 # Number of rows returned was capped by limit(), we need to schedule
123 # another query to get more logs (will start from last_log_id
124 # reported by current query)
126 elsif !notify_id.nil? and (ws.last_log_id.nil? or notify_id > ws.last_log_id)
127 # Number of rows returned was less than cap, but the notify id is
128 # higher than the last id visible to the client, so update last_log_id
129 ws.last_log_id = notify_id
131 elsif !notify_id.nil?
132 # No filters set up, so just record the sequence number
133 ws.last_log_id = notify_id
136 Rails.logger.warn "Error publishing event: #{$!}"
137 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
138 ws.send ({status: 500, message: 'error'}.to_json)
143 # Handle inbound subscribe or unsubscribe message.
144 def handle_message ws, event
146 # Parse event data as JSON
147 p = (Oj.load event.data).symbolize_keys
149 if p[:method] == 'subscribe'
150 # Handle subscribe event
153 # Set or reset the last_log_id. The event bus only reports events
154 # for rows that come after last_log_id.
155 ws.last_log_id = p[:last_log_id].to_i
158 if ws.filters.length < MAX_FILTERS
159 # Add a filter. This gets the :filters field which is the same
160 # format as used for regular index queries.
161 ws.filters << Filter.new(p)
162 ws.send ({status: 200, message: 'subscribe ok', filter: p}.to_json)
164 # Send any pending events
167 ws.send ({status: 403, message: "maximum of #{MAX_FILTERS} filters allowed per connection"}.to_json)
170 elsif p[:method] == 'unsubscribe'
171 # Handle unsubscribe event
173 len = ws.filters.length
174 ws.filters.select! { |f| not ((f.filters == p[:filters]) or (f.filters.empty? and p[:filters].nil?)) }
175 if ws.filters.length < len
176 ws.send ({status: 200, message: 'unsubscribe ok'}.to_json)
178 ws.send ({status: 404, message: 'filter not found'}.to_json)
182 ws.send ({status: 400, message: "missing or unrecognized method"}.to_json)
184 rescue Oj::Error => e
185 ws.send ({status: 400, message: "malformed request"}.to_json)
187 Rails.logger.warn "Error handling message: #{$!}"
188 Rails.logger.warn "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
189 ws.send ({status: 500, message: 'error'}.to_json)
194 # Constant maximum number of filters, to avoid silly huge database queries.
197 # Called by RackSocket when a new websocket connection has been established.
200 # Disconnect if no valid API token.
201 # current_user is included from CurrentApiClient
203 ws.send ({status: 401, message: "Valid API token required"}.to_json)
208 # Initialize our custom fields on the websocket connection object.
209 ws.user = current_user
213 # Subscribe to internal postgres notifications through @channel. This will
214 # call push_events when a notification comes through.
215 sub = @channel.subscribe do |msg|
219 # Set up callback for inbound message dispatch.
220 ws.on :message do |event|
221 handle_message ws, event
224 # Set up socket close callback
225 ws.on :close do |event|
226 @channel.unsubscribe sub
230 # Start up thread to monitor the Postgres database, if none exists already.
235 # from http://stackoverflow.com/questions/16405520/postgres-listen-notify-rails
236 ActiveRecord::Base.connection_pool.with_connection do |connection|
237 conn = connection.instance_variable_get(:@connection)
239 conn.async_exec "LISTEN logs"
241 # wait_for_notify will block until there is a change
242 # notification from Postgres about the logs table, then push
243 # the notification into the EventMachine channel. Each
244 # websocket connection subscribes to the other end of the
245 # channel and calls #push_events to actually dispatch the
246 # events to the client.
247 conn.wait_for_notify do |channel, pid, payload|
248 @channel.push payload.to_i
252 # Don't want the connection to still be listening once we return
253 # it to the pool - could result in weird behavior for the next
254 # thread to check it out.
255 conn.async_exec "UNLISTEN *"
263 # Since EventMachine is an asynchronous event based dispatcher, #on_connect
264 # does not block but instead returns immediately after having set up the
265 # websocket and notification channel callbacks.