-
Notifications
You must be signed in to change notification settings - Fork 6
feat: Enable realtime mode (SSE) #73
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require 'logger' | ||
| require 'faraday' | ||
| require 'json' | ||
|
|
||
| module Flagsmith | ||
| # Ruby client for realtime access to flagsmith.com | ||
| class RealtimeClient | ||
| attr_accessor :running | ||
|
|
||
| def initialize(config) | ||
| @config = config | ||
| @thread = nil | ||
| @running = false | ||
| @main = nil | ||
| end | ||
|
|
||
| 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 | ||
| @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.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 | ||
| 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 | ||
| end | ||
|
|
||
| @running = false | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| require 'spec_helper' | ||
| require 'faraday' | ||
|
|
||
| RSpec.describe Flagsmith::RealtimeClient do | ||
| let(:mock_logger) { double('Logger', warn: nil, info: nil, error: nil) } | ||
| let(:mock_config) do | ||
| double('Config', | ||
| realtime_api_url: 'https://example.com/', | ||
| environment_key: 'test-environment', | ||
| logger: mock_logger) | ||
| end | ||
| let(:mock_environment) { double('Environment', | ||
| api_key: 'some_api_key' )} | ||
| let(:mock_main) { double('Main', | ||
| update_environment: nil, | ||
| environment: mock_environment, | ||
| ) } | ||
| let(:realtime_client) { described_class.new(mock_config) } | ||
| let(:sse_response) do | ||
| <<~SSE | ||
| data: {"updated_at": 1} | ||
|
|
||
| data: {"updated_at": 2} | ||
| SSE | ||
| end | ||
| let(:retry_interval) { 0.01 } | ||
|
|
||
| before(:each) do | ||
| allow(Faraday).to receive(:new).and_return(double('Faraday::Connection', get: double('Response', body: sse_response))) | ||
| allow(Thread).to receive(:new).and_yield | ||
| end | ||
|
|
||
| describe '#listen' do | ||
| after { realtime_client.running = false } | ||
|
|
||
| it 'parses SSE data and calls update_environment when updated_at increases' do | ||
| expect(mock_main).to receive(:update_environment).twice | ||
| realtime_client.listen(mock_main, retry_interval: retry_interval, remaining_attempts: 3) | ||
| end | ||
|
|
||
| it 'logs retries and continues on connection failure' do | ||
| allow(Faraday).to receive(:new).and_raise(Faraday::ConnectionFailed.new('Connection failed')) | ||
|
|
||
| expect(mock_logger).to receive(:warn).with(/Connection failed/).at_least(:once) | ||
| realtime_client.listen(mock_main, retry_interval: retry_interval, remaining_attempts: 3) | ||
| end | ||
|
|
||
| it 'handles and logs unexpected errors gracefully' do | ||
| allow(Faraday).to receive(:new).and_raise(StandardError.new('Unexpected error')) | ||
|
|
||
| expect(mock_logger).to receive(:error).with(/Unexpected error/).at_least(:once) | ||
| realtime_client.listen(mock_main, retry_interval: retry_interval, remaining_attempts: 3) | ||
| end | ||
|
|
||
| end | ||
| end | ||
|
|
||
| RSpec.describe Flagsmith::Client do | ||
| describe '#initialize' do | ||
| before do | ||
| # Mock the methods to avoid initialization interferring. | ||
| allow_any_instance_of(Flagsmith::Client).to receive(:api_client) | ||
| allow_any_instance_of(Flagsmith::Client).to receive(:analytics_processor) | ||
| allow_any_instance_of(Flagsmith::Client).to receive(:environment_data_polling_manager) | ||
| allow_any_instance_of(Flagsmith::Client).to receive(:engine) | ||
| allow_any_instance_of(Flagsmith::Client).to receive(:load_offline_handler) | ||
| end | ||
|
|
||
| context 'when realtime_mode is true and local_evaluation is false' do | ||
| it 'raises a Flagsmith::ClientError' do | ||
| config = double( | ||
| 'Config', | ||
| realtime_mode?: true, | ||
| local_evaluation?: false, | ||
| offline_mode?: false, | ||
| offline_handler: nil, | ||
| ) | ||
| allow(Flagsmith::Config).to receive(:new).and_return(config) | ||
|
|
||
| expect { | ||
| Flagsmith::Client.new(config) | ||
| }.to raise_error(Flagsmith::ClientError, 'The enable_realtime_updates config param requires a matching enable_local_evaluation param.') | ||
| end | ||
| end | ||
|
|
||
| context 'when realtime_mode is false or local_evaluation is true' do | ||
| it 'does not raise an exception' do | ||
| config = double( | ||
| 'Config', | ||
| realtime_mode?: false, | ||
| local_evaluation?: true, | ||
| offline_mode?: false, | ||
| offline_handler: nil, | ||
| ) | ||
| allow(Flagsmith::Config).to receive(:new).and_return(config) | ||
|
|
||
| expect { | ||
| Flagsmith::Client.new(config) | ||
| }.not_to raise_error | ||
| end | ||
| end | ||
| end | ||
| end |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I can't quite understand the reasoning behind different logging levels for different errors here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The reason why we
warnfor a connection failed error is that it is expected behaviour. The SSE connection is, by design, going to fail after a poll of 30 seconds.