+ ws.queue.clear
+ ws.queue << [:close, nil]
+ end
+
+ # Spin off a new thread to handle sending events to the client. We need a
+ # separate thread per connection so that a slow client doesn't interfere
+ # with other clients.
+ #
+ # We don't want the loop in the request thread because on a TERM signal,
+ # Puma waits for outstanding requests to complete, and long-lived websocket
+ # connections may not complete in a timely manner.
+ Thread.new do
+ # Loop and react to socket events.
+ loop do
+ eventType, msg = ws.queue.pop
+ if ws.queue.length > 1000
+ ws.send ({status: 500, message: 'Notify backlog too long'}.to_json)
+ ws.close
+ else
+ if eventType == :message
+ handle_message ws, msg
+ elsif eventType == :notify
+ push_events ws, msg
+ elsif eventType == :close
+ break
+ end
+ end
+ end