Skip to content
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

Multiple Client Instances & Orphaned Threads #143

Closed
tonyta opened this issue Oct 25, 2019 · 6 comments
Closed

Multiple Client Instances & Orphaned Threads #143

tonyta opened this issue Oct 25, 2019 · 6 comments

Comments

@tonyta
Copy link
Contributor

tonyta commented Oct 25, 2019

We ran into this issue where instantiating a client can lead to an orphaned thread (and possibly multiple persistent connection to the LD server). We've found a workaround for our implementation, but it seems like unintended behavior. Hope this helps!

Describe the bug

LaunchDarkly::Client seems to leave orphaned threads if client instances are garbage collected before closing.

We originally encountered this in Rails, when autoloading reloading made us lose the reference to our original client and we instantiated another one. We noticed that there were multiple connections to LaunchDarkly involving multiple threads. These threads and connections remain until the ruby process is closed.

To reproduce

Here is a contrived reproduction script:

require "ldclient-rb"

puts "Ruby Version: #{RUBY_VERSION}"
puts "LaunchDarkly Version: #{LaunchDarkly::VERSION}"

puts
puts "Creating 10 clients..."
clients = Array.new(10) { LaunchDarkly::LDClient.new("") }
puts "clients: #{ObjectSpace.each_object(LaunchDarkly::LDClient).count}"
puts "threads: #{Thread.list.count}"

puts
puts "Closing every other client..."
clients.each_with_index { |c, i| c.close if i.even? }
puts "clients: #{ObjectSpace.each_object(LaunchDarkly::LDClient).count}"
puts "threads: #{Thread.list.count}"

puts
puts "Clearing client references and garbage collecting..."
clients.clear
GC.start
sleep 1
puts "clients: #{ObjectSpace.each_object(LaunchDarkly::LDClient).count}"
puts "threads: #{Thread.list.count}"

puts
puts "Remaining threads..."
puts Thread.list

The above script initializes 10 clients. The threads created by the closed clients are eventually terminated. The threads created by the other clients remain indefinitely even after those clients are garbage collected.

Note: I'm aware that I'm initializing with an invalid SDK key, but this didn't seem to have an effect on the outcome.

Ruby Version: 2.5.5
LaunchDarkly Version: 5.6.0

