Skip to content

Commit 25299b7

Browse files
LaunchDarklyReleaseBoteli-darklybwoskow-ldLaunchDarklyCIjacobthemyth
authored
prepare 7.0.1 release (#208)
* 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>
1 parent 199b65c commit 25299b7

File tree

7 files changed

+353
-31
lines changed

7 files changed

+353
-31
lines changed

lib/ldclient-rb/impl/evaluator_helpers.rb

+4-4
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,21 @@ module EvaluatorHelpers
1010
# @param flag [LaunchDarkly::Impl::Model::FeatureFlag]
1111
# @param reason [LaunchDarkly::EvaluationReason]
1212
#
13-
def self.evaluation_detail_for_off_variation(flag, reason, logger = nil)
13+
def self.evaluation_detail_for_off_variation(flag, reason)
1414
index = flag.off_variation
15-
index.nil? ? EvaluationDetail.new(nil, nil, reason) : evaluation_detail_for_variation(flag, index, reason, logger)
15+
index.nil? ? EvaluationDetail.new(nil, nil, reason) : evaluation_detail_for_variation(flag, index, reason)
1616
end
1717

1818
#
1919
# @param flag [LaunchDarkly::Impl::Model::FeatureFlag]
2020
# @param index [Integer]
2121
# @param reason [LaunchDarkly::EvaluationReason]
2222
#
23-
def self.evaluation_detail_for_variation(flag, index, reason, logger = nil)
23+
def self.evaluation_detail_for_variation(flag, index, reason)
2424
vars = flag.variations
2525
if index < 0 || index >= vars.length
26-
logger.error("[LDClient] Data inconsistency in feature flag \"#{flag.key}\": invalid variation index") unless logger.nil?
2726
EvaluationDetail.new(nil, nil, EvaluationReason::error(EvaluationReason::ERROR_MALFORMED_FLAG))
27+
# This error condition has already been logged at the time we received the flag data - see model/feature_flag.rb
2828
else
2929
EvaluationDetail.new(vars[index], index, reason)
3030
end

lib/ldclient-rb/impl/model/clause.rb

+11-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
1+
require "ldclient-rb/reference"
2+
13

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

46
module LaunchDarkly
57
module Impl
68
module Model
79
class Clause
8-
def initialize(data, logger)
10+
def initialize(data, errors_out = nil)
911
@data = data
1012
@context_kind = data[:contextKind]
11-
@attribute = (@context_kind.nil? || @context_kind.empty?) ? Reference.create_literal(data[:attribute]) : Reference.create(data[:attribute])
12-
unless logger.nil? || @attribute.error.nil?
13-
logger.error("[LDClient] Data inconsistency in feature flag: #{@attribute.error}")
14-
end
1513
@op = data[:op].to_sym
14+
if @op == :segmentMatch
15+
@attribute = nil
16+
else
17+
@attribute = (@context_kind.nil? || @context_kind.empty?) ? Reference.create_literal(data[:attribute]) : Reference.create(data[:attribute])
18+
unless errors_out.nil? || @attribute.error.nil?
19+
errors_out << "clause has invalid attribute: #{@attribute.error}"
20+
end
21+
end
1622
@values = data[:values] || []
1723
@negate = !!data[:negate]
1824
end

lib/ldclient-rb/impl/model/feature_flag.rb

+37-18
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@
44

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

7+
def check_variation_range(flag, errors_out, variation, description)
8+
unless flag.nil? || errors_out.nil? || variation.nil?
9+
if variation < 0 || variation >= flag.variations.length
10+
errors_out << "#{description} has invalid variation index"
11+
end
12+
end
13+
end
14+
715
module LaunchDarkly
816
module Impl
917
module Model
@@ -12,6 +20,7 @@ class FeatureFlag
1220
# @param logger [Logger|nil]
1321
def initialize(data, logger = nil)
1422
raise ArgumentError, "expected hash but got #{data.class}" unless data.is_a?(Hash)
23+
errors = []
1524
@data = data
1625
@key = data[:key]
1726
@version = data[:version]
@@ -20,24 +29,30 @@ def initialize(data, logger = nil)
2029
@variations = data[:variations] || []
2130
@on = !!data[:on]
2231
fallthrough = data[:fallthrough] || {}
23-
@fallthrough = VariationOrRollout.new(fallthrough[:variation], fallthrough[:rollout])
32+
@fallthrough = VariationOrRollout.new(fallthrough[:variation], fallthrough[:rollout], self, errors, "fallthrough")
2433
@off_variation = data[:offVariation]
34+
check_variation_range(self, errors, @off_variation, "off variation")
2535
@prerequisites = (data[:prerequisites] || []).map do |prereq_data|
26-
Prerequisite.new(prereq_data, self, logger)
36+
Prerequisite.new(prereq_data, self, errors)
2737
end
2838
@targets = (data[:targets] || []).map do |target_data|
29-
Target.new(target_data, self, logger)
39+
Target.new(target_data, self, errors)
3040
end
3141
@context_targets = (data[:contextTargets] || []).map do |target_data|
32-
Target.new(target_data, self, logger)
42+
Target.new(target_data, self, errors)
3343
end
3444
@rules = (data[:rules] || []).map.with_index do |rule_data, index|
35-
FlagRule.new(rule_data, index, self, logger)
45+
FlagRule.new(rule_data, index, self, errors)
3646
end
3747
@salt = data[:salt]
38-
@off_result = EvaluatorHelpers.evaluation_detail_for_off_variation(self, EvaluationReason::off, logger)
48+
@off_result = EvaluatorHelpers.evaluation_detail_for_off_variation(self, EvaluationReason::off)
3949
@fallthrough_results = Preprocessor.precompute_multi_variation_results(self,
4050
EvaluationReason::fallthrough(false), EvaluationReason::fallthrough(true))
51+
unless logger.nil?
52+
errors.each do |message|
53+
logger.error("[LDClient] Data inconsistency in feature flag \"#{@key}\": #{message}")
54+
end
55+
end
4156
end
4257

4358
# @return [Hash]
@@ -93,12 +108,13 @@ def to_json(*a)
93108
end
94109

95110
class Prerequisite
96-
def initialize(data, flag, logger)
111+
def initialize(data, flag, errors_out = nil)
97112
@data = data
98113
@key = data[:key]
99114
@variation = data[:variation]
100115
@failure_result = EvaluatorHelpers.evaluation_detail_for_off_variation(flag,
101-
EvaluationReason::prerequisite_failed(@key), logger)
116+
EvaluationReason::prerequisite_failed(@key))
117+
check_variation_range(flag, errors_out, @variation, "prerequisite")
102118
end
103119

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

