Repository navigation
feat: Support getExperimentFlag, trackEvent and trackExposure methods
#127
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
7 commits
Select commit
Hold shift + click to select a range
1bbde24
deps: update dependency flagsmith/sdk-spec to v0.7.1
renovate[bot] d507238
ci: Run the SDK spec for this SDK's capabilities
flagsmith-engineering[bot] 7489c5e
feat: Experiment flags, tracking events and exposure events
flagsmithsmith[bot] a59d16e
fix: Schedule at most one flush when the event buffer is full
flagsmithsmith[bot] 795dff1
fix: Release stopped event processors and keep identifiers out of logs
flagsmithsmith[bot] 1030339
fix: Reject enable_events in offline mode
flagsmithsmith[bot] 02a2389
refactor: Keep the scheduled flush out of EventProcessor#flush
flagsmithsmith[bot] 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
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,163 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require 'set' | ||
|
|
||
| module Flagsmith | ||
| # Started event processors, stopped together at exit. A stopped processor leaves, so it is not kept in memory. | ||
| module RunningEventProcessors | ||
| @processors = Set.new | ||
| @mutex = Mutex.new | ||
| at_exit { to_a.each(&:stop) } | ||
|
|
||
| def self.add(processor) | ||
| @mutex.synchronize { @processors.add(processor) } | ||
| end | ||
|
|
||
| def self.delete(processor) | ||
| @mutex.synchronize { @processors.delete(processor) } | ||
| end | ||
|
|
||
| def self.to_a | ||
| @mutex.synchronize { @processors.to_a } | ||
| end | ||
| end | ||
|
|
||
| # Buffers tracking and exposure events, and sends them to the Flagsmith events API in batches. | ||
| # | ||
| # Events are sent every +flush_interval_seconds+, as soon as +max_buffer_items+ are buffered, | ||
| # or on #flush. Sending events never raises into the application: failures are logged. | ||
| class EventProcessor # rubocop:disable Metrics/ClassLength | ||
| include Flagsmith::SDK::Intervals | ||
|
|
||
| FLAG_EXPOSURE_EVENT = '$flag_exposure' | ||
| ENDPOINT = 'v1/events' | ||
| FLUSH_INTERVAL_SECONDS = 10 | ||
| MAX_BUFFER_ITEMS = 1000 | ||
| REQUEST_TIMEOUT_SECONDS = 3 | ||
| RETRIABLE_STATUSES = [500, 502, 503, 504].freeze | ||
|
|
||
| def initialize(config, flush_interval_seconds: FLUSH_INTERVAL_SECONDS, max_buffer_items: MAX_BUFFER_ITEMS) | ||
| @logger = config.logger | ||
| @flush_interval_seconds = flush_interval_seconds | ||
| @max_buffer_items = max_buffer_items | ||
| @connection = build_connection(config) | ||
| @events = [] | ||
| @buffered_exposures = Set.new | ||
| @mutex = Mutex.new | ||
| @flush_mutex = Mutex.new | ||
| @flush_pending = false | ||
| end | ||
|
|
||
| def track_event(event, identifier: nil, value: nil, traits: nil, metadata: nil) | ||
| buffer(payload(event, nil, identifier: identifier, value: value, traits: traits, metadata: metadata)) | ||
| end | ||
|
|
||
| # Equal exposures within one flush interval add no information, so only the first is sent. | ||
| def track_exposure_event(feature_name, identifier:, value: nil, traits: nil, metadata: nil) | ||
| buffer(payload(FLAG_EXPOSURE_EVENT, feature_name, | ||
| identifier: identifier, value: value, traits: traits, metadata: metadata)) | ||
| end | ||
|
|
||
| def flush | ||
| drain | ||
| end | ||
|
|
||
| def start | ||
| return if @interval | ||
|
|
||
| @interval = set_interval(@flush_interval_seconds) { flush } | ||
| RunningEventProcessors.add(self) | ||
| end | ||
|
|
||
| def stop | ||
| @flush_mutex.synchronize { clear_interval(@interval) } if @interval # never interrupts a batch being sent | ||
| @interval = nil | ||
| RunningEventProcessors.delete(self) | ||
| flush | ||
| end | ||
|
|
||
| private | ||
|
|
||
| # Only the flush scheduled by a full buffer clears +@flush_pending+, once it holds the buffer, so at most one | ||
| # such flush is waiting at a time. | ||
| def scheduled_flush | ||
| drain { @flush_pending = false } | ||
| end | ||
|
|
||
| def drain | ||
| @flush_mutex.synchronize do | ||
| batch = @mutex.synchronize do | ||
| buffered = @events | ||
| @events = [] | ||
| @buffered_exposures.clear | ||
| yield if block_given? | ||
| buffered | ||
| end | ||
| send_events(batch) unless batch.empty? | ||
| end | ||
| end | ||
|
|
||
| def build_connection(config) | ||
| Faraday.new(url: config.events_api_url, headers: headers(config)) do |f| | ||
|
gagantrivedi marked this conversation as resolved.
Resolved
|
||
| f.options.timeout = REQUEST_TIMEOUT_SECONDS | ||
| f.response :raise_error | ||
| f.request :retry, max: 1, interval: 1, methods: %i[post], retry_statuses: RETRIABLE_STATUSES, | ||
| exceptions: [*Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS, Faraday::ConnectionFailed] | ||
| end | ||
| end | ||
|
|
||
| def headers(config) | ||
| config.custom_headers.merge( | ||
| 'Content-Type' => 'application/json; charset=utf-8', | ||
| 'X-Environment-Key' => config.environment_key, | ||
| 'User-Agent' => Flagsmith::SDK::Utils.user_agent, | ||
| 'Flagsmith-SDK-User-Agent' => Flagsmith::SDK::Utils.user_agent | ||
| ) | ||
| end | ||
|
|
||
| def payload(event, feature_name, details) | ||
| { | ||
| event: event, | ||
| feature_name: feature_name, | ||
| identifier: details[:identifier], | ||
| value: details[:value]&.to_s, | ||
| traits: trait_values(details[:traits]), | ||
| metadata: (details[:metadata] || {}).transform_keys(&:to_s).merge('sdk_version' => Flagsmith::VERSION), | ||
| timestamp: (Time.now.to_f * 1000).to_i | ||
| } | ||
| end | ||
|
|
||
| # Traits given as { value:, transient: } configurations are sent as their value. | ||
| def trait_values(traits) | ||
| return nil if traits.nil? || traits.empty? | ||
|
|
||
| traits.to_h { |key, value| [key.to_s, value.is_a?(Hash) ? value[:value] : value] } | ||
| end | ||
|
|
||
| def buffer(event) | ||
| schedule_flush = @mutex.synchronize do | ||
| next false if duplicate_exposure?(event) | ||
|
|
||
| @events << event | ||
| next false if @flush_pending || @events.length < @max_buffer_items | ||
|
|
||
| @flush_pending = true | ||
| end | ||
| Thread.new { scheduled_flush } if schedule_flush | ||
| end | ||
|
|
||
| def duplicate_exposure?(event) | ||
| return false unless event[:event] == FLAG_EXPOSURE_EVENT | ||
| return false if @buffered_exposures.add?(event.values_at(:feature_name, :identifier, :value)) | ||
|
|
||
| @logger.debug "Skipping duplicate #{FLAG_EXPOSURE_EVENT} event for feature #{event[:feature_name]}" | ||
| true | ||
| end | ||
|
|
||
| def send_events(events) | ||
| @connection.post(ENDPOINT, { events: events }.to_json) | ||
| rescue StandardError => e | ||
| @logger.warn "Unable to send #{events.length} events to the Flagsmith events API, dropping them: #{e}" | ||
| end | ||
| end | ||
| end | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.