Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions libs/server-sdk/src/evaluation/bucketing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
BucketPrefix::BucketPrefix(Seed seed) : prefix_(seed) {}

BucketPrefix::BucketPrefix(std::string key, std::string salt)
: prefix_(KeyAndSalt{key, salt}) {}

Check warning on line 28 in libs/server-sdk/src/evaluation/bucketing.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/bucketing.cpp:28:31 [performance-unnecessary-value-param]

parameter 'salt' is passed by value and only copied once; consider moving it to avoid unnecessary copies

Check warning on line 28 in libs/server-sdk/src/evaluation/bucketing.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/bucketing.cpp:28:26 [performance-unnecessary-value-param]

parameter 'key' is passed by value and only copied once; consider moving it to avoid unnecessary copies

std::ostream& operator<<(std::ostream& os, BucketPrefix const& prefix) {
std::visit(
Expand Down Expand Up @@ -98,7 +98,7 @@
return key;
}

std::optional<double> ContextHash(Value const& value, BucketPrefix prefix) {

Check warning on line 101 in libs/server-sdk/src/evaluation/bucketing.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/bucketing.cpp:101:68 [performance-unnecessary-value-param]

the parameter 'prefix' is copied for each invocation but only used as a const reference; consider making it a const reference
using namespace launchdarkly::encoding;

std::optional<std::string> id = BucketValue(value);
Expand All @@ -118,9 +118,9 @@

try {
unsigned long long as_number =
std::stoull(sha1hash_hexed_first_15.data(), nullptr, /* base */ 16);

Check warning on line 121 in libs/server-sdk/src/evaluation/bucketing.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/bucketing.cpp:121:25 [readability-redundant-string-cstr]

redundant call to 'data'

double as_double = static_cast<double>(as_number);

Check warning on line 123 in libs/server-sdk/src/evaluation/bucketing.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/bucketing.cpp:123:9 [modernize-use-auto]

use auto when initializing with a cast to avoid duplicating the type name
return as_double / kBucketHashScale;

} catch (std::invalid_argument) {
Expand Down Expand Up @@ -149,14 +149,11 @@
return std::trunc(f) == f;
}

tl::expected<BucketResult, Error> Variation(

Check warning on line 152 in libs/server-sdk/src/evaluation/bucketing.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/bucketing.cpp:152:35 [readability-function-cognitive-complexity]

function 'Variation' has cognitive complexity of 28 (threshold 25)
Flag::VariationOrRollout const& vr,
std::string const& flag_key,
Context const& context,
std::optional<std::string> const& salt) {
if (!salt) {
return tl::make_unexpected(Error::MissingSalt(flag_key));
}
return std::visit(
[&](auto&& arg) -> tl::expected<BucketResult, Error> {
using T = std::decay_t<decltype(arg)>;
Expand All @@ -175,6 +172,11 @@
bool is_experiment =
arg.kind == Flag::Rollout::Kind::kExperiment;

// Only a rollout without a seed uses the salt.
if (!arg.seed && !salt) {
return tl::make_unexpected(Error::MissingSalt(flag_key));
}

std::optional<BucketPrefix> prefix =
arg.seed ? BucketPrefix(*arg.seed)
: BucketPrefix(flag_key, *salt);
Expand Down
3 changes: 2 additions & 1 deletion libs/server-sdk/src/evaluation/bucketing.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ class BucketResult {
* @param variation_or_rollout Variation or rollout.
* @param flag_key Key of flag.
* @param context Context to bucket.
* @param salt Salt to use when bucketing.
* @param salt Salt to use when bucketing. Only a rollout without a seed
* needs a salt.
* @return A BucketResult on success, or an error if bucketing failed.
*/
tl::expected<BucketResult, Error> Variation(
Expand Down
13 changes: 7 additions & 6 deletions libs/server-sdk/src/evaluation/rules.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@
}

integrations::Membership const* membership = stack.FindMembership(key);
if (!membership) {

Check warning on line 69 in libs/server-sdk/src/evaluation/rules.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/rules.cpp:69:10 [readability-implicit-bool-conversion]

implicit conversion 'const integrations::Membership *' -> bool
auto* store = stack.BigSegmentStore();
if (!store) {

Check warning on line 71 in libs/server-sdk/src/evaluation/rules.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/rules.cpp:71:14 [readability-implicit-bool-conversion]

implicit conversion 'data_components::BigSegmentStoreWrapper *' -> bool
stack.RecordBigSegmentsStatus(
EvaluationReason::BigSegmentsStatus::kNotConfigured);
return false;
Expand Down Expand Up @@ -118,7 +118,7 @@
data_interfaces::IStore const& store,
EvaluationStack& stack,
std::string const& key,
std::string const& salt) {
std::optional<std::string> const& salt) {
for (Clause const& clause : rule.clauses) {
auto maybe_match = Match(clause, context, store, stack);
if (!maybe_match) {
Expand All @@ -130,14 +130,18 @@
}

if (rule.weight && rule.weight >= 0.0) {
BucketPrefix prefix(key, salt);
// Only a rule with a weight uses the salt.
if (!salt) {
return tl::make_unexpected(Error::MissingSalt(key));
}
BucketPrefix prefix(key, *salt);
auto maybe_bucket = Bucket(context, rule.bucketBy, prefix, false,
rule.rolloutContextKind);
if (!maybe_bucket) {
return tl::make_unexpected(maybe_bucket.error());
}
auto [bucket, ignored] = *maybe_bucket;
return bucket < (*rule.weight / kBucketScale);

Check warning on line 144 in libs/server-sdk/src/evaluation/rules.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/src/evaluation/rules.cpp:144:26 [bugprone-narrowing-conversions]

narrowing conversion from 'unsigned long' to 'double'
}

return true;
Expand Down Expand Up @@ -261,11 +265,8 @@
}

for (auto const& rule : segment.rules) {
if (!segment.salt) {
return tl::make_unexpected(Error::MissingSalt(segment.key));
}
tl::expected<bool, Error> maybe_match =
Match(rule, context, store, stack, segment.key, *segment.salt);
Match(rule, context, store, stack, segment.key, segment.salt);
if (!maybe_match) {
return tl::make_unexpected(maybe_match.error());
}
Expand Down
3 changes: 2 additions & 1 deletion libs/server-sdk/src/evaluation/rules.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

#include <tl/expected.hpp>

#include <optional>
#include <string>

namespace launchdarkly::server_side::evaluation {
Expand All @@ -31,7 +32,7 @@ namespace launchdarkly::server_side::evaluation {
data_interfaces::IStore const& store,
EvaluationStack& stack,
std::string const& key,
std::string const& salt);
std::optional<std::string> const& salt);

[[nodiscard]] tl::expected<bool, Error> MatchSegment(
data_model::Clause const&,
Expand Down
125 changes: 125 additions & 0 deletions libs/server-sdk/tests/evaluator_tests.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "data_components/memory_store/memory_store.hpp"
#include "evaluation/evaluator.hpp"
#include "test_store.hpp"

Expand Down Expand Up @@ -28,7 +29,7 @@
Logger logger_;

protected:
std::unique_ptr<data_interfaces::IStore const> store_;

Check warning on line 32 in libs/server-sdk/tests/evaluator_tests.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/server-sdk/tests/evaluator_tests.cpp:32:52 [cppcoreguidelines-non-private-member-variables-in-classes]

member variable 'store_' has protected visibility
evaluation::Evaluator eval_;
};

Expand Down Expand Up @@ -276,3 +277,127 @@
t.join();
}
}

// Evaluates flags and segments that have no salt. The parameter is the salt
// property of each flag and segment: omitted, or null.
class EvaluatorWithoutSaltTests : public ::testing::TestWithParam<char const*> {
public:
EvaluatorWithoutSaltTests()
: logger_(logging::NullLogger()), eval_(logger_, store_) {
store_.Init({});
}

protected:
// Returns the flag or segment JSON with the salt property of the test
// parameter after the key.
static std::string WithSalt(std::string const& key,
std::string const& rest) {
return R"({"key":")" + key + R"(",)" + GetParam() + rest;
}

data_components::MemoryStore store_;

private:
Logger logger_;

protected:
evaluation::Evaluator eval_;
};

TEST_P(EvaluatorWithoutSaltTests, FixedFallthroughIsNotAnError) {
auto const flag = test_store::Flag(
WithSalt("flag", R"("version":1,"on":true,"variations":["a","b"],
"fallthrough":{"variation":1}})")
.c_str());

// Evaluate a flag that serves a fixed variation from its fallthrough.
auto const detail =
eval_.Evaluate(*flag.item, ContextBuilder().Kind("user", "u").Build());

// The flag serves the variation without a MALFORMED_FLAG error.
ASSERT_FALSE(detail.IsError());
EXPECT_EQ(*detail, Value("b"));
EXPECT_EQ(detail.Reason(), EvaluationReason::Fallthrough(false));
}

TEST_P(EvaluatorWithoutSaltTests, FixedRuleIsNotAnError) {
auto const flag = test_store::Flag(
WithSalt("flag", R"("version":1,"on":true,"variations":["a","b"],
"fallthrough":{"variation":0},
"rules":[{"id":"rule","variation":1,"clauses":[
{"attribute":"key","op":"in","values":["u"]}]}]})")
.c_str());

// Evaluate a flag whose matching rule serves a fixed variation.
auto const detail =
eval_.Evaluate(*flag.item, ContextBuilder().Kind("user", "u").Build());

// The rule serves the variation without a MALFORMED_FLAG error.
ASSERT_FALSE(detail.IsError());
EXPECT_EQ(*detail, Value("b"));
EXPECT_EQ(detail.Reason(), EvaluationReason::RuleMatch(0, "rule", false));
}

TEST_P(EvaluatorWithoutSaltTests, RolloutWithSeedIsNotAnError) {
auto const flag = test_store::Flag(
WithSalt("flag", R"("version":1,"on":true,"variations":["a","b"],
"fallthrough":{"rollout":{"seed":61,"variations":[
{"variation":1,"weight":100000}]}}})")
.c_str());

// Evaluate a flag whose fallthrough is a rollout with a seed. The seed
// replaces the salt when the SDK buckets the context.
auto const detail =
eval_.Evaluate(*flag.item, ContextBuilder().Kind("user", "u").Build());

// The rollout serves its variation without a MALFORMED_FLAG error.
ASSERT_FALSE(detail.IsError());
EXPECT_EQ(*detail, Value("b"));
}

TEST_P(EvaluatorWithoutSaltTests, RolloutWithoutSeedIsMalformed) {
auto const flag = test_store::Flag(
WithSalt("flag", R"("version":1,"on":true,"variations":["a","b"],
"fallthrough":{"rollout":{"variations":[
{"variation":1,"weight":100000}]}}})")
.c_str());

// Evaluate a flag whose fallthrough is a rollout without a seed. The SDK
// has no salt to bucket the context with.
auto const detail =
eval_.Evaluate(*flag.item, ContextBuilder().Kind("user", "u").Build());

// The flag is malformed.
EXPECT_EQ(detail.Reason(), EvaluationReason::MalformedFlag());
}

TEST_P(EvaluatorWithoutSaltTests, SegmentRuleIsNotAnError) {
store_.Upsert("segment",
test_store::Segment(
WithSalt("segment", R"("version":1,"rules":[{"clauses":[
{"attribute":"key","op":"in","values":["u"]}]}]})")
.c_str()));
auto const flag = test_store::Flag(R"({"key":"flag","salt":"salt",
"version":1,"on":true,"variations":["a","b"],
"fallthrough":{"variation":0},
"rules":[{"id":"rule","variation":1,"clauses":[
{"attribute":"","op":"segmentMatch","values":["segment"]}]}]})");

// Evaluate a flag whose rule matches a segment by the segment's rule. The
// segment rule has no weight.
auto const detail =
eval_.Evaluate(*flag.item, ContextBuilder().Kind("user", "u").Build());

// The segment rule matches without a MALFORMED_FLAG error.
ASSERT_FALSE(detail.IsError());
EXPECT_EQ(*detail, Value("b"));
EXPECT_EQ(detail.Reason(), EvaluationReason::RuleMatch(0, "rule", false));
}

INSTANTIATE_TEST_SUITE_P(SaltProperty,
EvaluatorWithoutSaltTests,
::testing::Values("", R"("salt":null,)"),
[](::testing::TestParamInfo<char const*> const& info) {
return std::string(
info.param[0] == '\0' ? "Omitted" : "Null");
});
Loading