Class: IbmAppconfigurationRubySdk::ConnectionManager

Inherits:
Object
  • Object
show all
Defined in:
lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(region:, guid:, apikey:, collection_id:, environment_id:, start_background_retry: false) ⇒ ConnectionManager

Returns a new instance of ConnectionManager.



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
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 38

def initialize(region:, guid:, apikey:, collection_id:, environment_id:, start_background_retry: false)
  @region = region
  @guid = guid
  @apikey = apikey
  @collection_id = collection_id
  @environment_id = environment_id
  @start_background_retry = start_background_retry

  @state = IbmAppconfigurationRubySdk::State::DISCONNECTED

  @state_mutex = Mutex.new

  @reconnect_attempts = 0

  @should_reconnect = true

  @socket = nil
  @driver = nil

  @reader_thread = nil
  @watchdog_thread = nil

  @last_heartbeat_at = Time.now

  # Initialize ConfigFetcher and BackgroundRetryManager
  @config_fetcher = nil
  @background_retry_manager = nil

  @logger = IbmAppconfigurationRubySdk::Logger.instance

  # Setup SDK components
  setup_sdk
end

Instance Attribute Details

#last_heartbeat_atObject (readonly)

Returns the value of attribute last_heartbeat_at.



36
37
38
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 36

def last_heartbeat_at
  @last_heartbeat_at
end

Instance Method Details

#cleanup_connectionObject


CLEANUP



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 375

def cleanup_connection
  @logger.log(Constants::WEBSOCKET_CLOSING_EXISTING) if @driver

  begin
    @driver&.close
  rescue StandardError => e
    @logger.log("cleanup driver: #{e.message}")
  end

  begin
    @socket&.close
  rescue StandardError => e
    @logger.log("cleanup socket: #{e.message}")
  end

  @reader_thread.kill if @reader_thread && @reader_thread != Thread.current

  begin
    @watchdog_thread&.kill
  rescue StandardError => e
    @logger.log("cleanup watchdog: #{e.message}")
  end

  @driver = nil
  @socket = nil

  @reader_thread = nil
  @watchdog_thread = nil
end

#connectObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 72

def connect
  @shutting_down = false

  transition_state(State::CONNECTING)

  # Get authentication token
  begin
    @logger.log(Constants::WEBSOCKET_INITIATING_CONNECTION)
    bearer_token = ApiManager.token

    if bearer_token.nil? || bearer_token.empty?
      @logger.error(Constants::WEBSOCKET_AUTH_TOKEN_FAILED)
      transition_state(State::RECONNECTING)
      schedule_reconnect
      return
    end

    @logger.log(Constants::WEBSOCKET_AUTH_TOKEN_SUCCESS)
  rescue StandardError => e
    @logger.error("Exception getting authentication token: #{e.class.name} - #{e.message}")
    transition_state(State::RECONNECTING)
    schedule_reconnect
    return
  end

  # Get WebSocket URL
  url = @url_builder.websocket_url

  if url.nil? || url.empty?
    @logger.error(Constants::WEBSOCKET_URL_FAILED)
    transition_state(State::RECONNECTING)
    schedule_reconnect
    return
  end

  uri = URI.parse(url)

  host = uri.host
  port = uri.port || (uri.scheme == "wss" ? 443 : 80)

  # Create TCP socket
  tcp_socket = TCPSocket.new(host, port)

  # Wrap with SSL only for wss://, use plain TCP for ws://
  if uri.scheme == "wss"
    ssl_context = OpenSSL::SSL::SSLContext.new
    ssl_context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)

    raw_socket = OpenSSL::SSL::SSLSocket.new(tcp_socket, ssl_context)
    raw_socket.sync_close = true
    raw_socket.hostname = host # Set SNI hostname for SSL handshake
    raw_socket.connect
  else
    raw_socket = tcp_socket
  end

  # Create driver socket with full URL
  socket = IbmAppconfigurationRubySdk::DriverSocket.new(raw_socket, url)

  @socket = raw_socket

  @driver = WebSocket::Driver.client(socket)

  # Set authentication headers
  @driver.set_header("Authorization", bearer_token)
  @driver.set_header("User-Agent", "appconfiguration-ruby-sdk/#{IbmAppconfigurationRubySdk::VERSION}")
  register_callbacks

  @driver.start

  @logger.log(Constants::WEBSOCKET_REQUEST_SENT)

  start_reader_thread

  # Start background retry if flag is set (fallback configurations were loaded)
  if @start_background_retry
    @background_retry_manager.start(
      reason: "Initial config API fetch failed - using fallback configuration"
    )
  end
  @start_background_retry = true
