Class: Flagsmith::RealtimeClient
- Inherits:
-
Object
- Object
- Flagsmith::RealtimeClient
- Defined in:
- lib/flagsmith/sdk/realtime_client.rb
Overview
Ruby client for realtime access to flagsmith.com
Instance Attribute Summary collapse
-
#running ⇒ Object
Returns the value of attribute running.
Instance Method Summary collapse
- #endpoint ⇒ Object
-
#initialize(config) ⇒ RealtimeClient
constructor
A new instance of RealtimeClient.
-
#listen(main, remaining_attempts: Float::INFINITY, retry_interval: 0.5) ⇒ Object
rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength.
Constructor Details
#initialize(config) ⇒ RealtimeClient
Returns a new instance of RealtimeClient.
12 13 14 15 16 17 |
# File 'lib/flagsmith/sdk/realtime_client.rb', line 12 def initialize(config) @config = config @thread = nil @running = false @main = nil end |
Instance Attribute Details
#running ⇒ Object
Returns the value of attribute running.
10 11 12 |
# File 'lib/flagsmith/sdk/realtime_client.rb', line 10 def running @running end |
Instance Method Details
#endpoint ⇒ Object
19 20 21 |
# File 'lib/flagsmith/sdk/realtime_client.rb', line 19 def endpoint "#{@config.realtime_api_url}sse/environments/#{@main.environment.api_key}/stream" end |
#listen(main, remaining_attempts: Float::INFINITY, retry_interval: 0.5) ⇒ Object
rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength
23 24 25 26 27 28 29 30 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 |
# File 'lib/flagsmith/sdk/realtime_client.rb', line 23 def listen(main, remaining_attempts: Float::INFINITY, retry_interval: 0.5) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength last_updated_at = 0 @main = main @running = true @thread = Thread.new do while @running && remaining_attempts.positive? remaining_attempts -= 1 @config.logger.warn 'Beginning to pull down realtime endpoint' begin sleep retry_interval # Open connection to SSE endpoint Faraday.new(url: endpoint).get do |req| req..timeout = nil # Keep connection alive indefinitely req..open_timeout = 10 end.body.each_line do |line| # rubocop:disable Style/MultilineBlockChain # SSE protocol: Skip non-event lines next if line.strip.empty? || line.start_with?(':') # Parse SSE fields next unless line.start_with?('data: ') data = JSON.parse(line[6..].strip) updated_at = data['updated_at'] next unless updated_at > last_updated_at @config.logger.info "Realtime updating environment from #{last_updated_at} to #{updated_at}" @main.update_environment last_updated_at = updated_at end rescue Faraday::ConnectionFailed, Faraday::TimeoutError => e @config.logger.warn "Connection failed: #{e.}. Retrying in #{retry_interval} seconds..." rescue StandardError => e @config.logger.error "Error: #{e.}. Retrying in #{retry_interval} seconds..." end end end @running = false end |