Module: Cargosocket::Stream
- Defined in:
- lib/cargosocket/stream.rb
Constant Summary collapse
- WS_OPT_KEYS =
%w{host port debug secure secure_proxy tls_options close_timeout outbound_limit}.map(&:to_sym)
Class Method Summary collapse
- .call(cargoenv) ⇒ Object
- .config_socket(cargoenv, ws) ⇒ Object
- .periodic_ping(cargoenv, ws) ⇒ Object
- .setup_connection(cargoenv, ws, path, query) ⇒ Object
Class Method Details
.call(cargoenv) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/cargosocket/stream.rb', line 7 def self.call(cargoenv) raise "requires stream adapter" unless cargoenv[:adapter] EM.run do ws_config = WS_OPT_KEYS.reduce({}) do |acc, key| acc[key] = cargoenv[key] if cargoenv.has_key?(key) next acc end EM::WebSocket.run(ws_config){ |ws| config_socket(cargoenv, ws) } end end |
.config_socket(cargoenv, ws) ⇒ Object
19 20 21 22 23 24 25 |
# File 'lib/cargosocket/stream.rb', line 19 def self.config_socket(cargoenv, ws) ws.onopen do |w| path = w.path.sub(/^\//, '') periodic_ping(cargoenv, ws) EM.add_timer(0.5){ setup_connection(cargoenv, ws, path, w.query) } end end |
.periodic_ping(cargoenv, ws) ⇒ Object
27 28 29 |
# File 'lib/cargosocket/stream.rb', line 27 def self.periodic_ping(cargoenv, ws) EM.add_periodic_timer(cargoenv[:ping_timer] || 5){ ws.ping } end |
.setup_connection(cargoenv, ws, path, query) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/cargosocket/stream.rb', line 31 def self.setup_connection(cargoenv, ws, path, query) cb_adapter = StreamAdapters::CargobullAdapter channels = cb_adapter.channels(cargoenv, path, query) ref = cb_adapter.reference(cargoenv, path, query) if channels && ref state = cargoenv[:adapter].subscribe(*channels) do |channel, | cb_adapter.pop(cargoenv, path, ref, channel, , &ws.method(:send)) end state.keys.each do |channel| cb_adapter.subscribe(cargoenv, path, ref, channel) do |v| cargoenv[:adapter].push(channel, v) end end ws. do || state.keys.each do |channel| cb_adapter.push(cargoenv, path, ref, channel, .strip){ |v| cargoenv[:adapter].push(channel, v) } end end ws.onerror do |error| cargoenv[:adapter].unsubscribe(state) do |channel| cb_adapter.error(cargoenv, path, ref, channel) do |v| cargoenv[:adapter].push(channel, v) end end end ws.onclose do cargoenv[:adapter].unsubscribe(state) do |channel| cb_adapter.unsubscribe(cargoenv, path, ref, channel) do |v| cargoenv[:adapter].push(channel, v) end end end else ws.close(3001, channels.inspect || ref.to_s || "unknown") end end |