rescue StandardError => e
  @logger.error("Websocket Connection failed: #{e.class.name} - #{e.message}")

  transition_state(
    IbmAppconfigurationRubySdk::State::RECONNECTING
  )

  schedule_reconnect
end

#connected?Boolean

Returns:

  • (Boolean)


173
174
175
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 173

def connected?
  @state == IbmAppconfigurationRubySdk::State::CONNECTED
end

#disconnectObject



163
164
165
166
167
168
169
170
171
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 163

def disconnect
  @should_reconnect = false

  transition_state(IbmAppconfigurationRubySdk::State::CLOSING)

  cleanup_connection

  transition_state(IbmAppconfigurationRubySdk::State::CLOSED)
end

#handle_disconnect(reason) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 342

def handle_disconnect(reason)
  should_schedule = false

  @logger.error("#{Constants::WEBSOCKET_CONNECTION_LOST} (#{reason})")

  @state_mutex.synchronize do
    return if [
      IbmAppconfigurationRubySdk::State::RECONNECTING,
      IbmAppconfigurationRubySdk::State::CLOSING,
      IbmAppconfigurationRubySdk::State::CLOSED
    ].include?(@state)

    @logger.info("Handling websocket disconnect: #{reason}")

    transition_state(
      IbmAppconfigurationRubySdk::State::RECONNECTING
    )

    should_schedule =
      @should_reconnect
  end

  # Schedule reconnect FIRST
  schedule_reconnect if should_schedule

  # Then cleanup old connection
  cleanup_connection
end

#register_callbacksObject


INTERNAL CALLBACKS



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 181

