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
10 changes: 5 additions & 5 deletions libs/client-sdk/src/data_sources/polling_data_source.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
static char const* const kCouldNotParseEndpoint =
"Could not parse polling endpoint URL.";

static network::HttpRequest MakeRequest(
network::HttpRequest MakePollRequest(
config::shared::built::ServiceEndpoints const& endpoints,
config::shared::built::DataSourceConfig<config::shared::ClientSDK>
data_source_config,
Expand Down Expand Up @@ -66,7 +66,7 @@
config::shared::built::DataSourceConfig<config::shared::ClientSDK> const&
data_source_config,
config::shared::built::HttpProperties const& http_properties,
boost::asio::any_io_executor ioc,

Check warning on line 69 in libs/client-sdk/src/data_sources/polling_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/polling_data_source.cpp:69:34 [performance-unnecessary-value-param]

the parameter 'ioc' is copied for each invocation but only used as a const reference; consider making it a const reference
Context const& context,
IDataSourceUpdateSink& handler,
DataSourceStatusManager& status_manager,
Expand All @@ -83,10 +83,10 @@
config::shared::built::PollingConfig<config::shared::ClientSDK>>(
data_source_config.method)
.poll_interval),
request_(MakeRequest(endpoints,
data_source_config,
http_properties,
context)) {
request_(MakePollRequest(endpoints,
data_source_config,
http_properties,
context)) {
auto const& polling_config = std::get<
config::shared::built::PollingConfig<config::shared::ClientSDK>>(
data_source_config.method);
Expand All @@ -113,7 +113,7 @@
});
}

