Class: Jatai::Websocket::CableClient

Inherits:
Object
  • Object
show all
Defined in:
lib/jatai/websocket/cable_client.rb

Defined Under Namespace

Classes: ConnectionError

Constant Summary collapse

RECONNECT_DELAYS =
[ 1, 3, 10 ].freeze

Instance Method Summary collapse

Constructor Details

#initialize(api_url: nil, token: nil) ⇒ CableClient

Returns a new instance of CableClient.



11
12
13
14
15
16
17
# File 'lib/jatai/websocket/cable_client.rb', line 11

def initialize(api_url: nil, token: nil)
  @api_url = api_url || Jatai::Config.api_url
  @token = token || Jatai::Config.token
  @subscriptions = {}
  @connected = false
  @log_callback = nil
end

Instance Method Details

#connect!Object

Raises:



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/jatai/websocket/cable_client.rb', line 19

def connect!
  raise ConnectionError, "Token nao encontrado. Execute `jatai login`." unless @token

  ws_url = @api_url.sub(%r{^https?://}, "wss://").chomp("/") + "/cable"
  @ws = WebSocket::Client::Simple.connect(ws_url, headers: {
    "Authorization" => "Bearer #{@token}",
    "Origin" => @api_url
  })

  setup_handlers
  wait_for_welcome
  self
end

#disconnectObject



68
69
70
71
# File 'lib/jatai/websocket/cable_client.rb', line 68

def disconnect
  @ws&.close
  @connected = false
end

#on_log(&block) ⇒ Object



64
65
66
# File 'lib/jatai/websocket/cable_client.rb', line 64

def on_log(&block)
  @log_callback = block
end

#subscribe(channel, params = {}, &callback) ⇒ Object



33
34
35
36
37
38
# File 'lib/jatai/websocket/cable_client.rb', line 33

def subscribe(channel, params = {}, &callback)
  identifier = { channel: channel }.merge(params).to_json
  @subscriptions[identifier] = callback
  send_command("subscribe", identifier)
  identifier
end

#wait_for(channel, params: {}, until_status: [], timeout: 1800) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/jatai/websocket/cable_client.rb', line 40

def wait_for(channel, params: {}, until_status: [], timeout: 1800)
  result = nil
  identifier = subscribe(channel, params) do |msg|
    status = msg["status"]
    result = status if until_status.include?(status)
  end

  deadline = Time.now + timeout
  loop do
    return result if result
    raise ConnectionError, "Timeout aguardando status (#{timeout}s)" if Time.now > deadline

    unless @connected
      reconnect!
      # Re-subscribe after reconnect
      @subscriptions.each_key { |id| send_command("subscribe", id) }
    end

    sleep 0.2
  end
ensure
  send_command("unsubscribe", identifier) if identifier && @connected
end