114130
class Target
115-
def initialize(data, flag, logger)
131+
def initialize(data, flag, errors_out = nil)
116132
@kind = data[:contextKind] || LDContext::KIND_DEFAULT
117133
@data = data
118134
@values = Set.new(data[:values] || [])
119135
@variation = data[:variation]
120136
@match_result = EvaluatorHelpers.evaluation_detail_for_variation(flag,
121-
data[:variation], EvaluationReason::target_match, logger)
137+
data[:variation], EvaluationReason::target_match)
138+
check_variation_range(flag, errors_out, @variation, "target")
122139
end
123140

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

136153
class FlagRule
137-
def initialize(data, rule_index, flag, logger)
154+
def initialize(data, rule_index, flag, errors_out = nil)
138155
@data = data
139156
@clauses = (data[:clauses] || []).map do |clause_data|
140-
Clause.new(clause_data, logger)
157+
Clause.new(clause_data, errors_out)
141158
end
142-
@variation_or_rollout = VariationOrRollout.new(data[:variation], data[:rollout])
159+
@variation_or_rollout = VariationOrRollout.new(data[:variation], data[:rollout], flag, errors_out, 'rule')
143160
rule_id = data[:id]
144161
match_reason = EvaluationReason::rule_match(rule_index, rule_id)
145162
match_reason_in_experiment = EvaluationReason::rule_match(rule_index, rule_id, true)
@@ -157,9 +174,10 @@ def initialize(data, rule_index, flag, logger)
157174
end
158175