def register_callbacks
  @driver.on(:open) do |event|
    @logger.info(Constants::WEBSOCKET_CONNECTED)

    # Check for HTTP status code during WebSocket handshake
    # The event object may contain status_code for HTTP errors
    if event.respond_to?(:status_code) && event.status_code
      status_code = event.status_code

      # Check for client-side errors (4xx except 429 Too Many Requests)
      if status_code >= 400 && status_code < 500 && status_code != 429
        @logger.error("WebSocket handshake failed with client error: #{status_code} - will not retry")
        @should_reconnect = false
        cleanup_connection
        transition_state(IbmAppconfigurationRubySdk::State::CLOSED)
        return
      end
    end

    @logger.log(Constants::WEBSOCKET_CONNECTION_RESET_WATCHDOG)

    transition_state(IbmAppconfigurationRubySdk::State::CONNECTED)

    @logger.info(Constants::WEBSOCKET_ESTABLISHED)

    @reconnect_attempts = 0

    @last_heartbeat_at = Time.now

    start_watchdog_thread

    # Incase of websocket retry we need to call /config again
    @start_background_retry = true
  end

  @driver.on(:message) do |event|
    @logger.log("Received: #{event.data}")

    if event.data == "test message"
      # Heartbeat message
      @last_heartbeat_at = Time.now
      @logger.log(Constants::WEBSOCKET_HEARTBEAT_UPDATED)
    else
      # Configuration update message
      @logger.info(Constants::WEBSOCKET_CONFIG_UPDATE_RECEIVED)

      # Stop any active background retry and restart from t=0
      if @background_retry_manager.active?
        @logger.log(Constants::WEBSOCKET_STOP_ACTIVE_BACKGROUND_RETRY)
        @background_retry_manager.stop
      end

      # Start background retry manager which will fetch immediately at t=0
      @background_retry_manager.start(
        reason: "Configuration update notification received"
      )
      @logger.log(Constants::WEBSOCKET_BACKGROUND_RETRY_STARTED)
    end
  end

  @driver.on(:close) do |event|
    @logger.log(Constants::WEBSOCKET_ON_CLOSE)

    if event.code == IbmAppconfigurationRubySdk::Constants::CUSTOM_SOCKET_CLOSE_REASON_CODE
      @logger.log("Websocket connection closed by the client. Reason: #{event.code} #{event.reason}")
    end

    @logger.info("Websocket Connection closed (code: #{event.code}, reason: #{event.reason})")

    # Check for WebSocket close codes that map to HTTP 4xx client errors
    # Close codes 4000-4499 (except 4429) indicate client-side errors
    if event.code && event.code >= 4000 && event.code < 4500 && event.code != 4429
      @logger.error("WebSocket closed with client error code: #{event.code} - will not retry")
      @should_reconnect = false
      cleanup_connection
      transition_state(IbmAppconfigurationRubySdk::State::CLOSED)
      return
    end

    @should_reconnect = true
    handle_disconnect("WebSocket close")
  end

  @driver.on(:error) do |event|
    @logger.log(Constants::WEBSOCKET_ON_ERROR)
    @logger.error("WebSocket error: #{event}")

    # Check if error contains a status code indicating client-side error
    if event.respond_to?(:status_code) && event.status_code
      status_code = event.status_code

      # Check for client-side errors (4xx except 429 Too Many Requests)
      if status_code >= 400 && status_code < 500 && status_code != 429
        @logger.error("WebSocket error with client error status: #{status_code} - will not retry")
        @should_reconnect = false
        cleanup_connection
        transition_state(IbmAppconfigurationRubySdk::State::CLOSED)
        return
      end
    end

    @should_reconnect = true

    handle_disconnect("WebSocket error")
  end
end

#schedule_reconnectObject


RECONNECT



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 409

def schedule_reconnect
  delay =
    IbmAppconfigurationRubySdk::RetryPolicy.next_delay(
      @reconnect_attempts
    )

  @logger.info("Websocket reconnect in #{delay.round(2)} sec")

  @reconnect_attempts += 1

  Thread.new do
    sleep(delay)

    connect if @should_reconnect
  end
end

#start_reader_threadObject



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 288

def start_reader_thread
  @reader_thread =
    Thread.new do
      loop do
        break if @socket.nil?

        data = @socket.readpartial(1024)
        @driver.parse(data)
      end
    rescue EOFError
      unless @shutting_down

        @logger.warning(Constants::WEBSOCKET_SERVER_DISCONNECTED)

        handle_disconnect("EOF")

      end
    rescue IOError => e
      if e.message.include?("stream closed")

        @logger.log(Constants::WEBSOCKET_READER_THREAD_STOPPED)

      else

        @logger.error("Reader IO error: #{e.message}")

        handle_disconnect(
          "Reader IO failure"
        )

      end
    rescue StandardError => e
      unless @shutting_down

        @logger.error("Reader error: #{e.class.name} - #{e.message}")

        handle_disconnect(
          "Reader failure"
        )

      end
    end
end

#start_watchdog_threadObject


WATCHDOG



336
337
338
339
340
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 336

def start_watchdog_thread
  watchdog = IbmAppconfigurationRubySdk::Watchdog.new(self)

  @watchdog_thread = watchdog.start
end

#transition_state(new_state) ⇒ Object


STATE



430
431
432
433
434
# File 'lib/ibm_appconfiguration_ruby_sdk/websocket/connection_manager.rb', line 430

def transition_state(new_state)
  @logger.log("#{@state} -> #{new_state}")

  @state = new_state
end