Skip to content

Commit

Permalink
prepare 7.0.1 release (launchdarkly#208)
Browse files Browse the repository at this point in the history
* 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 (launchdarkly#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 (launchdarkly#134)

* fail fast for nil SDK key when appropriate

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

* Only shutdown the Redis pool if it is owned by the SDK (launchdarkly#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 (launchdarkly#138)

* update to json 2.3.1 (launchdarkly#139)

* update json dep to 2.3.x to fix CVE

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

* try fixing release metadata

* update the default base url (launchdarkly#144)

* revert renames of feature_store & update_processor

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

* update dependencies and add CI for ruby 3 (launchdarkly#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 (launchdarkly#147)

* don't send event for nil user evaluation

* remove lockfile (launchdarkly#148)

* rm redundant nil check

* Experiment Allocation Changes (launchdarkly#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 (launchdarkly#151)

The in_experiment attribute was added to reasons as part of launchdarkly#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 (launchdarkly#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 (launchdarkly#153)

* add log warnings for nil/empty user key

* rm warning for empty string key

* fix test

* diagnostic events should respect HTTPS_PROXY (launchdarkly#154)

* minor test simplification (launchdarkly#155)

* allow higher minor versions of json and http gems

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

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

* enable verbose rspec output

* fix socket factory tests

* restore log suppression

* Replacing deprecated circleci image usage (launchdarkly#159)

* use Releaser v2 config (launchdarkly#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 (launchdarkly#163)

* use ruby-eventsource 2.1.1 for fix of sc-123850 and sc-125504 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#173)

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

* comments

* add test for cache expiration

* use TestData in our own tests (launchdarkly#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 (launchdarkly#184)

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

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

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

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

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

* Add contract tests (launchdarkly#178)

* Fix string interpolation in log message (launchdarkly#187)

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

* Remove Hakiri badge from README (launchdarkly#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 (launchdarkly#190)

* master -> main

* update ruby-eventsource version for parsing efficiency fix

* miscellaneous optimizations for event processing (launchdarkly#193)

* Drop support for EOL ruby versions (launchdarkly#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 (launchdarkly#195)

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

* Update rubocop and enable in CI (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#201)

* Initial creation of LDContext (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#219)

* Support attribute reference lookups (launchdarkly#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 (launchdarkly#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 (launchdarkly#221)

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

* Remove inline user configuration option (launchdarkly#223)

* Add context_ configuration options (launchdarkly#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 (launchdarkly#225)

* Bump diplomat

* Bump redis

* Remove oga

* Bump connection_pool

* Favor set for faster target lookups (launchdarkly#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 (launchdarkly#229)

* Update big segment support for users to context (launchdarkly#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 (launchdarkly#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 (launchdarkly#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 (launchdarkly#233)

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

* Rename config option private_attribute_names (launchdarkly#234)

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

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

* improve data model validation logging; allow missing/empty attribute for segmentMatch (launchdarkly#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>
  • Loading branch information
20 people authored Jan 19, 2023
1 parent 199b65c commit 25299b7
Show file tree
Hide file tree
Showing 7 changed files with 353 additions and 31 deletions.
8 changes: 4 additions & 4 deletions lib/ldclient-rb/impl/evaluator_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,21 @@ module EvaluatorHelpers
# @param flag [LaunchDarkly::Impl::Model::FeatureFlag]
# @param reason [LaunchDarkly::EvaluationReason]
#
def self.evaluation_detail_for_off_variation(flag, reason, logger = nil)
def self.evaluation_detail_for_off_variation(flag, reason)
index = flag.off_variation
index.nil? ? EvaluationDetail.new(nil, nil, reason) : evaluation_detail_for_variation(flag, index, reason, logger)
index.nil? ? EvaluationDetail.new(nil, nil, reason) : evaluation_detail_for_variation(flag, index, reason)
end

#
# @param flag [LaunchDarkly::Impl::Model::FeatureFlag]
# @param index [Integer]
# @param reason [LaunchDarkly::EvaluationReason]
#
def self.evaluation_detail_for_variation(flag, index, reason, logger = nil)
def self.evaluation_detail_for_variation(flag, index, reason)
vars = flag.variations
if index < 0 || index >= vars.length
logger.error("[LDClient] Data inconsistency in feature flag \"#{flag.key}\": invalid variation index") unless logger.nil?
EvaluationDetail.new(nil, nil, EvaluationReason::error(EvaluationReason::ERROR_MALFORMED_FLAG))
# This error condition has already been logged at the time we received the flag data - see model/feature_flag.rb
else
EvaluationDetail.new(vars[index], index, reason)
end
Expand Down
16 changes: 11 additions & 5 deletions lib/ldclient-rb/impl/model/clause.rb
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
require "ldclient-rb/reference"


# See serialization.rb for implementation notes on the data model classes.

module LaunchDarkly
module Impl
module Model
class Clause
def initialize(data, logger)
def initialize(data, errors_out = nil)
@data = data
@context_kind = data[:contextKind]
@attribute = (@context_kind.nil? || @context_kind.empty?) ? Reference.create_literal(data[:attribute]) : Reference.create(data[:attribute])
unless logger.nil? || @attribute.error.nil?
logger.error("[LDClient] Data inconsistency in feature flag: #{@attribute.error}")
end
@op = data[:op].to_sym
if @op == :segmentMatch
@attribute = nil
else
@attribute = (@context_kind.nil? || @context_kind.empty?) ? Reference.create_literal(data[:attribute]) : Reference.create(data[:attribute])
unless errors_out.nil? || @attribute.error.nil?
errors_out << "clause has invalid attribute: #{@attribute.error}"
end
end
@values = data[:values] || []
@negate = !!data[:negate]
end
Expand Down
55 changes: 37 additions & 18 deletions lib/ldclient-rb/impl/model/feature_flag.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@

# See serialization.rb for implementation notes on the data model classes.

def check_variation_range(flag, errors_out, variation, description)
unless flag.nil? || errors_out.nil? || variation.nil?
if variation < 0 || variation >= flag.variations.length
errors_out << "#{description} has invalid variation index"
end
end
end

module LaunchDarkly
module Impl
module Model
Expand All @@ -12,6 +20,7 @@ class FeatureFlag
# @param logger [Logger|nil]
def initialize(data, logger = nil)
raise ArgumentError, "expected hash but got #{data.class}" unless data.is_a?(Hash)
errors = []
@data = data
@key = data[:key]
@version = data[:version]
Expand All @@ -20,24 +29,30 @@ def initialize(data, logger = nil)
@variations = data[:variations] || []
@on = !!data[:on]
fallthrough = data[:fallthrough] || {}
@fallthrough = VariationOrRollout.new(fallthrough[:variation], fallthrough[:rollout])
@fallthrough = VariationOrRollout.new(fallthrough[:variation], fallthrough[:rollout], self, errors, "fallthrough")
@off_variation = data[:offVariation]
check_variation_range(self, errors, @off_variation, "off variation")
@prerequisites = (data[:prerequisites] || []).map do |prereq_data|
Prerequisite.new(prereq_data, self, logger)
Prerequisite.new(prereq_data, self, errors)
end
@targets = (data[:targets] || []).map do |target_data|
Target.new(target_data, self, logger)
Target.new(target_data, self, errors)
end
@context_targets = (data[:contextTargets] || []).map do |target_data|
Target.new(target_data, self, logger)
Target.new(target_data, self, errors)
end
@rules = (data[:rules] || []).map.with_index do |rule_data, index|
FlagRule.new(rule_data, index, self, logger)
FlagRule.new(rule_data, index, self, errors)
end
@salt = data[:salt]
@off_result = EvaluatorHelpers.evaluation_detail_for_off_variation(self, EvaluationReason::off, logger)
@off_result = EvaluatorHelpers.evaluation_detail_for_off_variation(self, EvaluationReason::off)
@fallthrough_results = Preprocessor.precompute_multi_variation_results(self,
EvaluationReason::fallthrough(false), EvaluationReason::fallthrough(true))
unless logger.nil?
errors.each do |message|
logger.error("[LDClient] Data inconsistency in feature flag \"#{@key}\": #{message}")
end
end
end

# @return [Hash]
Expand Down Expand Up @@ -93,12 +108,13 @@ def to_json(*a)
end

class Prerequisite
def initialize(data, flag, logger)
def initialize(data, flag, errors_out = nil)
@data = data
@key = data[:key]
@variation = data[:variation]
@failure_result = EvaluatorHelpers.evaluation_detail_for_off_variation(flag,
EvaluationReason::prerequisite_failed(@key), logger)
EvaluationReason::prerequisite_failed(@key))
check_variation_range(flag, errors_out, @variation, "prerequisite")
end

# @return [Hash]
Expand All @@ -112,13 +128,14 @@ def initialize(data, flag, logger)
end

class Target
def initialize(data, flag, logger)
def initialize(data, flag, errors_out = nil)
@kind = data[:contextKind] || LDContext::KIND_DEFAULT
@data = data
@values = Set.new(data[:values] || [])
@variation = data[:variation]
@match_result = EvaluatorHelpers.evaluation_detail_for_variation(flag,
data[:variation], EvaluationReason::target_match, logger)
data[:variation], EvaluationReason::target_match)
check_variation_range(flag, errors_out, @variation, "target")
end

# @return [String]
Expand All @@ -134,12 +151,12 @@ def initialize(data, flag, logger)
end

class FlagRule
def initialize(data, rule_index, flag, logger)
def initialize(data, rule_index, flag, errors_out = nil)
@data = data
@clauses = (data[:clauses] || []).map do |clause_data|
Clause.new(clause_data, logger)
Clause.new(clause_data, errors_out)
end
@variation_or_rollout = VariationOrRollout.new(data[:variation], data[:rollout])
@variation_or_rollout = VariationOrRollout.new(data[:variation], data[:rollout], flag, errors_out, 'rule')
rule_id = data[:id]
match_reason = EvaluationReason::rule_match(rule_index, rule_id)
match_reason_in_experiment = EvaluationReason::rule_match(rule_index, rule_id, true)
Expand All @@ -157,9 +174,10 @@ def initialize(data, rule_index, flag, logger)
end

class VariationOrRollout
def initialize(variation, rollout_data)
def initialize(variation, rollout_data, flag = nil, errors_out = nil, description = nil)
@variation = variation
@rollout = rollout_data.nil? ? nil : Rollout.new(rollout_data)
check_variation_range(flag, errors_out, variation, description)
@rollout = rollout_data.nil? ? nil : Rollout.new(rollout_data, flag, errors_out, description)
end

# @return [Integer|nil]
Expand All @@ -169,9 +187,9 @@ def initialize(variation, rollout_data)
end

class Rollout
def initialize(data)
def initialize(data, flag = nil, errors_out = nil, description = nil)
@context_kind = data[:contextKind]
@variations = (data[:variations] || []).map { |v| WeightedVariation.new(v) }
@variations = (data[:variations] || []).map { |v| WeightedVariation.new(v, flag, errors_out, description) }
@bucket_by = data[:bucketBy]
@kind = data[:kind]
@is_experiment = @kind == "experiment"
Expand All @@ -193,10 +211,11 @@ def initialize(data)
end

class WeightedVariation
def initialize(data)
def initialize(data, flag = nil, errors_out = nil, description = nil)
@variation = data[:variation]
@weight = data[:weight]
@untracked = !!data[:untracked]
check_variation_range(flag, errors_out, @variation, description)
end

# @return [Integer]
Expand Down
12 changes: 9 additions & 3 deletions lib/ldclient-rb/impl/model/segment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class Segment
# @param logger [Logger|nil]
def initialize(data, logger = nil)
raise ArgumentError, "expected hash but got #{data.class}" unless data.is_a?(Hash)
errors = []
@data = data
@key = data[:key]
@version = data[:version]
Expand All @@ -26,12 +27,17 @@ def initialize(data, logger = nil)
SegmentTarget.new(target_data)
end
@rules = (data[:rules] || []).map do |rule_data|
SegmentRule.new(rule_data, logger)
SegmentRule.new(rule_data, errors)
end
@unbounded = !!data[:unbounded]
@unbounded_context_kind = data[:unboundedContextKind] || LDContext::KIND_DEFAULT
@generation = data[:generation]
@salt = data[:salt]
unless logger.nil?
errors.each do |message|
logger.error("[LDClient] Data inconsistency in segment \"#{@key}\": #{message}")
end
end
end

# @return [Hash]
Expand Down Expand Up @@ -98,10 +104,10 @@ def initialize(data)
end

class SegmentRule
def initialize(data, logger)
def initialize(data, errors_out = nil)
@data = data
@clauses = (data[:clauses] || []).map do |clause_data|
Clause.new(clause_data, logger)
Clause.new(clause_data, errors_out)
end
@weight = data[:weight]
@bucket_by = data[:bucketBy]
Expand Down
2 changes: 1 addition & 1 deletion lib/ldclient-rb/impl/model/serialization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ module Model
# @param kind [Hash] normally either FEATURES or SEGMENTS
# @param input [object] a JSON string or a parsed hash (or a data model object, in which case
# we'll just return the original object)
# @param logger [Logger|nil] logs warnings if there are any data validation problems
# @param logger [Logger|nil] logs errors if there are any data validation problems
# @return [Object] the flag or segment (or, for an unknown data kind, the data as a hash)
def self.deserialize(kind, input, logger = nil)
return nil if input.nil?
Expand Down
16 changes: 16 additions & 0 deletions spec/capturing_logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
require "stringio"

class CapturingLogger
def initialize
@output = StringIO.new
@logger = Logger.new(@output)
end

def output
@output.string
end

def method_missing(meth, *args, &block)
@logger.send(meth, *args, &block)
end
end
Loading

0 comments on commit 25299b7

Please sign in to comment.