159176
class VariationOrRollout
160-
def initialize(variation, rollout_data)
177+
def initialize(variation, rollout_data, flag = nil, errors_out = nil, description = nil)
161178
@variation = variation
162-
@rollout = rollout_data.nil? ? nil : Rollout.new(rollout_data)
179+
check_variation_range(flag, errors_out, variation, description)
180+
@rollout = rollout_data.nil? ? nil : Rollout.new(rollout_data, flag, errors_out, description)
163181
end
164182

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

171189
class Rollout
172-
def initialize(data)
190+
def initialize(data, flag = nil, errors_out = nil, description = nil)
173191
@context_kind = data[:contextKind]
174-
@variations = (data[:variations] || []).map { |v| WeightedVariation.new(v) }
192+
@variations = (data[:variations] || []).map { |v| WeightedVariation.new(v, flag, errors_out, description) }
175193
@bucket_by = data[:bucketBy]
176194
@kind = data[:kind]
177195
@is_experiment = @kind == "experiment"
@@ -193,10 +211,11 @@ def initialize(data)
193211
end
194212

195213
class WeightedVariation
196-
def initialize(data)
214+
def initialize(data, flag = nil, errors_out = nil, description = nil)
197215
@variation = data[:variation]
198216
@weight = data[:weight]
199217
@untracked = !!data[:untracked]
218+
check_variation_range(flag, errors_out, @variation, description)
200219
end
201220

202221
# @return [Integer]

lib/ldclient-rb/impl/model/segment.rb

+9-3
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ class Segment
1212
# @param logger [Logger|nil]
1313
def initialize(data, logger = nil)
1414
raise ArgumentError, "expected hash but got #{data.class}" unless data.is_a?(Hash)
15+
errors = []
1516
@data = data
1617
@key = data[:key]
1718
@version = data[:version]
@@ -26,12 +27,17 @@ def initialize(data, logger = nil)
2627
SegmentTarget.new(target_data)
2728
end
2829
@rules = (data[:rules] || []).map do |rule_data|
29-
SegmentRule.new(rule_data, logger)
30+
SegmentRule.new(rule_data, errors)
3031
end
3132
@unbounded = !!data[:unbounded]
3233
@unbounded_context_kind = data[:unboundedContextKind] || LDContext::KIND_DEFAULT
3334
@generation = data[:generation]
3435
@salt = data[:salt]
36+
unless logger.nil?
37+
errors.each do |message|
38+
logger.error("[LDClient] Data inconsistency in segment \"#{@key}\": #{message}")
39+
end
40+
end
3541
end
3642

3743
# @return [Hash]
@@ -98,10 +104,10 @@ def initialize(data)
98104
end
99105

100106
class SegmentRule
101-
def initialize(data, logger)
107+
def initialize(data, errors_out = nil)
102108
@data = data
103109
@clauses = (data[:clauses] || []).map do |clause_data|
104-
Clause.new(clause_data, logger)
110+
Clause.new(clause_data, errors_out)
105111
end
106112
@weight = data[:weight]
107113
@bucket_by = data[:bucketBy]

lib/ldclient-rb/impl/model/serialization.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ module Model
3737
# @param kind [Hash] normally either FEATURES or SEGMENTS
3838
# @param input [object] a JSON string or a parsed hash (or a data model object, in which case
3939
# we'll just return the original object)
40-
# @param logger [Logger|nil] logs warnings if there are any data validation problems
40+
# @param logger [Logger|nil] logs errors if there are any data validation problems
4141
# @return [Object] the flag or segment (or, for an unknown data kind, the data as a hash)
4242
def self.deserialize(kind, input, logger = nil)
4343
return nil if input.nil?

spec/capturing_logger.rb

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
require "stringio"
2+
3+
class CapturingLogger
4+
def initialize
5+
@output = StringIO.new
6+
@logger = Logger.new(@output)
7+
end
8+
9+
def output
10+
@output.string
11+
end
12+
13+
def method_missing(meth, *args, &block)
14+
@logger.send(meth, *args, &block)
15+
end
16+
end

0 commit comments

Comments
 (0)