Class: OpenC3::WebSocketApi

Inherits:
Object show all
Defined in:
lib/openc3/script/web_socket_api.rb

Overview

Base class - Do not use directly

Direct Known Subclasses

CmdTlmWebSocketApi, ScriptWebSocketApi

Constant Summary collapse

USER_AGENT =
'OpenC3 / v7 (ruby/openc3/lib/io/web_socket_api)'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(url:, write_timeout: 10.0, read_timeout: 10.0, connect_timeout: 5.0, authentication: nil, scope: $openc3_scope, &block) ⇒ WebSocketApi

Create the WebsocketApi object. If a block is given will automatically connect/disconnect



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/openc3/script/web_socket_api.rb', line 24

def initialize(url:, write_timeout: 10.0, read_timeout: 10.0, connect_timeout: 5.0, authentication: nil, scope: $openc3_scope, &block)
  # $openc3_scope is only set inside the Script Runner / microservice
  # environment. Fall back to OPENC3_SCOPE (mirrors the Python client) so a
  # bare `ruby script.rb` doesn't send a nil scope that the server rejects.
  @scope = scope || ENV.fetch('OPENC3_SCOPE', 'DEFAULT')
  @authentication = authentication.nil? ? generate_auth() : authentication
  @url = url
  @write_timeout = write_timeout
  @read_timeout = read_timeout
  @connect_timeout = connect_timeout
  @subscribed = false
  if block_given?
    begin
      connect()
      yield self
    ensure
      disconnect()
    end
  end
end

Instance Method Details

#connectObject

Connect to the websocket with authorization in query params



171
172
173
174
175
176
177
178
179
180
# File 'lib/openc3/script/web_socket_api.rb', line 171

def connect
  disconnect()
  final_url = @url + "?scope=#{@scope}"
  @stream = WebSocketClientStream.new(final_url, @write_timeout, @read_timeout, @connect_timeout)
  @stream.headers = {
    'Sec-WebSocket-Protocol' => 'actioncable-v1-json, actioncable-unsupported',
    'User-Agent' => USER_AGENT
  }
  @stream.connect
end

#connected?Boolean

Are we connected?

Returns:

  • (Boolean)


183
184
185
186
187
188
189
# File 'lib/openc3/script/web_socket_api.rb', line 183

def connected?
  if @stream
    @stream.connected?
  else
    false
  end
end

#disconnectObject

Disconnect from the websocket and attempt to send unsubscribe message



192
193
194
195
196
197
198
199
200
201
# File 'lib/openc3/script/web_socket_api.rb', line 192

def disconnect
  if connected?()
    begin
      unsubscribe()
    rescue
      # Oh well, we tried
    end
    @stream.disconnect
  end
end

#generate_authObject

Generate the appropriate token for OpenC3



206
207
208
209
210
211
212
213
214
215
216
# File 'lib/openc3/script/web_socket_api.rb', line 206

def generate_auth
  if ENV['OPENC3_API_TOKEN'].nil? and ENV['OPENC3_API_USER'].nil?
    if ENV['OPENC3_API_PASSWORD']
      return OpenC3Authentication.new()
    else
      raise "Environment Variables Not Set for Authentication"
    end
  else
    return OpenC3KeycloakAuthentication.new(ENV['OPENC3_KEYCLOAK_URL'])
  end
end

#read(ignore_protocol_messages: true, timeout: nil) ⇒ Object

Read the next message with json parsing, filtering, and timeout support



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/openc3/script/web_socket_api.rb', line 52

def read(ignore_protocol_messages: true, timeout: nil)
  start_time = Time.now
  while true
    message = read_message()
    # Empty string is a normal end-of-stream signal when ActionCable / anycable-go
    # closes the WS. Treat it the same as nil so consumer `while (resp = api.read)`
    # loops exit cleanly instead of hitting JSON::ParserError on JSON.parse("").
    return nil if message.nil? || message.empty?

    begin
      json_hash = JSON.parse(message, allow_nan: true, create_additions: true)
    rescue JSON::ParserError
      # Defense-in-depth: treat malformed frames as end-of-stream rather than crashing.
      return nil
    end
    if ignore_protocol_messages
      type = json_hash['type']
      if type # ping, welcome, confirm_subscription, reject_subscription, disconnect
        if type == 'disconnect'
          if json_hash['reason'] == 'unauthorized'
            raise "Unauthorized"
          end
        end
        if type == 'reject_subscription'
          raise "Subscription Rejected"
        end
        if timeout
          end_time = Time.now
          if (end_time - start_time) > timeout
            raise Timeout::Error, "No Data Timeout"
          end
        end
        if defined? RunningScript and RunningScript.instance
          raise StopScript if RunningScript.instance.stop?
        end
        next
      end
    end
    return json_hash['message']
  end
end

#read_messageObject

Read the next message without filtering / parsing



46
47
48
49
# File 'lib/openc3/script/web_socket_api.rb', line 46

def read_message
  subscribe()
  return @stream.read
end

#subscribeObject

Will subscribe to the channel based on @identifier



95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/openc3/script/web_socket_api.rb', line 95

def subscribe
  unless @subscribed
    # Token is part of the identifier so it surfaces as params[:token] in
    # ApplicationCable::Channel#authenticate_subscription! — ActionCable
    # ignores `data` on `subscribe` commands.
    @identifier['token'] = @authentication.token(include_bearer: false)
    json_hash = {}
    json_hash['command'] = 'subscribe'
    json_hash['identifier'] = JSON.generate(@identifier, allow_nan: true)
    @stream.write(JSON.generate(json_hash, allow_nan: true))
    @subscribed = true
    wait_for_subscribed()
  end
end

#unsubscribeObject

Will unsubscribe to the channel based on @identifier



138
139
140
141
142
143
144
145
146
# File 'lib/openc3/script/web_socket_api.rb', line 138

def unsubscribe
  if @subscribed
    json_hash = {}
    json_hash['command'] = 'unsubscribe'
    json_hash['identifier'] = JSON.generate(@identifier, allow_nan: true)
    @stream.write(JSON.generate(json_hash, allow_nan: true))
    @subscribed = false
  end
end

#wait_for_subscribedObject

Block until the server confirms the subscription. ActionCable / anycable-go process 'subscribe' and 'message' commands as independent RPCs, so an action (add/remove) written immediately after subscribe can reach StreamingChannel#add before the subscription's broadcaster exists, where it is silently dropped (a no-op) and no data ever streams. Waiting for confirm_subscription guarantees the broadcaster is ready before any action is written.



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/openc3/script/web_socket_api.rb', line 117

def wait_for_subscribed
  while true
    message = @stream.read
    raise "WebSocket closed before subscription was confirmed" if message.nil? || message.empty?

    json_hash = JSON.parse(message, allow_nan: true, create_additions: true)
    case json_hash['type']
    when 'confirm_subscription'
      return
    when 'reject_subscription'
      raise "Subscription Rejected"
    when 'disconnect'
      raise "Unauthorized" if json_hash['reason'] == 'unauthorized'
    else
      # Ignore welcome / ping and keep waiting for confirmation
      next
    end
  end
end

#write(data) ⇒ Object

General write to the websocket



165
166
167
168
# File 'lib/openc3/script/web_socket_api.rb', line 165

def write(data)
  subscribe()
  @stream.write(data)
end

#write_action(data_hash) ⇒ Object

Send an ActionCable command



149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/openc3/script/web_socket_api.rb', line 149

def write_action(data_hash)
  # Subscribe first so the token is present in @identifier before we
  # serialize it below. ActionCable matches a 'message' command to its
  # subscription by the exact identifier string; if subscribe() injected the
  # token only afterward, the message identifier (no token) would not match
  # the subscription identifier (with token) and the server would silently
  # ignore the action.
  subscribe()
  json_hash = {}
  json_hash['command'] = 'message'
  json_hash['identifier'] = JSON.generate(@identifier, allow_nan: true)
  json_hash['data'] = JSON.generate(data_hash, allow_nan: true)
  write(JSON.generate(json_hash, allow_nan: true))
end