Class: ConnectionManager

Inherits:
Object
  • Object
show all
Defined in:
lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/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
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/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 = State::DISCONNECTED

  @state_mutex = Mutex.new

  @reconnect_attempts = 0

  @should_reconnect = true

  @socket = nil
  @driver = nil

  @reader_thread = nil
  @watchdog_thread = nil
  @connectivity_thread = nil

  @last_heartbeat_at = Time.now

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

  # 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/configurations/internal/websocket_client/connection_manager.rb', line 36

def last_heartbeat_at
  @last_heartbeat_at
end

Instance Method Details

#cleanup_connectionObject


CLEANUP




410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 410

def cleanup_connection
  begin
    @driver&.close
  rescue StandardError
  end

  begin
    @socket&.close
  rescue StandardError
  end

  # begin
  #   @reader_thread&.kill
  # rescue
  @reader_thread.kill if @reader_thread && @reader_thread != Thread.current

  begin
    @watchdog_thread&.kill
  rescue StandardError
  end

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

  @driver = nil
  @socket = nil

  @reader_thread = nil
  @watchdog_thread = nil
  @connectivity_thread = nil
end

#connectObject



71
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
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 71

def connect
  @shutting_down = false

  transition_state(State::CONNECTING)

  # Get authentication token
  begin
    puts "⏳ Requesting IAM token..."
    bearer_token = ApiManager.token

    if bearer_token.nil? || bearer_token.empty?
      puts "❌ Failed to get authentication token"
      transition_state(State::RECONNECTING)
      schedule_reconnect
      return
    end

    puts "✓ Got authentication token"
  rescue StandardError => e
    puts "❌ Exception getting authentication token: #{e.message}"
    puts "   Error details: #{e.class.name}"
    transition_state(State::RECONNECTING)
    schedule_reconnect
    return
  end

  # Get WebSocket URL
  url = @url_builder.websocket_url

  if url.nil? || url.empty?
    puts "❌ Failed to get WebSocket URL"
    transition_state(State::RECONNECTING)
    schedule_reconnect
    return
  end

  uri = URI.parse(url)

  host = uri.host
  port = uri.port || 443 # Default to 443 for wss://

  puts "Connecting to #{host}:#{port}"

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

  # Wrap with SSL for wss://
  ssl_context = OpenSSL::SSL::SSLContext.new
  ssl_context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)

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

  # Create driver socket with full URL
  socket = DriverSocket.new(ssl_socket, url)

  @socket = ssl_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}")
  puts "✓ Headers set with authentication"

  register_callbacks

  @driver.start

  start_reader_thread

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

  transition_state(
    State::RECONNECTING
  )

  schedule_reconnect
end

#connected?Boolean

Returns:

  • (Boolean)


172
173
174
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 172

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

#disconnectObject



162
163
164
165
166
167
168
169
170
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 162

def disconnect
  @should_reconnect = false

  transition_state(State::CLOSING)

  cleanup_connection

  transition_state(State::CLOSED)
end

#handle_disconnect(reason) ⇒ Object



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
404
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 379

def handle_disconnect(reason)
  should_schedule = false

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

    puts "Handling disconnect: #{reason}"

    transition_state(
      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




180
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
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 180

def register_callbacks
  @driver.on(:open) do |event|
    puts "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
        puts "❌ WebSocket handshake failed with client error: #{status_code}"
        puts "⛔ Client-side error detected - will not retry connection"
        @should_reconnect = false
        cleanup_connection
        transition_state(State::CLOSED)
        return
      end
    end

    transition_state(State::CONNECTED)

    @reconnect_attempts = 0

    @last_heartbeat_at = Time.now

    start_watchdog_thread
    start_connectivity_thread

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

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

    if event.data == "test message"
      # Heartbeat message
      @last_heartbeat_at = Time.now
      puts "Heartbeat updated"
    else
      # Configuration update message
      puts "📦 Configuration update received"

      # Stop any active background retry and restart from t=0
      if @background_retry_manager.active?
        puts "🛑 Stopping active background retry to restart from t=0"
        @background_retry_manager.stop
      end

      # Start background retry manager which will fetch immediately at t=0
      puts "🔄 Starting background retry for configuration update..."
      @background_retry_manager.start(
        reason: "Configuration update notification received"
      )
      puts "✓ Background retry started (will fetch immediately at t=0)"
    end
  end

  @driver.on(:close) do |event|
    puts "Connection closed"

    puts "Code: #{event.code}"
    puts "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
      puts "❌ WebSocket closed with client error code: #{event.code}"
      puts "⛔ Client-side error detected - will not retry connection"
      @should_reconnect = false
      cleanup_connection
      transition_state(State::CLOSED)
      return
    end

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

  @driver.on(:error) do |event|
    puts "WebSocket error"

    p 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
        puts "❌ WebSocket error with client error status: #{status_code}"
        puts "⛔ Client-side error detected - will not retry connection"
        @should_reconnect = false
        cleanup_connection
        transition_state(State::CLOSED)
        return
      end
    end

    @should_reconnect = true

    handle_disconnect("WebSocket error")
  end
end

#schedule_reconnectObject


RECONNECT




445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 445

def schedule_reconnect
  delay =
    RetryPolicy.next_delay(
      @reconnect_attempts
    )

  puts "Reconnect in #{delay.round(2)} sec"

  @reconnect_attempts += 1

  Thread.new do
    sleep(delay)

    connect if @should_reconnect
  end
end

#start_connectivity_threadObject


CONNECTIVITY




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
370
371
372
373
374
375
376
377
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 344

def start_connectivity_thread
  @connectivity_thread = Thread.new do
    is_connected = true

    loop do
      sleep(30)

      internet = Connectivity.check_internet

      if !internet

        puts "⚠️ No Internet Connection"

        is_connected = false

      else

        unless is_connected

          puts "✓ Internet connection restored"

          # Connection will be handled by reconnect logic
          handle_disconnect("Lost iinternet")

        end

        is_connected = true

      end
    end
  rescue StandardError => e
    puts "Connectivity thread error: #{e.message}"
  end
end

#start_reader_threadObject



286
287
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
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 286

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

        puts "Server disconnected"

        handle_disconnect("EOF")

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

        puts "Reader thread stopped"

      else

        puts "Reader IO error: #{e.message}"

        handle_disconnect(
          "Reader IO failure"
        )

      end
    rescue StandardError => e
      unless @shutting_down

        puts "Reader error: #{e.message}"

        handle_disconnect(
          "Reader failure"
        )

      end
    end
end

#start_watchdog_threadObject


WATCHDOG




334
335
336
337
338
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 334

def start_watchdog_thread
  watchdog = Watchdog.new(self)

  @watchdog_thread = watchdog.start
end

#transition_state(new_state) ⇒ Object


STATE




466
467
468
469
470
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/websocket_client/connection_manager.rb', line 466

def transition_state(new_state)
  puts "#{@state} -> #{new_state}"

  @state = new_state
end