diff --git a/lib/flagsmith/sdk/realtime_client.rb b/lib/flagsmith/sdk/realtime_client.rb index 58bd717..2c5eace 100644 --- a/lib/flagsmith/sdk/realtime_client.rb +++ b/lib/flagsmith/sdk/realtime_client.rb @@ -20,8 +20,8 @@ def endpoint "#{@config.realtime_api_url}sse/environments/#{@main.environment.api_key}/stream" end - def listen(main, remaining_attempts: Float::INFINITY, retry_interval: 0.5) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength - last_updated_at = 0 + def listen(main, remaining_attempts: Float::INFINITY, retry_interval: 0.5) # rubocop:disable Metrics/MethodLength + @last_updated_at = 0 @main = main @running = true @thread = Thread.new do @@ -30,34 +30,48 @@ def listen(main, remaining_attempts: Float::INFINITY, retry_interval: 0.5) # rub @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.options.timeout = nil # Keep connection alive indefinitely - req.options.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 + stream_events rescue Faraday::ConnectionFailed, Faraday::TimeoutError => e @config.logger.warn "Connection failed: #{e.message}. Retrying in #{retry_interval} seconds..." rescue StandardError => e @config.logger.error "Error: #{e.message}. Retrying in #{retry_interval} seconds..." end end + ensure + @running = false end + end - @running = false + private + + # Open connection to SSE endpoint and handle the events as they arrive, + # rather than once the server closes the connection. + def stream_events + buffer = +'' + Faraday.new(url: endpoint).get do |req| + req.options.timeout = nil # Keep connection alive indefinitely + req.options.open_timeout = 10 + req.options.on_data = proc do |chunk, _received_bytes, _env| + buffer << chunk + process_line(buffer.slice!(/.*\n/)) while buffer.include?("\n") + end + end + end + + def process_line(line) + # SSE protocol: Skip non-event lines + return if line.strip.empty? || line.start_with?(':') + + # Parse SSE fields + return unless line.start_with?('data: ') + + data = JSON.parse(line[6..].strip) + updated_at = data['updated_at'] + return 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 end end diff --git a/spec/sdk/realtime_client_spec.rb b/spec/sdk/realtime_client_spec.rb index 4badf29..0dcaf1b 100644 --- a/spec/sdk/realtime_client_spec.rb +++ b/spec/sdk/realtime_client_spec.rb @@ -25,8 +25,29 @@ end let(:retry_interval) { 0.01 } + # Minimal stand-in for a Faraday connection that streams the response the + # way the real adapter does: chunks are handed to `on_data` while the request + # is still open, and the response is only returned once the server hangs up. + let(:stream_chunks) { [sse_response] } + let(:connection_count) { [0] } + let(:updates_seen_while_connected) { [] } + let(:update_count) { [0] } + let(:mock_connection) do + connection = double('Faraday::Connection') + allow(connection).to receive(:get) do |&block| + connection_count[0] += 1 + request = Faraday::Request.create(:get) { |req| req.options = Faraday::RequestOptions.new } + block&.call(request) + stream_chunks.each { |chunk| request.options.on_data&.call(chunk, chunk.bytesize, nil) } + updates_seen_while_connected << update_count[0] + double('Response', body: '') + end + connection + end + before(:each) do - allow(Faraday).to receive(:new).and_return(double('Faraday::Connection', get: double('Response', body: sse_response))) + allow(Faraday).to receive(:new).and_return(mock_connection) + allow(mock_main).to receive(:update_environment) { update_count[0] += 1 } allow(Thread).to receive(:new).and_yield end @@ -52,6 +73,39 @@ realtime_client.listen(mock_main, retry_interval: retry_interval, remaining_attempts: 3) end + context 'when the events arrive split across chunks' do + let(:stream_chunks) { ['data: {"updated', "_at\": 1}\n\ndata: {\"updated_at\": 2}\n", "\n"] } + + it 'reassembles the lines before parsing them' do + expect(mock_logger).not_to receive(:error) + realtime_client.listen(mock_main, retry_interval: retry_interval, remaining_attempts: 1) + expect(update_count[0]).to eq(2) + end + end + + context 'with a real background thread' do + before { allow(Thread).to receive(:new).and_call_original } + + def wait_for_listener + realtime_client.instance_variable_get(:@thread).join(5) + end + + it 'stays running and reconnects after the stream is closed' do + realtime_client.listen(mock_main, retry_interval: retry_interval, remaining_attempts: 3) + expect(realtime_client.running).to be(true) + + wait_for_listener + expect(connection_count[0]).to eq(3) + expect(realtime_client.running).to be(false) + end + + it 'updates the environment while the stream is still open' do + realtime_client.listen(mock_main, retry_interval: retry_interval, remaining_attempts: 1) + wait_for_listener + + expect(updates_seen_while_connected).to eq([2]) + end + end end end