websocket_server.rb 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. class WebsocketServer
  2. cattr_reader :clients, :options
  3. def self.run(options)
  4. @options = options
  5. @clients = {}
  6. Rails.configuration.interface = 'websocket'
  7. EventMachine.run do
  8. EventMachine::WebSocket.start( host: @options[:b], port: @options[:p], secure: @options[:s], tls_options: @options[:tls_options] ) do |ws|
  9. # register client connection
  10. ws.onopen do |handshake|
  11. WebsocketServer.onopen(ws, handshake)
  12. end
  13. # unregister client connection
  14. ws.onclose do
  15. WebsocketServer.onclose(ws)
  16. end
  17. # manage messages
  18. ws.onmessage do |msg|
  19. WebsocketServer.onmessage(ws, msg)
  20. end
  21. end
  22. # check unused connections
  23. EventMachine.add_timer(0.5) do
  24. WebsocketServer.check_unused_connections
  25. end
  26. # check open unused connections, kick all connection without activity in the last 2 minutes
  27. EventMachine.add_periodic_timer(120) do
  28. WebsocketServer.check_unused_connections
  29. end
  30. EventMachine.add_periodic_timer(20) do
  31. WebsocketServer.log_status
  32. end
  33. EventMachine.add_periodic_timer(0.4) do
  34. WebsocketServer.send_to_client
  35. end
  36. end
  37. end
  38. def self.onopen(websocket, handshake)
  39. headers = handshake.headers
  40. client_id = websocket.object_id.to_s
  41. log 'notice', 'Client connected.', client_id
  42. Sessions.create( client_id, {}, { type: 'websocket' } )
  43. return if @clients.include? client_id
  44. @clients[client_id] = {
  45. websocket: websocket,
  46. last_ping: Time.now.utc.to_i,
  47. error_count: 0,
  48. headers: headers,
  49. }
  50. end
  51. def self.onclose(websocket)
  52. client_id = websocket.object_id.to_s
  53. log 'notice', 'Client disconnected.', client_id
  54. # removed from current client list
  55. if @clients.include? client_id
  56. @clients.delete client_id
  57. end
  58. Sessions.destroy(client_id)
  59. end
  60. def self.onmessage(websocket, msg)
  61. client_id = websocket.object_id.to_s
  62. log 'debug', "received: #{msg} ", client_id
  63. begin
  64. data = JSON.parse(msg)
  65. rescue => e
  66. log 'error', "can't parse message: #{msg}, #{e.inspect}", client_id
  67. return
  68. end
  69. # check if connection not already exists
  70. return if !@clients[client_id]
  71. Sessions.touch(client_id) # rubocop:disable Rails/SkipsModelValidations
  72. @clients[client_id][:last_ping] = Time.now.utc.to_i
  73. # spool messages for new connects
  74. if data['spool']
  75. Sessions.spool_create(data)
  76. end
  77. if data['event']
  78. log 'debug', "execute event '#{data['event']}'", client_id
  79. message = Sessions::Event.run(
  80. event: data['event'],
  81. payload: data,
  82. session: @clients[client_id][:session],
  83. headers: @clients[client_id][:headers],
  84. client_id: client_id,
  85. clients: @clients,
  86. options: @options,
  87. )
  88. if message
  89. websocket_send(client_id, message)
  90. end
  91. else
  92. log 'error', "unknown message '#{data.inspect}'", client_id
  93. end
  94. end
  95. def self.websocket_send(client_id, data)
  96. msg = if data.class != Array
  97. "[#{data.to_json}]"
  98. else
  99. data.to_json
  100. end
  101. log 'debug', "send #{msg}", client_id
  102. if !@clients[client_id]
  103. log 'error', "no such @clients for #{client_id}", client_id
  104. return
  105. end
  106. @clients[client_id][:websocket].send(msg)
  107. end
  108. def self.check_unused_connections
  109. log 'notice', 'check unused idle connections...'
  110. idle_time_in_sec = 4 * 60
  111. # close unused web socket sessions
  112. @clients.each do |client_id, client|
  113. next if ( client[:last_ping].to_i + idle_time_in_sec ) >= Time.now.utc.to_i
  114. log 'notice', 'closing idle websocket connection', client_id
  115. # remember to not use this connection anymore
  116. client[:disconnect] = true
  117. # try to close regular
  118. client[:websocket].close_websocket
  119. # delete session from client list
  120. sleep 0.3
  121. @clients.delete(client_id)
  122. end
  123. # close unused ajax long polling sessions
  124. clients = Sessions.destroy_idle_sessions(idle_time_in_sec)
  125. clients.each do |client_id|
  126. log 'notice', 'closing idle long polling connection', client_id
  127. end
  128. end
  129. def self.send_to_client
  130. return if @clients.size.zero?
  131. #log 'debug', 'checking for data to send...'
  132. @clients.each do |client_id, client|
  133. next if client[:disconnect]
  134. log 'debug', 'checking for data...', client_id
  135. begin
  136. queue = Sessions.queue(client_id)
  137. next if queue.blank?
  138. log 'notice', 'send data to client', client_id
  139. websocket_send(client_id, queue)
  140. rescue => e
  141. log 'error', 'problem:' + e.inspect, client_id
  142. # disconnect client
  143. client[:error_count] += 1
  144. if client[:error_count] > 20
  145. if @clients.include? client_id
  146. @clients.delete client_id
  147. end
  148. end
  149. end
  150. end
  151. end
  152. def self.log_status
  153. # websocket
  154. log 'notice', "Status: websocket clients: #{@clients.size}"
  155. @clients.each_key do |client_id|
  156. log 'notice', 'working...', client_id
  157. end
  158. # ajax
  159. client_list = Sessions.list
  160. clients = 0
  161. client_list.each_value do |client|
  162. next if client[:meta][:type] == 'websocket'
  163. clients = clients + 1
  164. end
  165. log 'notice', "Status: ajax clients: #{clients}"
  166. client_list.each do |client_id, client|
  167. next if client[:meta][:type] == 'websocket'
  168. log 'notice', 'working...', client_id
  169. end
  170. end
  171. def self.log(level, data, client_id = '-')
  172. if !@options[:v]
  173. return if level == 'debug'
  174. end
  175. puts "#{Time.now.utc.iso8601}:client(#{client_id}) #{data}" # rubocop:disable Rails/Output
  176. #puts "#{Time.now.utc.iso8601}:#{ level }:client(#{ client_id }) #{ data }"
  177. end
  178. end