void PollingDataSource::HandlePollResult(network::HttpResult res) {

Check warning on line 116 in libs/client-sdk/src/data_sources/polling_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/polling_data_source.cpp:116:62 [performance-unnecessary-value-param]

the parameter 'res' is copied for each invocation but only used as a const reference; consider making it a const reference
auto header_etag = res.Headers().find("etag");
bool has_etag = header_etag != res.Headers().end();

Expand Down
11 changes: 11 additions & 0 deletions libs/client-sdk/src/data_sources/polling_data_source.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@

namespace launchdarkly::client_side::data_sources {

/**
* Makes the request that polls for the flags of a context. The method of
* data_source_config must be a PollingConfig.
*/
network::HttpRequest MakePollRequest(
config::shared::built::ServiceEndpoints const& endpoints,
config::shared::built::DataSourceConfig<config::shared::ClientSDK>
data_source_config,
config::shared::built::HttpProperties const& http_properties,
Context const& context);

class PollingDataSource
: public IDataSource,
public std::enable_shared_from_this<PollingDataSource> {
Expand All @@ -34,7 +45,7 @@
Logger const& logger);

void Start() override;
void ShutdownAsync(std::function<void()>) override;

Check warning on line 48 in libs/client-sdk/src/data_sources/polling_data_source.hpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/polling_data_source.hpp:48:45 [readability-named-parameter]

all parameters should be named in a function

private:
void DoPoll();
Expand Down
78 changes: 77 additions & 1 deletion libs/client-sdk/src/data_sources/streaming_data_source.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#include "streaming_data_source.hpp"
#include "polling_data_source.hpp"

#include <launchdarkly/config/shared/defaults.hpp>
#include <launchdarkly/context_builder.hpp>
#include <launchdarkly/detail/unreachable.hpp>
#include <launchdarkly/encoding/base_64.hpp>
#include <launchdarkly/network/http_error_messages.hpp>
#include <launchdarkly/network/http_requester.hpp>
#include <launchdarkly/serialization/json_context.hpp>

Expand All @@ -24,7 +27,7 @@
config::shared::built::DataSourceConfig<config::shared::ClientSDK> const&
data_source_config,
config::shared::built::HttpProperties const& http_properties,
boost::asio::any_io_executor ioc,

Check warning on line 30 in libs/client-sdk/src/data_sources/streaming_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/streaming_data_source.cpp:30:34 [performance-unnecessary-value-param]

the parameter 'ioc' is copied for each invocation but only used as a const reference; consider making it a const reference
Context context,
IDataSourceUpdateSink& handler,
DataSourceStatusManager& status_manager,
Expand All @@ -37,7 +40,14 @@
DataSourceEventHandler(context_, handler, logger, status_manager_)),
http_config_(http_properties),
data_source_config_(data_source_config),
streaming_endpoint_(endpoints.StreamingBaseUrl()) {}
streaming_endpoint_(endpoints.StreamingBaseUrl()),
requester_(ioc, http_properties.Tls()),
ping_request_(MakePollRequest(
endpoints,
{config::shared::Defaults<config::shared::ClientSDK>::PollingConfig(),
data_source_config.with_reasons, data_source_config.use_report},
http_properties,
context_)) {}

void StreamingDataSource::Start() {
status_manager_.SetState(DataSourceStatus::DataSourceState::kInitializing);
Expand Down Expand Up @@ -129,6 +139,10 @@

client_builder.receiver([weak_self](launchdarkly::sse::Event const& event) {
if (auto self = weak_self.lock()) {
if (event.type() == "ping") {
self->PollAfterPing();
return;
}
self->data_source_handler_.HandleMessage(event.type(),
event.data());
// TODO: Use the result of handle message to restart the
Expand Down Expand Up @@ -172,14 +186,19 @@
std::string error_string) {
auto const state = sse::IsRecoverable(error) ? DataSourceState::kInterrupted
: DataSourceState::kShutdown;
if (state == DataSourceState::kShutdown) {
// The stream does not reconnect after this error. Stop the ping polls
// too, so that a poll in flight does not change the state.
stopped_ = true;
}
std::visit(
[this, state, error_string = std::move(error_string)](auto error) {
using T = std::decay_t<decltype(error)>;
if constexpr (std::is_same_v<T, sse::errors::ReadTimeout>) {

Check warning on line 197 in libs/client-sdk/src/data_sources/streaming_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/streaming_data_source.cpp:197:72 [bugprone-branch-clone]

repeated branch in conditional chain
this->status_manager_.SetState(
state,
DataSourceStatus::ErrorInfo::ErrorKind::kNetworkError,
std::move(error_string));

Check warning on line 201 in libs/client-sdk/src/data_sources/streaming_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/streaming_data_source.cpp:201:21 [performance-move-const-arg]

std::move of the const variable 'error_string' has no effect; remove std::move() or make the variable non-const

} else if constexpr (std::is_same_v<
T,
Expand All @@ -188,21 +207,21 @@
state,
static_cast<DataSourceStatusManager::StatusCodeType>(
error.status),
std::move(error_string));

Check warning on line 210 in libs/client-sdk/src/data_sources/streaming_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/streaming_data_source.cpp:210:21 [performance-move-const-arg]

std::move of the const variable 'error_string' has no effect; remove std::move() or make the variable non-const

} else if constexpr (std::is_same_v<
T, sse::errors::InvalidRedirectLocation>) {
this->status_manager_.SetState(
state,
DataSourceStatus::ErrorInfo::ErrorKind::kNetworkError,
std::move(error_string));

Check warning on line 217 in libs/client-sdk/src/data_sources/streaming_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/streaming_data_source.cpp:217:21 [performance-move-const-arg]

std::move of the const variable 'error_string' has no effect; remove std::move() or make the variable non-const

} else if constexpr (std::is_same_v<T,
sse::errors::NotRedirectable>) {
this->status_manager_.SetState(
state,
DataSourceStatus::ErrorInfo::ErrorKind::kNetworkError,
std::move(error_string));

Check warning on line 224 in libs/client-sdk/src/data_sources/streaming_data_source.cpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/streaming_data_source.cpp:224:21 [performance-move-const-arg]

std::move of the const variable 'error_string' has no effect; remove std::move() or make the variable non-const
} else {
static_assert(always_false_v<decltype(error)>,
"non-exhaustive visitor");
Expand All @@ -211,7 +230,64 @@
std::move(error));
}

void StreamingDataSource::PollAfterPing() {
if (stopped_) {
return;
}
if (ping_poll_in_flight_) {
// The poll in flight can be older than the change that caused this
// ping. Poll one more time when it completes.
LD_LOG(logger_, LogLevel::kDebug)
<< "Received ping during a poll, polling again when it completes";
ping_poll_pending_ = true;
return;
}
LD_LOG(logger_, LogLevel::kDebug)
<< "Polling for flag updates after a ping";
ping_poll_in_flight_ = true;
auto weak_self = weak_from_this();
requester_.Request(ping_request_,
[weak_self](network::HttpResult const& res) {
if (auto self = weak_self.lock()) {
self->HandlePingPollResult(res);
}
});
}

void StreamingDataSource::HandlePingPollResult(network::HttpResult const& res) {
ping_poll_in_flight_ = false;
if (stopped_) {
LD_LOG(logger_, LogLevel::kDebug)
<< "Discarding the result of a poll that completed after shutdown";
return;
}
if (res.IsError()) {
auto const error_message = res.ErrorMessage().value_or("unknown error");
LD_LOG(logger_, LogLevel::kWarn)
<< "Polling after a ping failed: " << error_message;
status_manager_.SetState(
DataSourceStatus::DataSourceState::kInterrupted,
DataSourceStatus::ErrorInfo::ErrorKind::kNetworkError,
error_message);
} else if (res.Status() == 200) {
data_source_handler_.HandleMessage("put", res.Body().value_or(""));
} else {
auto const error_message = network::ErrorForStatusCode(
res.Status(), "polling request after a ping",
"will poll again on the next ping");
LD_LOG(logger_, LogLevel::kWarn) << error_message;
status_manager_.SetState(
DataSourceStatus::DataSourceState::kInterrupted, res.Status(),
error_message);
}
if (ping_poll_pending_) {
ping_poll_pending_ = false;
PollAfterPing();
}
}

void StreamingDataSource::ShutdownAsync(std::function<void()> completion) {
stopped_ = true;
if (client_) {
status_manager_.SetState(
DataSourceStatus::DataSourceState::kInitializing);
Expand Down
25 changes: 25 additions & 0 deletions libs/client-sdk/src/data_sources/streaming_data_source.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,25 @@
#include <launchdarkly/context.hpp>
#include <launchdarkly/data/evaluation_result.hpp>
#include <launchdarkly/logging/logger.hpp>
#include <launchdarkly/network/requester.hpp>
#include <launchdarkly/sse/client.hpp>

#include <atomic>
#include <chrono>

namespace launchdarkly::client_side::data_sources {

/**
* Streams the flags of one context. When the stream sends a "ping" event, the
* data source polls for the flags of the context and applies the result.
* Call Start at most once. After ShutdownAsync, the data source does not
* start again.
*
* Thread safety: Start and ShutdownAsync are safe from any thread, but not at
* the same time. The stream, poll and error callbacks run on the executor
* given to the constructor. That executor must run on one thread, because the
* data source relies on it to run those callbacks one at a time.
*/
class StreamingDataSource final
: public IDataSource,
public std::enable_shared_from_this<StreamingDataSource> {
Expand All @@ -36,10 +49,12 @@
Logger const& logger);

void Start() override;
void ShutdownAsync(std::function<void()>) override;

Check warning on line 52 in libs/client-sdk/src/data_sources/streaming_data_source.hpp

View workflow job for this annotation

GitHub Actions / cpp-linter

libs/client-sdk/src/data_sources/streaming_data_source.hpp:52:45 [readability-named-parameter]

all parameters should be named in a function

private:
void HandleErrorStateChange(sse::Error error, std::string error_string);
void PollAfterPing();
void HandlePingPollResult(network::HttpResult const& res);

Context context_;
boost::asio::any_io_executor exec_;
Expand All @@ -55,5 +70,15 @@

Logger const& logger_;
std::shared_ptr<launchdarkly::sse::Client> client_;
network::Requester requester_;
network::HttpRequest ping_request_;

// Used only on the executor thread.
bool ping_poll_in_flight_ = false;
bool ping_poll_pending_ = false;

// ShutdownAsync and an unrecoverable stream error set this. ShutdownAsync
// can run on a different thread.
std::atomic<bool> stopped_{false};
};
} // namespace launchdarkly::client_side::data_sources
Loading
Loading