Creating clients...
E, [2019-10-24T15:48:44.765951 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:44.766084 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:45.105761 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:45.105904 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:45.399326 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:45.399652 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:45.729868 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:45.730277 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:46.132979 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:46.133164 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:46.436607 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:46.436749 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:46.727070 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:46.727248 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:47.055064 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:47.055177 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:47.464489 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:47.464632 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
E, [2019-10-24T15:48:47.774941 #41465] ERROR -- : [LDClient] HTTP error 401 (invalid SDK key) for streaming connection - giving up permanently
E, [2019-10-24T15:48:47.775231 #41465] ERROR -- : [LDClient] LaunchDarkly client initialization failed
clients: 10
threads: 12

Closing every other client...
clients: 10
threads: 7

Clearing client references and garbage collecting...
clients: 0
threads: 7

Remaining threads...
#<Thread:0x00007fdae4065c40 run>
#<Thread:0x00007fdae392a1b0@/Users/tonyta/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/concurrent-ruby-1.1.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:317 sleep>
#<Thread:0x00007fdae40fb880@/Users/tonyta/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/launchdarkly-server-sdk-5.6.0/lib/ldclient-rb/events.rb:172 sleep_forever>
#<Thread:0x00007fdae3601060@/Users/tonyta/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/launchdarkly-server-sdk-5.6.0/lib/ldclient-rb/events.rb:172 sleep_forever>
#<Thread:0x00007fdae35d3408@/Users/tonyta/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/launchdarkly-server-sdk-5.6.0/lib/ldclient-rb/events.rb:172 sleep_forever>
#<Thread:0x00007fdae358ad98@/Users/tonyta/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/launchdarkly-server-sdk-5.6.0/lib/ldclient-rb/events.rb:172 sleep_forever>
#<Thread:0x00007fdae3550030@/Users/tonyta/.rbenv/versions/2.5.5/lib/ruby/gems/2.5.0/gems/launchdarkly-server-sdk-5.6.0/lib/ldclient-rb/events.rb:172 sleep_forever>

Expected behavior
If the expected use is to have a single client instance, this gem take a more control of its client initialization (a la newrelic_rpm), with stricter control over its threads.

Otherwise, if multiple clients are expected, it'd be nice to keep track and terminate orphaned threads. I'm not sure if multiple connections to the LaunchDarkly server is created, but is so, those should be closed too.

Logs
none

SDK version
LaunchDarkly Version: 5.6.0

Language version, developer tools
Ruby Version: 2.5.5

OS/platform
Platform: x86_64-darwin18

Additional context
none

@eli-darkly
Copy link
Contributor

I'm not very familiar with Rails autoloading behavior— are you saying it's not possible for you to explicitly close a client that you know you're not going to be able to hold on to?

Off the top of my head, one way we might deal with this would be to define a finalizer for the client object which would ensure that the close logic runs if it's garbage-collected.

@tonyta
Copy link
Contributor Author

tonyta commented Oct 25, 2019

I misspoke... I meant Rails reloading not autoloading (corrected above). In development mode, Rails can reload classes that have changed.

We figured out a different implementation to avoid this issue, but the original problem came about when we refined an autoloadable/reloadable class like the following:

class Feature
  class << self
    def ld_client
      @ld_client ||= LaunchDarkly::LDClient.new(ENV["LD_SDK_KEY"])
    end
  end
end

When Rails reloads the Feature class, Ruby garbage-collects the original Feature class and defines a new one with a new instance variable @ld_client. This means the original client also gets garbage collected and its thread is orphaned and sleeps forever and a new client is lazily created. This means two threads and potentially two connections to LD.

Even though we've figured a better implementation for this, this could potentially be a gotcha for other users of this gem. You do have good documentation about this in your Ruby SDK Reference:

LDClient must be a singleton

It's important to make this a singleton-- internally, the client instance maintains internal state that allows us to serve feature flags without making any remote requests. Be sure that you're not instantiating a new client with every request.

But it might be helpful if the LD gem manages the client singleton internally to avoid improper implementation.

@eli-darkly
Copy link
Contributor

Unfortunately, I don't think the idea of having the LD gem manage a singleton client will work. There are sometimes cases where you really do want to have two clients (e.g. if you are using feature flags from multiple environments) so the server-side SDKs always allow you to create multiple instances; we just don't want people to create them unnecessarily every single time there is a new web request. We've found that the only way to reliably discourage that mistake is to make a very strong statement about how you should use a singleton instance. So really "must" in that case means "must (in almost all use cases)".

@eli-darkly
Copy link
Contributor

Something I'm unclear on in your example: what does Feature represent? There isn't more than one of them, is there?

@louis-launchdarkly
Copy link
Contributor

Given there is no comment from the requester in the past two years, closing this ticket. If you need instructions on how to close the client when a worker terminates, please refer to #144.

LaunchDarklyReleaseBot added a commit that referenced this issue Mar 18, 2022
* fix doc comments

* add YARD config so our docs show up correctly everywhere

* don't need markup-provider option

* rm obsolete proxy param

* remove net-http-persistent

* fix concurrent-ruby usage that breaks on Windows

* add pipeline and clean up with with rm_rf instead of rm

* fix highlight blocks

* Hr/azure3 (#103)

* Add Consul and Redis services to Windows.
* Enable Consul and Redis testing

* add dynamo (#104)

* add experimentation event overrides for rules and fallthrough

* warn & don't send event if identify or track has no valid user

* include user in prereq flag events

* rm unnecessary logic

* more factory methods

* update readme to refer to docs

* add Ruby 2.6.2 to CI

* fix missing require for net/http

* stringify built-in user attributes in events, and secondary key for evals

* make const names consistent

* support metric value with track()

* update method description

* applying markdown templates and updating repository url references

* Cleaning up markdown files

* allow skipping database tests

* Updating the package name (#115)

* update package name

* missed one

* revert module entry point name change

* bump ld-eventsource version for stream logging fix

* use YAML.safe_load

* add unit test and temporarily revert fix to demonstrate failure

* restore fix

* add comment about not using FileDataSource in production

* drop events if inbox is full

* update doc comment for track with metric_value

* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Harpo roeder <hroeder@launchdarkly.com>
Co-authored-by: hroederld <46500128+hroederld@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Jun 15, 2022
* rm obsolete proxy param

* remove net-http-persistent

* fix concurrent-ruby usage that breaks on Windows

* add pipeline and clean up with with rm_rf instead of rm

* fix highlight blocks

* Hr/azure3 (#103)

* Add Consul and Redis services to Windows.
* Enable Consul and Redis testing

* add dynamo (#104)

* add experimentation event overrides for rules and fallthrough

* warn & don't send event if identify or track has no valid user

* include user in prereq flag events

* rm unnecessary logic

* more factory methods

* update readme to refer to docs

* add Ruby 2.6.2 to CI

* fix missing require for net/http

* stringify built-in user attributes in events, and secondary key for evals

* make const names consistent

* support metric value with track()

* update method description

* applying markdown templates and updating repository url references

* Cleaning up markdown files

* allow skipping database tests

* Updating the package name (#115)

* update package name

* missed one

* revert module entry point name change

* bump ld-eventsource version for stream logging fix

* use YAML.safe_load

* add unit test and temporarily revert fix to demonstrate failure

* restore fix

* add comment about not using FileDataSource in production

* drop events if inbox is full

* update doc comment for track with metric_value

* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Harpo roeder <hroeder@launchdarkly.com>
Co-authored-by: hroederld <46500128+hroederld@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Jun 30, 2022
* remove net-http-persistent

* fix concurrent-ruby usage that breaks on Windows

* add pipeline and clean up with with rm_rf instead of rm

* fix highlight blocks

* Hr/azure3 (#103)

* Add Consul and Redis services to Windows.
* Enable Consul and Redis testing

* add dynamo (#104)

* add experimentation event overrides for rules and fallthrough

* warn & don't send event if identify or track has no valid user

* include user in prereq flag events

* rm unnecessary logic

* more factory methods

* update readme to refer to docs

* add Ruby 2.6.2 to CI

* fix missing require for net/http

* stringify built-in user attributes in events, and secondary key for evals

* make const names consistent

* support metric value with track()

* update method description

* applying markdown templates and updating repository url references

* Cleaning up markdown files

* allow skipping database tests

* Updating the package name (#115)

* update package name

* missed one

* revert module entry point name change

* bump ld-eventsource version for stream logging fix

* use YAML.safe_load

* add unit test and temporarily revert fix to demonstrate failure

* restore fix

* add comment about not using FileDataSource in production

* drop events if inbox is full

* update doc comment for track with metric_value

* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Harpo roeder <hroeder@launchdarkly.com>
Co-authored-by: hroederld <46500128+hroederld@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
eli-darkly added a commit that referenced this issue Sep 7, 2022
* Hr/azure3 (#103)

* Add Consul and Redis services to Windows.
* Enable Consul and Redis testing

* add dynamo (#104)

* add experimentation event overrides for rules and fallthrough

* warn & don't send event if identify or track has no valid user

* include user in prereq flag events

* rm unnecessary logic

* more factory methods

* update readme to refer to docs

* add Ruby 2.6.2 to CI

* fix missing require for net/http

* stringify built-in user attributes in events, and secondary key for evals

* make const names consistent

* support metric value with track()

* update method description

* applying markdown templates and updating repository url references

* Cleaning up markdown files

* allow skipping database tests

* Updating the package name (#115)

* update package name

* missed one

* revert module entry point name change

* bump ld-eventsource version for stream logging fix

* use YAML.safe_load

* add unit test and temporarily revert fix to demonstrate failure

* restore fix

* add comment about not using FileDataSource in production

* drop events if inbox is full

* update doc comment for track with metric_value

* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Add polling support for contract test service (#198)

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

Co-authored-by: hroederld <46500128+hroederld@users.noreply.github.com>
Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Dec 30, 2022
* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Drop support for EOL ruby versions (#196)

Ruby 2.5 was EOL 2021-04-05

As of June 27th, 2022, the latest jRuby is Ruby 2.6 compatible.

* Remove alias support (#195)

* Add polling support for contract test service (#198)

* Update rubocop and enable in CI (#197)

Several of the Rubocop cop definitions have been renamed or moved to
entirely other gems. This brings the configuration up to date with the
latest naming conventions.

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

* rubocop reformatting

* add super constructor calls

* disable rubocop Rails rules and fix some remaining syntax offenses

* fix super calls

* Add big segment support to contract tests (#201)

* Initial creation of LDContext (#206)

This introduces the initial structure and usage of the LDContext class.

Instances of this class are expected to be created through static
factory methods:

```ruby
LaunchDarkly::LDContext.create({...})
LaunchDarkly::LDContext.create_multi([...])
```

This class is not completed yet. Rather, this initial commit is focused
on the creation patterns and the most basic operations. Subsequent
commits will continue fleshing out this class and its operation.

The `get_value` method will see significant changes as we introduce
attribute reference support. Its current more simplistic implementation
exists only to serve some interim unit tests.

* Add reference based value retrieval (#207)

This commit introduces the References type used for targeting complex
attributes in the new LDContexts.

References are expected to be created through static factory methods:

```ruby
LaunchDarkly::Reference.create("/a/b")
LaunchDarkly::Reference.create_literal("/a/b")
```

These references can be used to retrieve values from an existing
LDContext

```ruby
ref = LaunchDarkly::Reference.create("/a/b")
result = context.get_value_for_reference(ref)
```

* Basic changes to use contexts in evaluations instead of users (#208)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

This replaces `LDUser` with `LDContext` in the parameters for
evaluations, and makes the minimum necessary adjustments to allow
evaluations to keep working as before as long as the context kind is
"user". None of the new behavior defined in the U2C spec is implemented
yet.

Generation of evaluation events is temporarily disabled because the
event logic hasn't been updated yet.

U2C contract tests for evaluations are partially enabled; a lot of
functionality is still missing, but all the tests that only cover
previously-existing evaluation behavior are passing.

[pr]: launchdarkly/php-server-sdk-private#103

* Support ContextKind in Clauses (#209)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

The main features of this commit are:

- introduction of `individual_context` and `individual_context_count`
  methods 
- context kind matching in clauses

[pr]: launchdarkly/php-server-sdk-private#108

* Support included / excluded contexts in segments (#210)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

Segments are now able to provide `includedContext` and `excludedContext`
properties which can target values within a specific context kind.

```json
{
    "includedContexts": [
        {
            "contextKind": "org",
            "values": ["orgkey1", "orgkey2"]
        }
    ]
}
```

[pr]: launchdarkly/php-server-sdk-private#111

* Add contextKind support for rollouts & experiements (#211)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

[pr]: launchdarkly/php-server-sdk-private#110

* Style and test matcher improvements (#212)

This commit enables several rubocop rules that were previously disabled.
Once enabled, `rubocop -A` was run to automatically apply these fixes.

There are a couple of additional changes that were made by hand:

- I added the rubocop and rubocop-performance gems as dev packages. This
  should help address the original installation issue we ran into when I
  introduced these tools.

- By default, new rubocop rules are disabled. This was the default
  before, but if you don't explicitly set this value, each run generates
  a ton of warning noise. This quiets that down.

- Updates some LDContext tests to be more strict in their expectations
  of truth.

* Remove support for secondary attribute (#213)

As decided in the [spec], we are removing the special behavior of the
secondary attribute. Going forward, secondary will be treated like any
other attribute, and will no longer be included when determining the
bucket for a context.

[spec]:
https://launchdarkly.atlassian.net/wiki/spaces/ENG/pages/2165212563/Consistent+and+Transparent+Rollout+Behavior+Unifying+Percent+Rollout+and+Traffic+Allocation

* Remove deprecated APIs (#214)

Since the users to context change requires a version break, this is the
perfect time to remove previously deprecated bits of functionality. This
includes:

- Removing `update_processor*` config entries
- `FileDataSource` entry point
- `RedisFeatureStore` entry point
- `Redis::sadd?` warning in unit tests

* store data model with classes that aren't Hash

* lint

* remove [] override methods in places where we don't need them

* comments

* migrate some more of the model to be non-hash classes

* lint

* Anonymous cannot be nil in new context format (#216)

The legacy user format allowed anonymous to be missing or explicitly
provided but set to nil.

The new context format requires anonymous to either not be set, or if it
is explicitly set, it must be a boolean value.

* Tweak error message language and style (#217)

Our previous error messages suffered from a couple drawbacks:

- The messages were complete sentences, limiting our ability to compose
  error messages
- The messages were overly broad in many cases
- The messages unnecessarily required string interpolation that rarely
  provided much value

These new messages are more succinct and are written as small clauses
which can be used in conjunction with other error messages more easily.

* copyedit

Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>

* Implement prerequisite cycle detection (#219)

* Support attribute reference lookups (#215)

This adds support for slash-delimited paths in clause attributes,
bucketBy, etc. It does not do anything related to private attribute
redaction because none of the U2C event logic is implemented yet.

* Implement segment recursion and cycle detection (#220)

Clauses in segment rules are now allowed to reference segments. To
prevent an infinite recursion edge case, we implement a similar cycle
detection mechanism as used on prerequisites.

* Update event logic to support users to context change (#221)

* Add legacy user-type support to the contract tests (#222)

* Remove inline user configuration option (#223)

* Add context_ configuration options (#224)

These new context_ configuration options are meant to replace the
historic user_ options. If both are provided, the context_ variant will
take precedence.

* Add support for flag context targets (#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (#228)

A few of our internal models maintain arrays of values. These arrays can
frequently be checked to see if they contain specific values.

Since set lookups are much faster than array lookups, this commit
changes the internal structure to a set for the values stored in Target
and SegmentTarget.

* Add secure mode hash to contract tests (#229)

* Update big segment support for users to context (#226)

To support the users to context change for big segments, this commit
makes the following changes:

- Introduces a new `Segment.unboundedContextKind` attribute. This will
default to `LDContext::KIND_DEFAULT` and is only referenced when
`Segment.unbounded` is true.

- With the creation of multi-kind contexts, a single evaluation may
result in multiple queries to the big segment store. This is reflected
in the changes to the `EvalResult` processing.

* Drop support for ruby 2.6 (#227)

Ruby 2.6 went EOL in March 2022. We originally didn't drop support for
it as doing so would require dropping support for jRuby as well.
However, jRuby recently released 9.4 which is Ruby 2.7+ compatible.

* Update remaining references from user to contexts (#231)

There are multiple places throughout the code where we are still
referencing users. I have tried to update all the places where a rename
seems reasonable or appropriate. There is still some work to do in the
test flag builders, but that will be done in a subsequent commit.

* Remove new relic integration (#233)

The new relic integration was removed many versions ago but a small
trace remained behind.

* Rename config option private_attribute_names (#234)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>

* Update test data integration to support contexts (#232)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Jan 19, 2023
* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Drop support for EOL ruby versions (#196)

Ruby 2.5 was EOL 2021-04-05

As of June 27th, 2022, the latest jRuby is Ruby 2.6 compatible.

* Remove alias support (#195)

* Add polling support for contract test service (#198)

* Update rubocop and enable in CI (#197)

Several of the Rubocop cop definitions have been renamed or moved to
entirely other gems. This brings the configuration up to date with the
latest naming conventions.

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

* rubocop reformatting

* add super constructor calls

* disable rubocop Rails rules and fix some remaining syntax offenses

* fix super calls

* Add big segment support to contract tests (#201)

* Initial creation of LDContext (#206)

This introduces the initial structure and usage of the LDContext class.

Instances of this class are expected to be created through static
factory methods:

```ruby
LaunchDarkly::LDContext.create({...})
LaunchDarkly::LDContext.create_multi([...])
```

This class is not completed yet. Rather, this initial commit is focused
on the creation patterns and the most basic operations. Subsequent
commits will continue fleshing out this class and its operation.

The `get_value` method will see significant changes as we introduce
attribute reference support. Its current more simplistic implementation
exists only to serve some interim unit tests.

* Add reference based value retrieval (#207)

This commit introduces the References type used for targeting complex
attributes in the new LDContexts.

References are expected to be created through static factory methods:

```ruby
LaunchDarkly::Reference.create("/a/b")
LaunchDarkly::Reference.create_literal("/a/b")
```

These references can be used to retrieve values from an existing
LDContext

```ruby
ref = LaunchDarkly::Reference.create("/a/b")
result = context.get_value_for_reference(ref)
```

* Basic changes to use contexts in evaluations instead of users (#208)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

This replaces `LDUser` with `LDContext` in the parameters for
evaluations, and makes the minimum necessary adjustments to allow
evaluations to keep working as before as long as the context kind is
"user". None of the new behavior defined in the U2C spec is implemented
yet.

Generation of evaluation events is temporarily disabled because the
event logic hasn't been updated yet.

U2C contract tests for evaluations are partially enabled; a lot of
functionality is still missing, but all the tests that only cover
previously-existing evaluation behavior are passing.

[pr]: launchdarkly/php-server-sdk-private#103

* Support ContextKind in Clauses (#209)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

The main features of this commit are:

- introduction of `individual_context` and `individual_context_count`
  methods 
- context kind matching in clauses

[pr]: launchdarkly/php-server-sdk-private#108

* Support included / excluded contexts in segments (#210)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

Segments are now able to provide `includedContext` and `excludedContext`
properties which can target values within a specific context kind.

```json
{
    "includedContexts": [
        {
            "contextKind": "org",
            "values": ["orgkey1", "orgkey2"]
        }
    ]
}
```

[pr]: launchdarkly/php-server-sdk-private#111

* Add contextKind support for rollouts & experiements (#211)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

[pr]: launchdarkly/php-server-sdk-private#110

* Style and test matcher improvements (#212)

This commit enables several rubocop rules that were previously disabled.
Once enabled, `rubocop -A` was run to automatically apply these fixes.

There are a couple of additional changes that were made by hand:

- I added the rubocop and rubocop-performance gems as dev packages. This
  should help address the original installation issue we ran into when I
  introduced these tools.

- By default, new rubocop rules are disabled. This was the default
  before, but if you don't explicitly set this value, each run generates
  a ton of warning noise. This quiets that down.

- Updates some LDContext tests to be more strict in their expectations
  of truth.

* Remove support for secondary attribute (#213)

As decided in the [spec], we are removing the special behavior of the
secondary attribute. Going forward, secondary will be treated like any
other attribute, and will no longer be included when determining the
bucket for a context.

[spec]:
https://launchdarkly.atlassian.net/wiki/spaces/ENG/pages/2165212563/Consistent+and+Transparent+Rollout+Behavior+Unifying+Percent+Rollout+and+Traffic+Allocation

* Remove deprecated APIs (#214)

Since the users to context change requires a version break, this is the
perfect time to remove previously deprecated bits of functionality. This
includes:

- Removing `update_processor*` config entries
- `FileDataSource` entry point
- `RedisFeatureStore` entry point
- `Redis::sadd?` warning in unit tests

* store data model with classes that aren't Hash

* lint

* remove [] override methods in places where we don't need them

* comments

* migrate some more of the model to be non-hash classes

* lint

* Anonymous cannot be nil in new context format (#216)

The legacy user format allowed anonymous to be missing or explicitly
provided but set to nil.

The new context format requires anonymous to either not be set, or if it
is explicitly set, it must be a boolean value.

* Tweak error message language and style (#217)

Our previous error messages suffered from a couple drawbacks:

- The messages were complete sentences, limiting our ability to compose
  error messages
- The messages were overly broad in many cases
- The messages unnecessarily required string interpolation that rarely
  provided much value

These new messages are more succinct and are written as small clauses
which can be used in conjunction with other error messages more easily.

* copyedit

Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>

* Implement prerequisite cycle detection (#219)

* Support attribute reference lookups (#215)

This adds support for slash-delimited paths in clause attributes,
bucketBy, etc. It does not do anything related to private attribute
redaction because none of the U2C event logic is implemented yet.

* Implement segment recursion and cycle detection (#220)

Clauses in segment rules are now allowed to reference segments. To
prevent an infinite recursion edge case, we implement a similar cycle
detection mechanism as used on prerequisites.

* Update event logic to support users to context change (#221)

* Add legacy user-type support to the contract tests (#222)

* Remove inline user configuration option (#223)

* Add context_ configuration options (#224)

These new context_ configuration options are meant to replace the
historic user_ options. If both are provided, the context_ variant will
take precedence.

* Add support for flag context targets (#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (#228)

A few of our internal models maintain arrays of values. These arrays can
frequently be checked to see if they contain specific values.

Since set lookups are much faster than array lookups, this commit
changes the internal structure to a set for the values stored in Target
and SegmentTarget.

* Add secure mode hash to contract tests (#229)

* Update big segment support for users to context (#226)

To support the users to context change for big segments, this commit
makes the following changes:

- Introduces a new `Segment.unboundedContextKind` attribute. This will
default to `LDContext::KIND_DEFAULT` and is only referenced when
`Segment.unbounded` is true.

- With the creation of multi-kind contexts, a single evaluation may
result in multiple queries to the big segment store. This is reflected
in the changes to the `EvalResult` processing.

* Drop support for ruby 2.6 (#227)

Ruby 2.6 went EOL in March 2022. We originally didn't drop support for
it as doing so would require dropping support for jRuby as well.
However, jRuby recently released 9.4 which is Ruby 2.7+ compatible.

* Update remaining references from user to contexts (#231)

There are multiple places throughout the code where we are still
referencing users. I have tried to update all the places where a rename
seems reasonable or appropriate. There is still some work to do in the
test flag builders, but that will be done in a subsequent commit.

* Remove new relic integration (#233)

The new relic integration was removed many versions ago but a small
trace remained behind.

* Rename config option private_attribute_names (#234)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>

* Update test data integration to support contexts (#232)

* improve data model validation logging; allow missing/empty attribute for segmentMatch (#236)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Jan 27, 2023
* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Drop support for EOL ruby versions (#196)

Ruby 2.5 was EOL 2021-04-05

As of June 27th, 2022, the latest jRuby is Ruby 2.6 compatible.

* Remove alias support (#195)

* Add polling support for contract test service (#198)

* Update rubocop and enable in CI (#197)

Several of the Rubocop cop definitions have been renamed or moved to
entirely other gems. This brings the configuration up to date with the
latest naming conventions.

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

* rubocop reformatting

* add super constructor calls

* disable rubocop Rails rules and fix some remaining syntax offenses

* fix super calls

* Add big segment support to contract tests (#201)

* Initial creation of LDContext (#206)

This introduces the initial structure and usage of the LDContext class.

Instances of this class are expected to be created through static
factory methods:

```ruby
LaunchDarkly::LDContext.create({...})
LaunchDarkly::LDContext.create_multi([...])
```

This class is not completed yet. Rather, this initial commit is focused
on the creation patterns and the most basic operations. Subsequent
commits will continue fleshing out this class and its operation.

The `get_value` method will see significant changes as we introduce
attribute reference support. Its current more simplistic implementation
exists only to serve some interim unit tests.

* Add reference based value retrieval (#207)

This commit introduces the References type used for targeting complex
attributes in the new LDContexts.

References are expected to be created through static factory methods:

```ruby
LaunchDarkly::Reference.create("/a/b")
LaunchDarkly::Reference.create_literal("/a/b")
```

These references can be used to retrieve values from an existing
LDContext

```ruby
ref = LaunchDarkly::Reference.create("/a/b")
result = context.get_value_for_reference(ref)
```

* Basic changes to use contexts in evaluations instead of users (#208)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

This replaces `LDUser` with `LDContext` in the parameters for
evaluations, and makes the minimum necessary adjustments to allow
evaluations to keep working as before as long as the context kind is
"user". None of the new behavior defined in the U2C spec is implemented
yet.

Generation of evaluation events is temporarily disabled because the
event logic hasn't been updated yet.

U2C contract tests for evaluations are partially enabled; a lot of
functionality is still missing, but all the tests that only cover
previously-existing evaluation behavior are passing.

[pr]: launchdarkly/php-server-sdk-private#103

* Support ContextKind in Clauses (#209)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

The main features of this commit are:

- introduction of `individual_context` and `individual_context_count`
  methods 
- context kind matching in clauses

[pr]: launchdarkly/php-server-sdk-private#108

* Support included / excluded contexts in segments (#210)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

Segments are now able to provide `includedContext` and `excludedContext`
properties which can target values within a specific context kind.

```json
{
    "includedContexts": [
        {
            "contextKind": "org",
            "values": ["orgkey1", "orgkey2"]
        }
    ]
}
```

[pr]: launchdarkly/php-server-sdk-private#111

* Add contextKind support for rollouts & experiements (#211)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

[pr]: launchdarkly/php-server-sdk-private#110

* Style and test matcher improvements (#212)

This commit enables several rubocop rules that were previously disabled.
Once enabled, `rubocop -A` was run to automatically apply these fixes.

There are a couple of additional changes that were made by hand:

- I added the rubocop and rubocop-performance gems as dev packages. This
  should help address the original installation issue we ran into when I
  introduced these tools.

- By default, new rubocop rules are disabled. This was the default
  before, but if you don't explicitly set this value, each run generates
  a ton of warning noise. This quiets that down.

- Updates some LDContext tests to be more strict in their expectations
  of truth.

* Remove support for secondary attribute (#213)

As decided in the [spec], we are removing the special behavior of the
secondary attribute. Going forward, secondary will be treated like any
other attribute, and will no longer be included when determining the
bucket for a context.

[spec]:
https://launchdarkly.atlassian.net/wiki/spaces/ENG/pages/2165212563/Consistent+and+Transparent+Rollout+Behavior+Unifying+Percent+Rollout+and+Traffic+Allocation

* Remove deprecated APIs (#214)

Since the users to context change requires a version break, this is the
perfect time to remove previously deprecated bits of functionality. This
includes:

- Removing `update_processor*` config entries
- `FileDataSource` entry point
- `RedisFeatureStore` entry point
- `Redis::sadd?` warning in unit tests

* store data model with classes that aren't Hash

* lint

* remove [] override methods in places where we don't need them

* comments

* migrate some more of the model to be non-hash classes

* lint

* Anonymous cannot be nil in new context format (#216)

The legacy user format allowed anonymous to be missing or explicitly
provided but set to nil.

The new context format requires anonymous to either not be set, or if it
is explicitly set, it must be a boolean value.

* Tweak error message language and style (#217)

Our previous error messages suffered from a couple drawbacks:

- The messages were complete sentences, limiting our ability to compose
  error messages
- The messages were overly broad in many cases
- The messages unnecessarily required string interpolation that rarely
  provided much value

These new messages are more succinct and are written as small clauses
which can be used in conjunction with other error messages more easily.

* copyedit

Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>

* Implement prerequisite cycle detection (#219)

* Support attribute reference lookups (#215)

This adds support for slash-delimited paths in clause attributes,
bucketBy, etc. It does not do anything related to private attribute
redaction because none of the U2C event logic is implemented yet.

* Implement segment recursion and cycle detection (#220)

Clauses in segment rules are now allowed to reference segments. To
prevent an infinite recursion edge case, we implement a similar cycle
detection mechanism as used on prerequisites.

* Update event logic to support users to context change (#221)

* Add legacy user-type support to the contract tests (#222)

* Remove inline user configuration option (#223)

* Add context_ configuration options (#224)

These new context_ configuration options are meant to replace the
historic user_ options. If both are provided, the context_ variant will
take precedence.

* Add support for flag context targets (#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (#228)

A few of our internal models maintain arrays of values. These arrays can
frequently be checked to see if they contain specific values.

Since set lookups are much faster than array lookups, this commit
changes the internal structure to a set for the values stored in Target
and SegmentTarget.

* Add secure mode hash to contract tests (#229)

* Update big segment support for users to context (#226)

To support the users to context change for big segments, this commit
makes the following changes:

- Introduces a new `Segment.unboundedContextKind` attribute. This will
default to `LDContext::KIND_DEFAULT` and is only referenced when
`Segment.unbounded` is true.

- With the creation of multi-kind contexts, a single evaluation may
result in multiple queries to the big segment store. This is reflected
in the changes to the `EvalResult` processing.

* Drop support for ruby 2.6 (#227)

Ruby 2.6 went EOL in March 2022. We originally didn't drop support for
it as doing so would require dropping support for jRuby as well.
However, jRuby recently released 9.4 which is Ruby 2.7+ compatible.

* Update remaining references from user to contexts (#231)

There are multiple places throughout the code where we are still
referencing users. I have tried to update all the places where a rename
seems reasonable or appropriate. There is still some work to do in the
test flag builders, but that will be done in a subsequent commit.

* Remove new relic integration (#233)

The new relic integration was removed many versions ago but a small
trace remained behind.

* Rename config option private_attribute_names (#234)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>

* Update test data integration to support contexts (#232)

* improve data model validation logging; allow missing/empty attribute for segmentMatch (#236)

* Fix JSON serialization failure (#237)

When we introduced models for the flag and segment data, we added
to_json methods which proxy to the underlying to_json method provided by
the `json` gem.

We defined the method with a variadic parameter, but we failed to unpack
it when passing it on to the underlying implementation. This resulted in
a serialization failure which prevented the redis data store from
initializing.

---------

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Mar 17, 2023
* don't let user fall outside of last bucket in rollout

* refactor evaluation logic and move it out of the main namespace

* comments

* fix type coercion behavior

* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Drop support for EOL ruby versions (#196)

Ruby 2.5 was EOL 2021-04-05

As of June 27th, 2022, the latest jRuby is Ruby 2.6 compatible.

* Remove alias support (#195)

* Add polling support for contract test service (#198)

* Update rubocop and enable in CI (#197)

Several of the Rubocop cop definitions have been renamed or moved to
entirely other gems. This brings the configuration up to date with the
latest naming conventions.

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

* rubocop reformatting

* add super constructor calls

* disable rubocop Rails rules and fix some remaining syntax offenses

* fix super calls

* Add big segment support to contract tests (#201)

* Initial creation of LDContext (#206)

This introduces the initial structure and usage of the LDContext class.

Instances of this class are expected to be created through static
factory methods:

```ruby
LaunchDarkly::LDContext.create({...})
LaunchDarkly::LDContext.create_multi([...])
```

This class is not completed yet. Rather, this initial commit is focused
on the creation patterns and the most basic operations. Subsequent
commits will continue fleshing out this class and its operation.

The `get_value` method will see significant changes as we introduce
attribute reference support. Its current more simplistic implementation
exists only to serve some interim unit tests.

* Add reference based value retrieval (#207)

This commit introduces the References type used for targeting complex
attributes in the new LDContexts.

References are expected to be created through static factory methods:

```ruby
LaunchDarkly::Reference.create("/a/b")
LaunchDarkly::Reference.create_literal("/a/b")
```

These references can be used to retrieve values from an existing
LDContext

```ruby
ref = LaunchDarkly::Reference.create("/a/b")
result = context.get_value_for_reference(ref)
```

* Basic changes to use contexts in evaluations instead of users (#208)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

This replaces `LDUser` with `LDContext` in the parameters for
evaluations, and makes the minimum necessary adjustments to allow
evaluations to keep working as before as long as the context kind is
"user". None of the new behavior defined in the U2C spec is implemented
yet.

Generation of evaluation events is temporarily disabled because the
event logic hasn't been updated yet.

U2C contract tests for evaluations are partially enabled; a lot of
functionality is still missing, but all the tests that only cover
previously-existing evaluation behavior are passing.

[pr]: launchdarkly/php-server-sdk-private#103

* Support ContextKind in Clauses (#209)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

The main features of this commit are:

- introduction of `individual_context` and `individual_context_count`
  methods 
- context kind matching in clauses

[pr]: launchdarkly/php-server-sdk-private#108

* Support included / excluded contexts in segments (#210)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

Segments are now able to provide `includedContext` and `excludedContext`
properties which can target values within a specific context kind.

```json
{
    "includedContexts": [
        {
            "contextKind": "org",
            "values": ["orgkey1", "orgkey2"]
        }
    ]
}
```

[pr]: launchdarkly/php-server-sdk-private#111

* Add contextKind support for rollouts & experiements (#211)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

[pr]: launchdarkly/php-server-sdk-private#110

* Style and test matcher improvements (#212)

This commit enables several rubocop rules that were previously disabled.
Once enabled, `rubocop -A` was run to automatically apply these fixes.

There are a couple of additional changes that were made by hand:

- I added the rubocop and rubocop-performance gems as dev packages. This
  should help address the original installation issue we ran into when I
  introduced these tools.

- By default, new rubocop rules are disabled. This was the default
  before, but if you don't explicitly set this value, each run generates
  a ton of warning noise. This quiets that down.

- Updates some LDContext tests to be more strict in their expectations
  of truth.

* Remove support for secondary attribute (#213)

As decided in the [spec], we are removing the special behavior of the
secondary attribute. Going forward, secondary will be treated like any
other attribute, and will no longer be included when determining the
bucket for a context.

[spec]:
https://launchdarkly.atlassian.net/wiki/spaces/ENG/pages/2165212563/Consistent+and+Transparent+Rollout+Behavior+Unifying+Percent+Rollout+and+Traffic+Allocation

* Remove deprecated APIs (#214)

Since the users to context change requires a version break, this is the
perfect time to remove previously deprecated bits of functionality. This
includes:

- Removing `update_processor*` config entries
- `FileDataSource` entry point
- `RedisFeatureStore` entry point
- `Redis::sadd?` warning in unit tests

* store data model with classes that aren't Hash

* lint

* remove [] override methods in places where we don't need them

* comments

* migrate some more of the model to be non-hash classes

* lint

* Anonymous cannot be nil in new context format (#216)

The legacy user format allowed anonymous to be missing or explicitly
provided but set to nil.

The new context format requires anonymous to either not be set, or if it
is explicitly set, it must be a boolean value.

* Tweak error message language and style (#217)

Our previous error messages suffered from a couple drawbacks:

- The messages were complete sentences, limiting our ability to compose
  error messages
- The messages were overly broad in many cases
- The messages unnecessarily required string interpolation that rarely
  provided much value

These new messages are more succinct and are written as small clauses
which can be used in conjunction with other error messages more easily.

* copyedit

Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>

* Implement prerequisite cycle detection (#219)

* Support attribute reference lookups (#215)

This adds support for slash-delimited paths in clause attributes,
bucketBy, etc. It does not do anything related to private attribute
redaction because none of the U2C event logic is implemented yet.

* Implement segment recursion and cycle detection (#220)

Clauses in segment rules are now allowed to reference segments. To
prevent an infinite recursion edge case, we implement a similar cycle
detection mechanism as used on prerequisites.

* Update event logic to support users to context change (#221)

* Add legacy user-type support to the contract tests (#222)

* Remove inline user configuration option (#223)

* Add context_ configuration options (#224)

These new context_ configuration options are meant to replace the
historic user_ options. If both are provided, the context_ variant will
take precedence.

* Add support for flag context targets (#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (#228)

A few of our internal models maintain arrays of values. These arrays can
frequently be checked to see if they contain specific values.

Since set lookups are much faster than array lookups, this commit
changes the internal structure to a set for the values stored in Target
and SegmentTarget.

* Add secure mode hash to contract tests (#229)

* Update big segment support for users to context (#226)

To support the users to context change for big segments, this commit
makes the following changes:

- Introduces a new `Segment.unboundedContextKind` attribute. This will
default to `LDContext::KIND_DEFAULT` and is only referenced when
`Segment.unbounded` is true.

- With the creation of multi-kind contexts, a single evaluation may
result in multiple queries to the big segment store. This is reflected
in the changes to the `EvalResult` processing.

* Drop support for ruby 2.6 (#227)

Ruby 2.6 went EOL in March 2022. We originally didn't drop support for
it as doing so would require dropping support for jRuby as well.
However, jRuby recently released 9.4 which is Ruby 2.7+ compatible.

* Update remaining references from user to contexts (#231)

There are multiple places throughout the code where we are still
referencing users. I have tried to update all the places where a rename
seems reasonable or appropriate. There is still some work to do in the
test flag builders, but that will be done in a subsequent commit.

* Remove new relic integration (#233)

The new relic integration was removed many versions ago but a small
trace remained behind.

* Rename config option private_attribute_names (#234)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>

* Update test data integration to support contexts (#232)

* improve data model validation logging; allow missing/empty attribute for segmentMatch (#236)

* Fix JSON serialization failure (#237)

When we introduced models for the flag and segment data, we added
to_json methods which proxy to the underlying to_json method provided by
the `json` gem.

We defined the method with a variadic parameter, but we failed to unpack
it when passing it on to the underlying implementation. This resulted in
a serialization failure which prevented the redis data store from
initializing.

* fix: Bump eventsource to resolve header parsing (#239)

The underlying event source library had an issue where, in certain
environments, content-type header detection was failing.

This was resolved in v2.2.2 of the event source gem.

---------

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Apr 3, 2023
* make type coercion behavior consistent with earlier versions for now

* whitespace

* break up Evaluator tests further

* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Drop support for EOL ruby versions (#196)

Ruby 2.5 was EOL 2021-04-05

As of June 27th, 2022, the latest jRuby is Ruby 2.6 compatible.

* Remove alias support (#195)

* Add polling support for contract test service (#198)

* Update rubocop and enable in CI (#197)

Several of the Rubocop cop definitions have been renamed or moved to
entirely other gems. This brings the configuration up to date with the
latest naming conventions.

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

* rubocop reformatting

* add super constructor calls

* disable rubocop Rails rules and fix some remaining syntax offenses

* fix super calls

* Add big segment support to contract tests (#201)

* Initial creation of LDContext (#206)

This introduces the initial structure and usage of the LDContext class.

Instances of this class are expected to be created through static
factory methods:

```ruby
LaunchDarkly::LDContext.create({...})
LaunchDarkly::LDContext.create_multi([...])
```

This class is not completed yet. Rather, this initial commit is focused
on the creation patterns and the most basic operations. Subsequent
commits will continue fleshing out this class and its operation.

The `get_value` method will see significant changes as we introduce
attribute reference support. Its current more simplistic implementation
exists only to serve some interim unit tests.

* Add reference based value retrieval (#207)

This commit introduces the References type used for targeting complex
attributes in the new LDContexts.

References are expected to be created through static factory methods:

```ruby
LaunchDarkly::Reference.create("/a/b")
LaunchDarkly::Reference.create_literal("/a/b")
```

These references can be used to retrieve values from an existing
LDContext

```ruby
ref = LaunchDarkly::Reference.create("/a/b")
result = context.get_value_for_reference(ref)
```

* Basic changes to use contexts in evaluations instead of users (#208)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

This replaces `LDUser` with `LDContext` in the parameters for
evaluations, and makes the minimum necessary adjustments to allow
evaluations to keep working as before as long as the context kind is
"user". None of the new behavior defined in the U2C spec is implemented
yet.

Generation of evaluation events is temporarily disabled because the
event logic hasn't been updated yet.

U2C contract tests for evaluations are partially enabled; a lot of
functionality is still missing, but all the tests that only cover
previously-existing evaluation behavior are passing.

[pr]: launchdarkly/php-server-sdk-private#103

* Support ContextKind in Clauses (#209)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

The main features of this commit are:

- introduction of `individual_context` and `individual_context_count`
  methods 
- context kind matching in clauses

[pr]: launchdarkly/php-server-sdk-private#108

* Support included / excluded contexts in segments (#210)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

Segments are now able to provide `includedContext` and `excludedContext`
properties which can target values within a specific context kind.

```json
{
    "includedContexts": [
        {
            "contextKind": "org",
            "values": ["orgkey1", "orgkey2"]
        }
    ]
}
```

[pr]: launchdarkly/php-server-sdk-private#111

* Add contextKind support for rollouts & experiements (#211)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

[pr]: launchdarkly/php-server-sdk-private#110

* Style and test matcher improvements (#212)

This commit enables several rubocop rules that were previously disabled.
Once enabled, `rubocop -A` was run to automatically apply these fixes.

There are a couple of additional changes that were made by hand:

- I added the rubocop and rubocop-performance gems as dev packages. This
  should help address the original installation issue we ran into when I
  introduced these tools.

- By default, new rubocop rules are disabled. This was the default
  before, but if you don't explicitly set this value, each run generates
  a ton of warning noise. This quiets that down.

- Updates some LDContext tests to be more strict in their expectations
  of truth.

* Remove support for secondary attribute (#213)

As decided in the [spec], we are removing the special behavior of the
secondary attribute. Going forward, secondary will be treated like any
other attribute, and will no longer be included when determining the
bucket for a context.

[spec]:
https://launchdarkly.atlassian.net/wiki/spaces/ENG/pages/2165212563/Consistent+and+Transparent+Rollout+Behavior+Unifying+Percent+Rollout+and+Traffic+Allocation

* Remove deprecated APIs (#214)

Since the users to context change requires a version break, this is the
perfect time to remove previously deprecated bits of functionality. This
includes:

- Removing `update_processor*` config entries
- `FileDataSource` entry point
- `RedisFeatureStore` entry point
- `Redis::sadd?` warning in unit tests

* store data model with classes that aren't Hash

* lint

* remove [] override methods in places where we don't need them

* comments

* migrate some more of the model to be non-hash classes

* lint

* Anonymous cannot be nil in new context format (#216)

The legacy user format allowed anonymous to be missing or explicitly
provided but set to nil.

The new context format requires anonymous to either not be set, or if it
is explicitly set, it must be a boolean value.

* Tweak error message language and style (#217)

Our previous error messages suffered from a couple drawbacks:

- The messages were complete sentences, limiting our ability to compose
  error messages
- The messages were overly broad in many cases
- The messages unnecessarily required string interpolation that rarely
  provided much value

These new messages are more succinct and are written as small clauses
which can be used in conjunction with other error messages more easily.

* copyedit

Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>

* Implement prerequisite cycle detection (#219)

* Support attribute reference lookups (#215)

This adds support for slash-delimited paths in clause attributes,
bucketBy, etc. It does not do anything related to private attribute
redaction because none of the U2C event logic is implemented yet.

* Implement segment recursion and cycle detection (#220)

Clauses in segment rules are now allowed to reference segments. To
prevent an infinite recursion edge case, we implement a similar cycle
detection mechanism as used on prerequisites.

* Update event logic to support users to context change (#221)

* Add legacy user-type support to the contract tests (#222)

* Remove inline user configuration option (#223)

* Add context_ configuration options (#224)

These new context_ configuration options are meant to replace the
historic user_ options. If both are provided, the context_ variant will
take precedence.

* Add support for flag context targets (#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (#228)

A few of our internal models maintain arrays of values. These arrays can
frequently be checked to see if they contain specific values.

Since set lookups are much faster than array lookups, this commit
changes the internal structure to a set for the values stored in Target
and SegmentTarget.

* Add secure mode hash to contract tests (#229)

* Update big segment support for users to context (#226)

To support the users to context change for big segments, this commit
makes the following changes:

- Introduces a new `Segment.unboundedContextKind` attribute. This will
default to `LDContext::KIND_DEFAULT` and is only referenced when
`Segment.unbounded` is true.

- With the creation of multi-kind contexts, a single evaluation may
result in multiple queries to the big segment store. This is reflected
in the changes to the `EvalResult` processing.

* Drop support for ruby 2.6 (#227)

Ruby 2.6 went EOL in March 2022. We originally didn't drop support for
it as doing so would require dropping support for jRuby as well.
However, jRuby recently released 9.4 which is Ruby 2.7+ compatible.

* Update remaining references from user to contexts (#231)

There are multiple places throughout the code where we are still
referencing users. I have tried to update all the places where a rename
seems reasonable or appropriate. There is still some work to do in the
test flag builders, but that will be done in a subsequent commit.

* Remove new relic integration (#233)

The new relic integration was removed many versions ago but a small
trace remained behind.

* Rename config option private_attribute_names (#234)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>

* Update test data integration to support contexts (#232)

* improve data model validation logging; allow missing/empty attribute for segmentMatch (#236)

* Fix JSON serialization failure (#237)

When we introduced models for the flag and segment data, we added
to_json methods which proxy to the underlying to_json method provided by
the `json` gem.

We defined the method with a variadic parameter, but we failed to unpack
it when passing it on to the underlying implementation. This resulted in
a serialization failure which prevented the redis data store from
initializing.

* fix: Bump eventsource to resolve header parsing (#239)

The underlying event source library had an issue where, in certain
environments, content-type header detection was failing.

This was resolved in v2.2.2 of the event source gem.

* Add key to error log for invalid context during variation call for easier debugging (#214)

---------

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
Co-authored-by: Matt Hooks <46452201+matt-dutchie@users.noreply.github.com>
LaunchDarklyReleaseBot added a commit that referenced this issue Apr 13, 2023
* make EvaluationReason an immutable class

* FrozenError doesn't exist in older Ruby, use more general RuntimeError

* precompute evaluation reasons when we receive a flag

* rm unused

* rename FeatureStore to DataStore

* remove references to UpdateProcessor (now DataSource)

* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Drop support for EOL ruby versions (#196)

Ruby 2.5 was EOL 2021-04-05

As of June 27th, 2022, the latest jRuby is Ruby 2.6 compatible.

* Remove alias support (#195)

* Add polling support for contract test service (#198)

* Update rubocop and enable in CI (#197)

Several of the Rubocop cop definitions have been renamed or moved to
entirely other gems. This brings the configuration up to date with the
latest naming conventions.

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

* rubocop reformatting

* add super constructor calls

* disable rubocop Rails rules and fix some remaining syntax offenses

* fix super calls

* Add big segment support to contract tests (#201)

* Initial creation of LDContext (#206)

This introduces the initial structure and usage of the LDContext class.

Instances of this class are expected to be created through static
factory methods:

```ruby
LaunchDarkly::LDContext.create({...})
LaunchDarkly::LDContext.create_multi([...])
```

This class is not completed yet. Rather, this initial commit is focused
on the creation patterns and the most basic operations. Subsequent
commits will continue fleshing out this class and its operation.

The `get_value` method will see significant changes as we introduce
attribute reference support. Its current more simplistic implementation
exists only to serve some interim unit tests.

* Add reference based value retrieval (#207)

This commit introduces the References type used for targeting complex
attributes in the new LDContexts.

References are expected to be created through static factory methods:

```ruby
LaunchDarkly::Reference.create("/a/b")
LaunchDarkly::Reference.create_literal("/a/b")
```

These references can be used to retrieve values from an existing
LDContext

```ruby
ref = LaunchDarkly::Reference.create("/a/b")
result = context.get_value_for_reference(ref)
```

* Basic changes to use contexts in evaluations instead of users (#208)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

This replaces `LDUser` with `LDContext` in the parameters for
evaluations, and makes the minimum necessary adjustments to allow
evaluations to keep working as before as long as the context kind is
"user". None of the new behavior defined in the U2C spec is implemented
yet.

Generation of evaluation events is temporarily disabled because the
event logic hasn't been updated yet.

U2C contract tests for evaluations are partially enabled; a lot of
functionality is still missing, but all the tests that only cover
previously-existing evaluation behavior are passing.

[pr]: launchdarkly/php-server-sdk-private#103

* Support ContextKind in Clauses (#209)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

The main features of this commit are:

- introduction of `individual_context` and `individual_context_count`
  methods 
- context kind matching in clauses

[pr]: launchdarkly/php-server-sdk-private#108

* Support included / excluded contexts in segments (#210)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

Segments are now able to provide `includedContext` and `excludedContext`
properties which can target values within a specific context kind.

```json
{
    "includedContexts": [
        {
            "contextKind": "org",
            "values": ["orgkey1", "orgkey2"]
        }
    ]
}
```

[pr]: launchdarkly/php-server-sdk-private#111

* Add contextKind support for rollouts & experiements (#211)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

[pr]: launchdarkly/php-server-sdk-private#110

* Style and test matcher improvements (#212)

This commit enables several rubocop rules that were previously disabled.
Once enabled, `rubocop -A` was run to automatically apply these fixes.

There are a couple of additional changes that were made by hand:

- I added the rubocop and rubocop-performance gems as dev packages. This
  should help address the original installation issue we ran into when I
  introduced these tools.

- By default, new rubocop rules are disabled. This was the default
  before, but if you don't explicitly set this value, each run generates
  a ton of warning noise. This quiets that down.

- Updates some LDContext tests to be more strict in their expectations
  of truth.

* Remove support for secondary attribute (#213)

As decided in the [spec], we are removing the special behavior of the
secondary attribute. Going forward, secondary will be treated like any
other attribute, and will no longer be included when determining the
bucket for a context.

[spec]:
https://launchdarkly.atlassian.net/wiki/spaces/ENG/pages/2165212563/Consistent+and+Transparent+Rollout+Behavior+Unifying+Percent+Rollout+and+Traffic+Allocation

* Remove deprecated APIs (#214)

Since the users to context change requires a version break, this is the
perfect time to remove previously deprecated bits of functionality. This
includes:

- Removing `update_processor*` config entries
- `FileDataSource` entry point
- `RedisFeatureStore` entry point
- `Redis::sadd?` warning in unit tests

* store data model with classes that aren't Hash

* lint

* remove [] override methods in places where we don't need them

* comments

* migrate some more of the model to be non-hash classes

* lint

* Anonymous cannot be nil in new context format (#216)

The legacy user format allowed anonymous to be missing or explicitly
provided but set to nil.

The new context format requires anonymous to either not be set, or if it
is explicitly set, it must be a boolean value.

* Tweak error message language and style (#217)

Our previous error messages suffered from a couple drawbacks:

- The messages were complete sentences, limiting our ability to compose
  error messages
- The messages were overly broad in many cases
- The messages unnecessarily required string interpolation that rarely
  provided much value

These new messages are more succinct and are written as small clauses
which can be used in conjunction with other error messages more easily.

* copyedit

Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>

* Implement prerequisite cycle detection (#219)

* Support attribute reference lookups (#215)

This adds support for slash-delimited paths in clause attributes,
bucketBy, etc. It does not do anything related to private attribute
redaction because none of the U2C event logic is implemented yet.

* Implement segment recursion and cycle detection (#220)

Clauses in segment rules are now allowed to reference segments. To
prevent an infinite recursion edge case, we implement a similar cycle
detection mechanism as used on prerequisites.

* Update event logic to support users to context change (#221)

* Add legacy user-type support to the contract tests (#222)

* Remove inline user configuration option (#223)

* Add context_ configuration options (#224)

These new context_ configuration options are meant to replace the
historic user_ options. If both are provided, the context_ variant will
take precedence.

* Add support for flag context targets (#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (#228)

A few of our internal models maintain arrays of values. These arrays can
frequently be checked to see if they contain specific values.

Since set lookups are much faster than array lookups, this commit
changes the internal structure to a set for the values stored in Target
and SegmentTarget.

* Add secure mode hash to contract tests (#229)

* Update big segment support for users to context (#226)

To support the users to context change for big segments, this commit
makes the following changes:

- Introduces a new `Segment.unboundedContextKind` attribute. This will
default to `LDContext::KIND_DEFAULT` and is only referenced when
`Segment.unbounded` is true.

- With the creation of multi-kind contexts, a single evaluation may
result in multiple queries to the big segment store. This is reflected
in the changes to the `EvalResult` processing.

* Drop support for ruby 2.6 (#227)

Ruby 2.6 went EOL in March 2022. We originally didn't drop support for
it as doing so would require dropping support for jRuby as well.
However, jRuby recently released 9.4 which is Ruby 2.7+ compatible.

* Update remaining references from user to contexts (#231)

There are multiple places throughout the code where we are still
referencing users. I have tried to update all the places where a rename
seems reasonable or appropriate. There is still some work to do in the
test flag builders, but that will be done in a subsequent commit.

* Remove new relic integration (#233)

The new relic integration was removed many versions ago but a small
trace remained behind.

* Rename config option private_attribute_names (#234)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>

* Update test data integration to support contexts (#232)

* improve data model validation logging; allow missing/empty attribute for segmentMatch (#236)

* Fix JSON serialization failure (#237)

When we introduced models for the flag and segment data, we added
to_json methods which proxy to the underlying to_json method provided by
the `json` gem.

We defined the method with a variadic parameter, but we failed to unpack
it when passing it on to the underlying implementation. This resulted in
a serialization failure which prevented the redis data store from
initializing.

* fix: Bump eventsource to resolve header parsing (#239)

The underlying event source library had an issue where, in certain
environments, content-type header detection was failing.

This was resolved in v2.2.2 of the event source gem.

* Add key to error log for invalid context during variation call for easier debugging (#214)

* feat: Add support for payload filtering (#238)

---------

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
Co-authored-by: Matt Hooks <46452201+matt-dutchie@users.noreply.github.com>
LaunchDarklyReleaseBot added a commit that referenced this issue May 4, 2023
* add event payload ID header

* (6.0) drop support for old Ruby versions

* add Ruby version constraint to gemspec

* remove Rake dependency

* update ld-eventsource to 1.0.2 which doesn't have Rake dependency

* implement diagnostic events in Ruby (#130)

* update ruby-eventsource to 1.0.3 for backoff bug

* fix incorrect initialization of EventProcessor

* remove install-time openssl check that breaks if you don't have rake

* treat comparison with wrong data type as a non-match, not an exception (#134)

* fail fast for nil SDK key when appropriate

* tolerate nil value for user.custom (#137)

* Only shutdown the Redis pool if it is owned by the SDK (#158)

* Only shutdown a Redis pool created by SDK

* Make pool shutdown behavior an option

* improve doc comment

* remove support for indirect/patch and indirect/put (#138)

* update to json 2.3.1 (#139)

* update json dep to 2.3.x to fix CVE

* add publication of API docs on GitHub Pages (#143)

* try fixing release metadata

* update the default base url (#144)

* revert renames of feature_store & update_processor

* [ch92483] Use http gem and add socket factory support (#142)

* update dependencies and add CI for ruby 3 (#141)

* reference eventsource 2.0 in gemspec

* add 5.x releasable branch for releaser

* use Ruby 2.6.6 in releases

* Removed the guides link

* [ch99757] add alias method (#147)

* don't send event for nil user evaluation

* remove lockfile (#148)

* rm redundant nil check

* Experiment Allocation Changes (#150)

* WIP - from sam's pairing session

* starting sdk changes

* adding tests and making sure everything works

* adding more tests

* removing the singleton for fallthrough

* Revert "removing the singleton for fallthrough"

This reverts commit dff7adbb809ecc63118d0fbff9742a88a039c679.

* taking a different approach to keep things immutable

* adding tests for untracked

* remove unnecessary comment

* making sure to return two values in all code paths

Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>

* Use camelCase for JSON property names (#151)

The in_experiment attribute was added to reasons as part of #150 but it doesn't appear to be received in events. I think that's because it's sending it in JSON as "in_experiment" rather than "inExperiment" as we expect to parse it.

* fixing ruby logic causing ih failures (#152)

* fixing ruby logic

* adding missing spec

* Apply suggestions from code review

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* pr tweaks

* making spec language consistent

Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>

* add log warning for missing user key (#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (#154)

* minor test simplification (#155)

* allow higher minor versions of json and http gems

* allow v5.x of http gem (#157)

* use Bundler 2.2.10 + modernize CI config (#158)

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (#159)

* use Releaser v2 config (#161)

* Updates docs URLs

* Update lib/ldclient-rb/ldclient.rb

Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>

* remove reliance on git in gemspec (#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (#164)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504

* comment phrasing

* Start work on flag builder.

* Add user targeting and rule builder

* Add datasource implementation

* Convert the current_flags hash to use symbols instead of strings as keys

* Fix typo on FlagRuleBuilder copy constructor

* minor refactoring of impl; Added use of new Clause struct instead of Hash in FlagRuleBuilder; Moved TestData.factory out of Impl namespace and renamed Impl to TestDataImpl

* Add the doc comments

* (big segments 1) add public config/interface/reason types (#167)

* Cleanup docstrings to be YARD docs

* Added Util.is_bool helper function to clean up the check for whether an object is a boolean; Removed the DeepCopyHash/DeepCopyArray objects in favor of deep_copy_hash and deep_copy_array functions

* Move public classes out of Impl namespace. Most of it is in public namespace except for the data source now.

* Move require of concurrent/atomics to the correct module

* (big segments 2) implement Big Segments evaluation & status APIs (#168)

* improve CONTRIBUTING.md with notes on code organization

* add note about doc comments

* Cleanup YARD warnings and cleanup docs

* Address PR feedback: Move is_bool back to Impl namespace to avoid confusion; Remove unnecessary nil check on variations in build function; fixup comments

* (big segments 3) implement Redis & DynamoDB big segment stores (#169)

* add missing import

* fix stale calculation

* fix big segments user hash algorithm to use SHA256

* improve & refactor client/evaluation tests

* more cleanup/DRY

* add use_preconfigured_flag and use_preconfigured_segment to TestData (#173)

* always cache big segment query result even if it's nil

* comments

* add test for cache expiration

* use TestData in our own tests (#174)

* use TestData in our own tests

* fix test

* replace LaunchDarkly::FileDataSource with LaunchDarkly::Integrations::FileData

* update ruby-eventsource version for recent SSE fixes

* Bump bundler version (#184)

* Add ability to to set initial reconnect delay (#183)

* Treat secondary as a built-in attribute (#180)

* all_flags_state is invalid if store isn't initialized (#182)

* identify should not emit events if user key is "" (#181)

* Account for traffic allocation on all flags (#185)

* Add contract tests (#178)

* Fix string interpolation in log message (#187)

* Default opts to empty hash when creating persistent feature store (#186)

* Remove Hakiri badge from README (#188)

Hakiri was sunset on January 31st, 2022 at which time our badge stopped
working.

* detect http/https proxy env vars when creating HTTP clients

* rever accidental change

* fix nil safety in test service config

* master -> main (#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (#193)

* Drop support for EOL ruby versions (#196)

Ruby 2.5 was EOL 2021-04-05

As of June 27th, 2022, the latest jRuby is Ruby 2.6 compatible.

* Remove alias support (#195)

* Add polling support for contract test service (#198)

* Update rubocop and enable in CI (#197)

Several of the Rubocop cop definitions have been renamed or moved to
entirely other gems. This brings the configuration up to date with the
latest naming conventions.

* Add windows tests in circleci (#199)

At some point in the past, we were experimenting with using Azure to
verify Window builds. Now that CircleCI supports Windows, we should keep
everything on a single CI provider.

* Add application info support (#194)

* reuse EvaluationDetail instances by precomputing results

* rubocop reformatting

* add super constructor calls

* disable rubocop Rails rules and fix some remaining syntax offenses

* fix super calls

* Add big segment support to contract tests (#201)

* Initial creation of LDContext (#206)

This introduces the initial structure and usage of the LDContext class.

Instances of this class are expected to be created through static
factory methods:

```ruby
LaunchDarkly::LDContext.create({...})
LaunchDarkly::LDContext.create_multi([...])
```

This class is not completed yet. Rather, this initial commit is focused
on the creation patterns and the most basic operations. Subsequent
commits will continue fleshing out this class and its operation.

The `get_value` method will see significant changes as we introduce
attribute reference support. Its current more simplistic implementation
exists only to serve some interim unit tests.

* Add reference based value retrieval (#207)

This commit introduces the References type used for targeting complex
attributes in the new LDContexts.

References are expected to be created through static factory methods:

```ruby
LaunchDarkly::Reference.create("/a/b")
LaunchDarkly::Reference.create_literal("/a/b")
```

These references can be used to retrieve values from an existing
LDContext

```ruby
ref = LaunchDarkly::Reference.create("/a/b")
result = context.get_value_for_reference(ref)
```

* Basic changes to use contexts in evaluations instead of users (#208)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

This replaces `LDUser` with `LDContext` in the parameters for
evaluations, and makes the minimum necessary adjustments to allow
evaluations to keep working as before as long as the context kind is
"user". None of the new behavior defined in the U2C spec is implemented
yet.

Generation of evaluation events is temporarily disabled because the
event logic hasn't been updated yet.

U2C contract tests for evaluations are partially enabled; a lot of
functionality is still missing, but all the tests that only cover
previously-existing evaluation behavior are passing.

[pr]: launchdarkly/php-server-sdk-private#103

* Support ContextKind in Clauses (#209)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

The main features of this commit are:

- introduction of `individual_context` and `individual_context_count`
  methods 
- context kind matching in clauses

[pr]: launchdarkly/php-server-sdk-private#108

* Support included / excluded contexts in segments (#210)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

Segments are now able to provide `includedContext` and `excludedContext`
properties which can target values within a specific context kind.

```json
{
    "includedContexts": [
        {
            "contextKind": "org",
            "values": ["orgkey1", "orgkey2"]
        }
    ]
}
```

[pr]: launchdarkly/php-server-sdk-private#111

* Add contextKind support for rollouts & experiements (#211)

This commit follows the general approach of the [equivalent PHP SDK
PR][pr].

[pr]: launchdarkly/php-server-sdk-private#110

* Style and test matcher improvements (#212)

This commit enables several rubocop rules that were previously disabled.
Once enabled, `rubocop -A` was run to automatically apply these fixes.

There are a couple of additional changes that were made by hand:

- I added the rubocop and rubocop-performance gems as dev packages. This
  should help address the original installation issue we ran into when I
  introduced these tools.

- By default, new rubocop rules are disabled. This was the default
  before, but if you don't explicitly set this value, each run generates
  a ton of warning noise. This quiets that down.

- Updates some LDContext tests to be more strict in their expectations
  of truth.

* Remove support for secondary attribute (#213)

As decided in the [spec], we are removing the special behavior of the
secondary attribute. Going forward, secondary will be treated like any
other attribute, and will no longer be included when determining the
bucket for a context.

[spec]:
https://launchdarkly.atlassian.net/wiki/spaces/ENG/pages/2165212563/Consistent+and+Transparent+Rollout+Behavior+Unifying+Percent+Rollout+and+Traffic+Allocation

* Remove deprecated APIs (#214)

Since the users to context change requires a version break, this is the
perfect time to remove previously deprecated bits of functionality. This
includes:

- Removing `update_processor*` config entries
- `FileDataSource` entry point
- `RedisFeatureStore` entry point
- `Redis::sadd?` warning in unit tests

* store data model with classes that aren't Hash

* lint

* remove [] override methods in places where we don't need them

* comments

* migrate some more of the model to be non-hash classes

* lint

* Anonymous cannot be nil in new context format (#216)

The legacy user format allowed anonymous to be missing or explicitly
provided but set to nil.

The new context format requires anonymous to either not be set, or if it
is explicitly set, it must be a boolean value.

* Tweak error message language and style (#217)

Our previous error messages suffered from a couple drawbacks:

- The messages were complete sentences, limiting our ability to compose
  error messages
- The messages were overly broad in many cases
- The messages unnecessarily required string interpolation that rarely
  provided much value

These new messages are more succinct and are written as small clauses
which can be used in conjunction with other error messages more easily.

* copyedit

Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>

* Implement prerequisite cycle detection (#219)

* Support attribute reference lookups (#215)

This adds support for slash-delimited paths in clause attributes,
bucketBy, etc. It does not do anything related to private attribute
redaction because none of the U2C event logic is implemented yet.

* Implement segment recursion and cycle detection (#220)

Clauses in segment rules are now allowed to reference segments. To
prevent an infinite recursion edge case, we implement a similar cycle
detection mechanism as used on prerequisites.

* Update event logic to support users to context change (#221)

* Add legacy user-type support to the contract tests (#222)

* Remove inline user configuration option (#223)

* Add context_ configuration options (#224)

These new context_ configuration options are meant to replace the
historic user_ options. If both are provided, the context_ variant will
take precedence.

* Add support for flag context targets (#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (#228)

A few of our internal models maintain arrays of values. These arrays can
frequently be checked to see if they contain specific values.

Since set lookups are much faster than array lookups, this commit
changes the internal structure to a set for the values stored in Target
and SegmentTarget.

* Add secure mode hash to contract tests (#229)

* Update big segment support for users to context (#226)

To support the users to context change for big segments, this commit
makes the following changes:

- Introduces a new `Segment.unboundedContextKind` attribute. This will
default to `LDContext::KIND_DEFAULT` and is only referenced when
`Segment.unbounded` is true.

- With the creation of multi-kind contexts, a single evaluation may
result in multiple queries to the big segment store. This is reflected
in the changes to the `EvalResult` processing.

* Drop support for ruby 2.6 (#227)

Ruby 2.6 went EOL in March 2022. We originally didn't drop support for
it as doing so would require dropping support for jRuby as well.
However, jRuby recently released 9.4 which is Ruby 2.7+ compatible.

* Update remaining references from user to contexts (#231)

There are multiple places throughout the code where we are still
referencing users. I have tried to update all the places where a rename
seems reasonable or appropriate. There is still some work to do in the
test flag builders, but that will be done in a subsequent commit.

* Remove new relic integration (#233)

The new relic integration was removed many versions ago but a small
trace remained behind.

* Rename config option private_attribute_names (#234)

Co-authored-by: Eli Bishop <eli@launchdarkly.com>

* Update test data integration to support contexts (#232)

* improve data model validation logging; allow missing/empty attribute for segmentMatch (#236)

* Fix JSON serialization failure (#237)

When we introduced models for the flag and segment data, we added
to_json methods which proxy to the underlying to_json method provided by
the `json` gem.

We defined the method with a variadic parameter, but we failed to unpack
it when passing it on to the underlying implementation. This resulted in
a serialization failure which prevented the redis data store from
initializing.

* fix: Bump eventsource to resolve header parsing (#239)

The underlying event source library had an issue where, in certain
environments, content-type header detection was failing.

This was resolved in v2.2.2 of the event source gem.

* Add key to error log for invalid context during variation call for easier debugging (#214)

* feat: Add support for payload filtering (#238)

* feat: Add data source status provider support (#240)

The client instance will now provide access to a
`data_source_status_provider`. This provider allows developers to
retrieve the status of the SDK on demand, or asynchronously by
registering listeners.

* test: Skip database integration tests by default (#241)

The full unit test suite includes tests relying on externally instances
of Redis, Consult, and DynamoDB.

By default, we do not want to run these tests. Rather, they should be
opt-in by setting the environment variable `LD_SKIP_DATABASE_TESTS=0`.

* feat: Introduce flag change tracker api (#242)

The client instance will now provide access to a `flag_tracker`. This
tracker allows developers to be notified when a flag configuration
changes (or optionally when the /value/ of a flag changes for a
particular context).

* ci: Add code coverage generation (#244)

* feat: Add support for data store status monitoring (#243)

The client instance will now provide access to a
`data_store_status_provider`. This provider allows developers to
retrieve the data store status of the SDK on demand, or asynchronously
by registering listeners.

* Fix monitoring_enabled? access

---------

Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: LaunchDarklyCI <dev@launchdarkly.com>
Co-authored-by: Jacob Smith <jacob@jacobsmith.io>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: hroederld <hroeder@launchdarkly.com>
Co-authored-by: Kerrie Martinez <kyee@launchdarkly.com>
Co-authored-by: pellyg-ld <gpelly@launchdarkly.com>
Co-authored-by: Sam Stokes <sstokes@launchdarkly.com>
Co-authored-by: LaunchDarklyReleaseBot <launchdarklyreleasebot@launchdarkly.com>
Co-authored-by: Ember Stevens <ember.stevens@launchdarkly.com>
Co-authored-by: ember-stevens <79482775+ember-stevens@users.noreply.github.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Matthew M. Keeler <keelerm84@gmail.com>
Co-authored-by: Ben Levy <benjaminlevy007@gmail.com>
Co-authored-by: Ben Levy <ben@foxhound.systems>
Co-authored-by: Matthew M. Keeler <mkeeler@launchdarkly.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
Co-authored-by: Matt Hooks <46452201+matt-dutchie@users.noreply.github.com>
@conrad
Copy link

conrad commented Feb 29, 2024

Just to share. We just experienced something very similar where a controller instantiated a class with a create call on the client multiple times--same logs and only getting default values on the impacted flags. The issue ended up being that we had done the Rails SDK configuration with the initializer, but hadn't done the Puma on_worker_boot instantiation as well.

The layout of the docs here could be a little better to make it more clear that you may have to do multiple of the collapsed options 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants