Skip to content
Open
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
27 changes: 16 additions & 11 deletions libs/client-sdk/src/client_impl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,15 @@
event_processor_->SendAsync(events::IdentifyEventParams{
std::chrono::system_clock::now(), std::move(context)});

return StartAsyncInternal();
return StartAsyncInternal(/* clear_selector= */ true);
}

void ClientImpl::RestartDataSource() {
auto start_op = [this]() {
void ClientImpl::RestartDataSource(bool clear_selector) {
auto start_op = [this, clear_selector]() {
// The old data source has stopped, so it can't write its selector back.
if (clear_selector) {
flag_manager_.ClearSelector();
}
data_source_ = data_source_factory_();
data_source_->Start();
};
Expand All @@ -178,7 +182,7 @@
data_source_->ShutdownAsync(start_op);
}

std::future<bool> ClientImpl::StartAsyncInternal() {
std::future<bool> ClientImpl::StartAsyncInternal(bool clear_selector) {
auto init_promise = std::make_shared<std::promise<bool>>();
auto init_future = init_promise->get_future();

Expand All @@ -194,13 +198,13 @@
return false; /* keep the change listener */
});

RestartDataSource();
RestartDataSource(clear_selector);

return init_future;
}

std::future<bool> ClientImpl::StartAsync() {
return StartAsyncInternal();
return StartAsyncInternal(/* clear_selector= */ false);
}

bool ClientImpl::Initialized() const {
Expand Down Expand Up @@ -244,11 +248,12 @@
}

template <typename T>
EvaluationDetail<T> ClientImpl::VariationInternal(FlagKey const& key,
Value default_value,
bool check_type,
bool detailed,
std::unordered_set<std::string>* visited) {
EvaluationDetail<T> ClientImpl::VariationInternal(

Check warning on line 251 in libs/client-sdk/src/client_impl.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/client_impl.cpp:251:33 [readability-function-cognitive-complexity]

function 'VariationInternal' has cognitive complexity of 28 (threshold 25)
FlagKey const& key,

Check warning on line 252 in libs/client-sdk/src/client_impl.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/client_impl.cpp:252:5 [bugprone-easily-swappable-parameters]

2 adjacent parameters of 'VariationInternal' of convertible types are easily swapped by mistake
Value default_value,
bool check_type,
bool detailed,
std::unordered_set<std::string>* visited) {
auto desc = flag_manager_.Store().Get(key);

events::FeatureEventParams event = {
Expand Down
15 changes: 8 additions & 7 deletions libs/client-sdk/src/client_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,17 +86,18 @@

flag_manager::IFlagNotifier& FlagNotifier() override;

~ClientImpl();

Check warning on line 89 in libs/client-sdk/src/client_impl.hpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/client_impl.hpp:89:5 [cppcoreguidelines-explicit-virtual-functions]

annotate this function with 'override' or (rarely) 'final'

std::future<bool> StartAsync() override;

private:
template <typename T>
[[nodiscard]] EvaluationDetail<T> VariationInternal(FlagKey const& key,
Value default_value,
bool check_type,
bool detailed,
std::unordered_set<std::string>* visited = nullptr);
[[nodiscard]] EvaluationDetail<T> VariationInternal(
FlagKey const& key,
Value default_value,
bool check_type,
bool detailed,
std::unordered_set<std::string>* visited = nullptr);
void TrackInternal(std::string event_name,
std::optional<Value> data,
std::optional<double> metric_value);
Expand All @@ -110,9 +111,9 @@

void UpdateContextSynchronized(Context context);

void RestartDataSource();
void RestartDataSource(bool clear_selector);

std::future<bool> StartAsyncInternal();
std::future<bool> StartAsyncInternal(bool clear_selector);
Config config_;
Logger logger_;

Expand Down
4 changes: 4 additions & 0 deletions libs/client-sdk/src/flag_manager/flag_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
FlagManager::FlagManager(std::string const& sdk_key,
Logger& logger,
std::size_t max_cached_contexts,
std::shared_ptr<IPersistence> persistence)

Check warning on line 11 in libs/client-sdk/src/flag_manager/flag_manager.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/flag_manager/flag_manager.cpp:11:56 [performance-unnecessary-value-param]

the parameter 'persistence' is copied for each invocation but only used as a const reference; consider making it a const reference
: flag_updater_(flag_store_),
persistence_updater_(sdk_key,
flag_updater_,
Expand Down Expand Up @@ -37,4 +37,8 @@
persistence_updater_.LoadCached(context);
}

void FlagManager::ClearSelector() {
flag_store_.ClearSelector();
}

} // namespace launchdarkly::client_side::flag_manager
3 changes: 3 additions & 0 deletions libs/client-sdk/src/flag_manager/flag_manager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ class FlagManager {

void LoadCache(Context const& context);

/** Forgets the selector, leaving the stored flag data in place. */
void ClearSelector();

private:
FlagStore flag_store_;
FlagUpdater flag_updater_;
Expand Down
38 changes: 38 additions & 0 deletions libs/client-sdk/tests/fdv2_cache_initializer_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

namespace {

class TestPersistence : public IPersistence {

Check warning on line 24 in libs/client-sdk/tests/fdv2_cache_initializer_test.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/tests/fdv2_cache_initializer_test.cpp:24:7 [cppcoreguidelines-virtual-class-destructor]

destructor of 'TestPersistence' is public and non-virtual
public:
using StoreType =
std::map<std::string,
Expand Down Expand Up @@ -74,7 +74,7 @@
auto* change_set = std::get_if<FDv2SourceResult::ChangeSet>(&result->value);
ASSERT_NE(nullptr, change_set);
EXPECT_EQ(ChangeSetType::kFull, change_set->change_set.type);
ASSERT_EQ(1u, change_set->change_set.data.size());

Check warning on line 77 in libs/client-sdk/tests/fdv2_cache_initializer_test.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/tests/fdv2_cache_initializer_test.cpp:77:15 [readability-uppercase-literal-suffix]

integer literal has suffix 'u', which is not uppercase
EXPECT_EQ("flagA", change_set->change_set.data[0].key);
EXPECT_EQ(Value("test"),
change_set->change_set.data[0].item.item->Detail().Value());
Expand Down Expand Up @@ -120,6 +120,44 @@
EXPECT_EQ(ChangeSetType::kNone, change_set->change_set.type);
}

TEST(FDv2CacheInitializerTest, ReadsTheContextItWasBuiltFor) {
auto first = ContextBuilder().Kind("user", "first").Build();
auto second = ContextBuilder().Kind("user", "second").Build();
auto logger = launchdarkly::logging::NullLogger();
auto persistence =
std::make_shared<TestPersistence>(TestPersistence::StoreType{
{kEnvironment,
{{PersistenceEncodeKey(first.CanonicalKey()),
R"({"flagA":{"version":1,"value":"first-value"}})"}}}});
FlagManager flag_manager("the-key", logger, 5, persistence);

// Initialize for the context that has nothing cached.
FDv2CacheInitializer second_initializer(&flag_manager.Cache(), second,
logger);
auto second_future = second_initializer.Run();
ASSERT_TRUE(second_future.IsFinished());
auto second_result = second_future.GetResult();

// Another context's data in the same cache is not a hit.
auto* second_change_set =
std::get_if<FDv2SourceResult::ChangeSet>(&second_result->value);
ASSERT_NE(nullptr, second_change_set);
EXPECT_EQ(ChangeSetType::kNone, second_change_set->change_set.type);

// Initialize for the context whose data is cached.
FDv2CacheInitializer first_initializer(&flag_manager.Cache(), first,
logger);
auto first_future = first_initializer.Run();
ASSERT_TRUE(first_future.IsFinished());
auto first_result = first_future.GetResult();

// That context's cached data comes back as a full data set.
auto* first_change_set =
std::get_if<FDv2SourceResult::ChangeSet>(&first_result->value);
ASSERT_NE(nullptr, first_change_set);
EXPECT_EQ(ChangeSetType::kFull, first_change_set->change_set.type);
}

// The orchestrator needs to tell cache initializers apart from network ones,
// so that a miss with nothing else configured still starts the SDK.
TEST(FDv2CacheInitializerTest, FactoryIdentifiesItselfAsReadingTheCache) {
Expand Down
74 changes: 74 additions & 0 deletions libs/client-sdk/tests/flag_persistence_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
using launchdarkly::data_model::ChangeSetType;
using launchdarkly::data_model::Selector;

class TestPersistence : public IPersistence {

Check warning on line 24 in libs/client-sdk/tests/flag_persistence_test.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/tests/flag_persistence_test.cpp:24:7 [cppcoreguidelines-virtual-class-destructor]

destructor of 'TestPersistence' is public and non-virtual
public:
using StoreType =
std::map<std::string,
Expand All @@ -34,7 +34,7 @@
store_[storageNamespace][key] = data;
};

void Remove(std::string storageNamespace,

Check warning on line 37 in libs/client-sdk/tests/flag_persistence_test.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/tests/flag_persistence_test.cpp:37:17 [bugprone-easily-swappable-parameters]

2 adjacent parameters of 'Remove' of similar type ('std::string') are easily swapped by mistake
std::string key) noexcept override {
auto& space = store_[storageNamespace];
auto found = space.find(key);
Expand Down Expand Up @@ -115,6 +115,80 @@
EXPECT_EQ("test", store.Get("flagA")->item->Detail().Value().AsString());
}

TEST(FlagPersistenceTests, LoadingACacheMissRetainsTheExistingData) {
auto first = ContextBuilder().Kind("user", "first").Build();
auto second = ContextBuilder().Kind("user", "second").Build();
auto store = FlagStore();
auto updater = FlagUpdater(store);
auto persistence =
std::make_shared<TestPersistence>(TestPersistence::StoreType());
auto logger = launchdarkly::logging::NullLogger();

FlagPersistence flag_persistence("the-key", updater, store, persistence,
logger, 5);

// Put the first context's flag data in the store.
flag_persistence.Apply(
first,
FlagChangeSet{
ChangeSetType::kFull,
{FlagChange{
"flagA",
ItemDescriptor{EvaluationResult{
1, std::nullopt, false, false, std::nullopt,
EvaluationDetailInternal{Value("first-value"), std::nullopt,
std::nullopt}}}}},
Selector{}},
/* from_cache= */ false);

// Load a context that has nothing cached.
flag_persistence.LoadCached(second);

// The flag data already in the store stays there.
ASSERT_TRUE(store.Get("flagA"));
EXPECT_EQ(Value("first-value"), store.Get("flagA")->item->Detail().Value());
}

TEST(FlagPersistenceTests, LoadingACacheHitReplacesTheExistingData) {
auto first = ContextBuilder().Kind("user", "first").Build();
auto second = ContextBuilder().Kind("user", "second").Build();
auto store = FlagStore();
auto updater = FlagUpdater(store);
auto logger = launchdarkly::logging::NullLogger();

auto persistence =
std::make_shared<TestPersistence>(TestPersistence::StoreType{
{"LaunchDarkly_rUTcjlHPv6Vegd27YmtGYkEGkEUGaEbn5M0JYTFQUpA=",
{{PersistenceEncodeKey(second.CanonicalKey()),
R"({"flagB":{"version":1,"value":"second-value"}})"}}}});

FlagPersistence flag_persistence("the-key", updater, store, persistence,
logger, 5);

// Put the first context's flag data in the store.
flag_persistence.Apply(
first,
FlagChangeSet{
ChangeSetType::kFull,
{FlagChange{
"flagA",
ItemDescriptor{EvaluationResult{
1, std::nullopt, false, false, std::nullopt,
EvaluationDetailInternal{Value("first-value"), std::nullopt,
std::nullopt}}}}},
Selector{}},
/* from_cache= */ false);

// Load a context that has cached data.
flag_persistence.LoadCached(second);

// The cached data takes the place of what the store held.
EXPECT_FALSE(store.Get("flagA"));
ASSERT_TRUE(store.Get("flagB"));
EXPECT_EQ(Value("second-value"),
store.Get("flagB")->item->Detail().Value());
}

TEST(FlagPersistenceTests, EvictsContextsBeyondMax) {
auto store = FlagStore();
auto updater = FlagUpdater(store);
Expand Down
Loading