From 8d385a44a93dab02967fbada98a1e2f5e9c3a8b9 Mon Sep 17 00:00:00 2001 From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:12:33 +0000 Subject: [PATCH 1/3] fix: Poll for flag updates when the stream sends a ping event Generated-by: termag --- .../src/data_sources/polling_data_source.cpp | 10 +- .../src/data_sources/polling_data_source.hpp | 11 + .../data_sources/streaming_data_source.cpp | 50 ++- .../data_sources/streaming_data_source.hpp | 5 + .../tests/streaming_data_source_ping_test.cpp | 301 ++++++++++++++++++ 5 files changed, 371 insertions(+), 6 deletions(-) create mode 100644 libs/client-sdk/tests/streaming_data_source_ping_test.cpp diff --git a/libs/client-sdk/src/data_sources/polling_data_source.cpp b/libs/client-sdk/src/data_sources/polling_data_source.cpp index e6cd4bf21..5aa3f94fb 100644 --- a/libs/client-sdk/src/data_sources/polling_data_source.cpp +++ b/libs/client-sdk/src/data_sources/polling_data_source.cpp @@ -17,7 +17,7 @@ namespace launchdarkly::client_side::data_sources { 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 data_source_config, @@ -83,10 +83,10 @@ PollingDataSource::PollingDataSource( config::shared::built::PollingConfig>( 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>( data_source_config.method); diff --git a/libs/client-sdk/src/data_sources/polling_data_source.hpp b/libs/client-sdk/src/data_sources/polling_data_source.hpp index 50a81760c..0c48f6e52 100644 --- a/libs/client-sdk/src/data_sources/polling_data_source.hpp +++ b/libs/client-sdk/src/data_sources/polling_data_source.hpp @@ -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 + data_source_config, + config::shared::built::HttpProperties const& http_properties, + Context const& context); + class PollingDataSource : public IDataSource, public std::enable_shared_from_this { diff --git a/libs/client-sdk/src/data_sources/streaming_data_source.cpp b/libs/client-sdk/src/data_sources/streaming_data_source.cpp index 83494a6a0..afb57f3fc 100644 --- a/libs/client-sdk/src/data_sources/streaming_data_source.cpp +++ b/libs/client-sdk/src/data_sources/streaming_data_source.cpp @@ -1,8 +1,11 @@ #include "streaming_data_source.hpp" +#include "polling_data_source.hpp" +#include #include #include #include +#include #include #include @@ -37,7 +40,14 @@ StreamingDataSource::StreamingDataSource( 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::PollingConfig(), + data_source_config.with_reasons, data_source_config.use_report}, + http_properties, + context_)) {} void StreamingDataSource::Start() { status_manager_.SetState(DataSourceStatus::DataSourceState::kInitializing); @@ -129,6 +139,10 @@ void StreamingDataSource::Start() { 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 @@ -165,6 +179,40 @@ void StreamingDataSource::Start() { client_->async_connect(); } +void StreamingDataSource::PollAfterPing() { + LD_LOG(logger_, LogLevel::kDebug) + << "Received ping, polling for flag updates"; + 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) { + 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); + return; + } + if (res.Status() == 200) { + data_source_handler_.HandleMessage("put", res.Body().value_or("")); + return; + } + auto const error_message = network::ErrorForStatusCode( + res.Status(), "polling request after a ping", std::nullopt); + LD_LOG(logger_, LogLevel::kWarn) << error_message; + status_manager_.SetState(DataSourceStatus::DataSourceState::kInterrupted, + res.Status(), error_message); +} + template inline constexpr bool always_false_v = false; diff --git a/libs/client-sdk/src/data_sources/streaming_data_source.hpp b/libs/client-sdk/src/data_sources/streaming_data_source.hpp index b644b711b..8b3455969 100644 --- a/libs/client-sdk/src/data_sources/streaming_data_source.hpp +++ b/libs/client-sdk/src/data_sources/streaming_data_source.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -40,6 +41,8 @@ class StreamingDataSource final 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_; @@ -55,5 +58,7 @@ class StreamingDataSource final Logger const& logger_; std::shared_ptr client_; + network::Requester requester_; + network::HttpRequest ping_request_; }; } // namespace launchdarkly::client_side::data_sources diff --git a/libs/client-sdk/tests/streaming_data_source_ping_test.cpp b/libs/client-sdk/tests/streaming_data_source_ping_test.cpp new file mode 100644 index 000000000..97c249905 --- /dev/null +++ b/libs/client-sdk/tests/streaming_data_source_ping_test.cpp @@ -0,0 +1,301 @@ +#include + +#include "data_sources/data_source_status_manager.hpp" +#include "data_sources/data_source_update_sink.hpp" +#include "data_sources/streaming_data_source.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace launchdarkly; +using namespace launchdarkly::client_side; +using namespace launchdarkly::client_side::data_sources; +using namespace std::chrono_literals; + +using config::shared::ClientSDK; +using config::shared::Defaults; + +namespace beast = boost::beast; +namespace http = beast::http; +using tcp = boost::asio::ip::tcp; + +namespace { + +using FlagData = std::unordered_map; +using Request = http::request; + +Logger MakeNullLogger() { + struct NullBackend : ILogBackend { + bool Enabled(LogLevel) noexcept override { return false; } + void Write(LogLevel, std::string) noexcept override {} + }; + return Logger{std::make_shared()}; +} + +// Records the first flag data that a data source gives to the SDK. +// +// Thread safety: the data source calls Init on its io_context thread. +// WaitForInit is safe from any thread. The recorded data is protected by +// mutex_. +class RecordingSink final : public IDataSourceUpdateSink { + public: + void Init(Context const&, FlagData data) override { + std::lock_guard lock(mutex_); + if (!init_data_) { + init_data_ = std::move(data); + } + cv_.notify_all(); + } + void Upsert(Context const&, std::string, ItemDescriptor) override {} + void Apply(Context const&, FlagChangeSet, bool) override {} + + // Returns the data of the first Init call, or nullopt if Init is not + // called before the timeout. + std::optional WaitForInit(std::chrono::milliseconds timeout) { + std::unique_lock lock(mutex_); + cv_.wait_for(lock, timeout, [this] { return init_data_.has_value(); }); + return init_data_; + } + + private: + std::mutex mutex_; + std::condition_variable cv_; + std::optional init_data_; +}; + +// Serves a stream that sends a ping event and then stays open, and a polling +// endpoint that returns fixed flag data. Records the first poll request. +// +// Thread safety: the accept and session handlers run on the io_context passed +// to the constructor. WaitForPoll is safe from any thread. The recorded +// request is protected by mutex_. +class PingService { + public: + PingService(boost::asio::io_context& ioc, std::string poll_body) + : acceptor_(ioc, + tcp::endpoint(boost::asio::ip::make_address("127.0.0.1"), + /* port= */ 0)), + poll_body_(std::move(poll_body)) { + Accept(); + } + + [[nodiscard]] std::string Url() const { + return "http://127.0.0.1:" + + std::to_string(acceptor_.local_endpoint().port()); + } + + // Returns the first poll request, or nullopt if no poll request arrives + // before the timeout. + std::optional WaitForPoll(std::chrono::milliseconds timeout) { + std::unique_lock lock(mutex_); + cv_.wait_for(lock, timeout, [this] { return poll_.has_value(); }); + return poll_; + } + + private: + struct Session : std::enable_shared_from_this { + Session(tcp::socket socket, PingService* service) + : socket(std::move(socket)), service(service) {} + + void Run() { + http::async_read(socket, buffer, request, + [self = shared_from_this()]( + beast::error_code const& ec, std::size_t) { + if (ec) { + return; + } + if (std::string(self->request.target()) + .rfind("/meval", 0) == 0) { + self->Stream(); + } else { + self->Poll(); + } + }); + } + + // Writes the response head and one ping event, but does not end the + // response. The stream stays open until the client closes it. + void Stream() { + stream_text = + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "\r\n" + "event: ping\n" + "data: \n" + "\n"; + boost::asio::async_write( + socket, boost::asio::buffer(stream_text), + [self = shared_from_this()](beast::error_code const& ec, + std::size_t) { + if (ec) { + return; + } + self->socket.async_wait( + tcp::socket::wait_read, + [self](beast::error_code const&) {}); + }); + } + + void Poll() { + service->RecordPoll(request); + response.result(http::status::ok); + response.set(http::field::content_type, "application/json"); + response.body() = service->poll_body_; + response.keep_alive(false); + response.prepare_payload(); + http::async_write( + socket, response, + [self = shared_from_this()](beast::error_code ec, std::size_t) { + self->socket.shutdown(tcp::socket::shutdown_send, ec); + }); + } + + tcp::socket socket; + beast::flat_buffer buffer; + Request request; + http::response response; + std::string stream_text; + PingService* service; + }; + + void Accept() { + acceptor_.async_accept( + [this](beast::error_code const& ec, tcp::socket socket) { + if (ec) { + return; + } + std::make_shared(std::move(socket), this)->Run(); + Accept(); + }); + } + + void RecordPoll(Request const& request) { + std::lock_guard lock(mutex_); + if (!poll_) { + poll_ = request; + } + cv_.notify_all(); + } + + tcp::acceptor acceptor_; + std::string const poll_body_; + + // Protected by mutex_. + std::mutex mutex_; + std::condition_variable cv_; + std::optional poll_; +}; + +} // namespace + +class StreamingDataSourcePingTest : public ::testing::Test { + protected: + // Starts a streaming data source whose stream sends a ping event. Returns + // the poll request that the data source sends and the flag data that it + // gives to the SDK. + std::pair, std::optional> PingAndWait( + bool use_report) { + boost::asio::io_context ioc; + auto work = boost::asio::make_work_guard(ioc); + PingService service(ioc, R"({"flagA":{"version":1,"value":"test"}})"); + + auto const endpoints = + config::shared::builders::EndpointsBuilder() + .RelayProxyBaseURL(service.Url()) + .Build(); + config::shared::built::DataSourceConfig const + data_source_config{Defaults::StreamingConfig(), + /* with_reasons= */ false, use_report}; + auto const http_properties = + config::shared::builders::HttpPropertiesBuilder() + .Build(); + + auto const logger = MakeNullLogger(); + DataSourceStatusManager status_manager; + RecordingSink sink; + auto source = std::make_shared( + *endpoints, data_source_config, http_properties, ioc.get_executor(), + context_, sink, status_manager, logger); + + source->Start(); + std::thread thread([&ioc] { ioc.run(); }); + + auto poll = service.WaitForPoll(5s); + auto data = sink.WaitForInit(5s); + + std::promise shutdown; + boost::asio::post(ioc, [&source, &shutdown] { + source->ShutdownAsync([&shutdown] { shutdown.set_value(); }); + }); + shutdown.get_future().wait_for(5s); + work.reset(); + ioc.stop(); + thread.join(); + return {std::move(poll), std::move(data)}; + } + + Context const context_ = ContextBuilder().Kind("user", "user-key").Build(); + FlagData const poll_data_{ + {"flagA", ItemDescriptor(EvaluationResult( + 1, + std::nullopt, + false, + false, + std::nullopt, + EvaluationDetailInternal(Value("test"), + std::nullopt, + std::nullopt)))}}; +}; + +TEST_F(StreamingDataSourcePingTest, PingPollsWithGetAndAppliesTheResult) { + // The stream sends a ping event to a data source that uses GET. + auto const [poll, data] = PingAndWait(/* use_report= */ false); + + // The data source polls for its context with GET and applies the result. + ASSERT_TRUE(poll); + EXPECT_EQ(http::verb::get, poll->method()); + EXPECT_EQ("/msdk/evalx/contexts/" + + encoding::Base64UrlEncode(boost::json::serialize( + boost::json::value_from(context_))), + poll->target()); + EXPECT_EQ(poll_data_, data); +} + +TEST_F(StreamingDataSourcePingTest, PingPollsWithReportAndAppliesTheResult) { + // The stream sends a ping event to a data source that uses REPORT. + auto const [poll, data] = PingAndWait(/* use_report= */ true); + + // The data source polls for its context with REPORT and applies the + // result. + ASSERT_TRUE(poll); + EXPECT_EQ(http::verb::report, poll->method()); + EXPECT_EQ("/msdk/evalx/context", poll->target()); + EXPECT_EQ(boost::json::value_from(context_), + boost::json::parse(poll->body())); + EXPECT_EQ(poll_data_, data); +} From ec625d61c7624960371ebe07a265b248137ba447 Mon Sep 17 00:00:00 2001 From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:19:09 +0000 Subject: [PATCH 2/3] fix: Coalesce ping polls and discard poll results after shutdown Generated-by: termag --- .../data_sources/streaming_data_source.cpp | 91 +-- .../data_sources/streaming_data_source.hpp | 17 + .../tests/streaming_data_source_ping_test.cpp | 544 +++++++++++++----- 3 files changed, 478 insertions(+), 174 deletions(-) diff --git a/libs/client-sdk/src/data_sources/streaming_data_source.cpp b/libs/client-sdk/src/data_sources/streaming_data_source.cpp index afb57f3fc..abaf1f81e 100644 --- a/libs/client-sdk/src/data_sources/streaming_data_source.cpp +++ b/libs/client-sdk/src/data_sources/streaming_data_source.cpp @@ -179,40 +179,6 @@ void StreamingDataSource::Start() { client_->async_connect(); } -void StreamingDataSource::PollAfterPing() { - LD_LOG(logger_, LogLevel::kDebug) - << "Received ping, polling for flag updates"; - 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) { - 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); - return; - } - if (res.Status() == 200) { - data_source_handler_.HandleMessage("put", res.Body().value_or("")); - return; - } - auto const error_message = network::ErrorForStatusCode( - res.Status(), "polling request after a ping", std::nullopt); - LD_LOG(logger_, LogLevel::kWarn) << error_message; - status_manager_.SetState(DataSourceStatus::DataSourceState::kInterrupted, - res.Status(), error_message); -} - template inline constexpr bool always_false_v = false; @@ -259,7 +225,64 @@ void StreamingDataSource::HandleErrorStateChange(sse::Error error, 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) + << "Received ping, polling for flag updates"; + 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 completion) { + stopped_ = true; if (client_) { status_manager_.SetState( DataSourceStatus::DataSourceState::kInitializing); diff --git a/libs/client-sdk/src/data_sources/streaming_data_source.hpp b/libs/client-sdk/src/data_sources/streaming_data_source.hpp index 8b3455969..ec052aa49 100644 --- a/libs/client-sdk/src/data_sources/streaming_data_source.hpp +++ b/libs/client-sdk/src/data_sources/streaming_data_source.hpp @@ -17,10 +17,20 @@ #include #include +#include #include 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. + * + * 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 { @@ -60,5 +70,12 @@ class StreamingDataSource final std::shared_ptr 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 sets this, and it can run on a different thread. + std::atomic stopped_{false}; }; } // namespace launchdarkly::client_side::data_sources diff --git a/libs/client-sdk/tests/streaming_data_source_ping_test.cpp b/libs/client-sdk/tests/streaming_data_source_ping_test.cpp index 97c249905..95565a654 100644 --- a/libs/client-sdk/tests/streaming_data_source_ping_test.cpp +++ b/libs/client-sdk/tests/streaming_data_source_ping_test.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -31,6 +32,7 @@ #include #include #include +#include using namespace launchdarkly; using namespace launchdarkly::client_side; @@ -39,6 +41,8 @@ using namespace std::chrono_literals; using config::shared::ClientSDK; using config::shared::Defaults; +using DataSourceState = DataSourceStatus::DataSourceState; +using ErrorKind = DataSourceStatus::ErrorInfo::ErrorKind; namespace beast = boost::beast; namespace http = beast::http; @@ -49,138 +53,202 @@ namespace { using FlagData = std::unordered_map; using Request = http::request; -Logger MakeNullLogger() { - struct NullBackend : ILogBackend { - bool Enabled(LogLevel) noexcept override { return false; } - void Write(LogLevel, std::string) noexcept override {} - }; - return Logger{std::make_shared()}; +char const* const kPingEvent = "event: ping\ndata: \n\n"; + +// Returns a poll response body with one flag, "flagA". +std::string FlagsJson(int version, std::string const& value) { + return R"({"flagA":{"version":)" + std::to_string(version) + + R"(,"value":")" + value + R"("}})"; } -// Records the first flag data that a data source gives to the SDK. +// Returns the value of "flagA" in each data set. +std::vector FlagAValues(std::vector const& data_sets) { + std::vector values; + for (auto const& data : data_sets) { + values.push_back(data.at("flagA").item->Detail().Value().AsString()); + } + return values; +} + +// Records the messages that the data source logs. // -// Thread safety: the data source calls Init on its io_context thread. -// WaitForInit is safe from any thread. The recorded data is protected by +// Thread safety: Write is safe from any thread, as ILogBackend requires. +// WaitForMessage is safe from any thread. The messages are protected by // mutex_. +class RecordingLogBackend final : public ILogBackend { + public: + bool Enabled(LogLevel) noexcept override { return true; } + + void Write(LogLevel, std::string message) noexcept override { + std::lock_guard lock(mutex_); + messages_.push_back(std::move(message)); + cv_.notify_all(); + } + + // Returns true if a message that contains the text is logged before the + // timeout. + bool WaitForMessage(std::string const& text, + std::chrono::milliseconds timeout) { + std::unique_lock lock(mutex_); + return cv_.wait_for(lock, timeout, [&] { + for (auto const& message : messages_) { + if (message.find(text) != std::string::npos) { + return true; + } + } + return false; + }); + } + + private: + std::mutex mutex_; + std::condition_variable cv_; + std::vector messages_; +}; + +// Records the flag data that a data source gives to the SDK. +// +// Thread safety: the data source calls Init and Upsert on its executor +// thread. The Wait methods are safe from any thread. The recorded data is +// protected by mutex_. class RecordingSink final : public IDataSourceUpdateSink { public: void Init(Context const&, FlagData data) override { std::lock_guard lock(mutex_); - if (!init_data_) { - init_data_ = std::move(data); - } + inits_.push_back(std::move(data)); cv_.notify_all(); } - void Upsert(Context const&, std::string, ItemDescriptor) override {} + + void Upsert(Context const&, std::string key, ItemDescriptor) override { + std::lock_guard lock(mutex_); + upserts_.push_back(std::move(key)); + cv_.notify_all(); + } + void Apply(Context const&, FlagChangeSet, bool) override {} - // Returns the data of the first Init call, or nullopt if Init is not - // called before the timeout. - std::optional WaitForInit(std::chrono::milliseconds timeout) { + // Waits until Init is called at least count times, or until the timeout. + // Returns the data of every Init call. + std::vector WaitForInits(std::size_t count, + std::chrono::milliseconds timeout) { std::unique_lock lock(mutex_); - cv_.wait_for(lock, timeout, [this] { return init_data_.has_value(); }); - return init_data_; + cv_.wait_for(lock, timeout, [&] { return inits_.size() >= count; }); + return inits_; + } + + // Waits until Upsert is called at least count times, or until the + // timeout. Returns the key of every Upsert call. + std::vector WaitForUpserts(std::size_t count, + std::chrono::milliseconds timeout) { + std::unique_lock lock(mutex_); + cv_.wait_for(lock, timeout, [&] { return upserts_.size() >= count; }); + return upserts_; } private: std::mutex mutex_; std::condition_variable cv_; - std::optional init_data_; + std::vector inits_; + std::vector upserts_; }; -// Serves a stream that sends a ping event and then stays open, and a polling -// endpoint that returns fixed flag data. Records the first poll request. +// Serves a stream and a polling endpoint from its own thread, as the Relay +// Proxy does for a ping stream. The stream sends a ping when a client +// connects, and then the events that the test sends. The test answers each +// poll request. // -// Thread safety: the accept and session handlers run on the io_context passed -// to the constructor. WaitForPoll is safe from any thread. The recorded -// request is protected by mutex_. +// Thread safety: the public methods are safe from any thread. The network +// handlers run on the thread of the service, and only they use sessions_, +// polls_ and stream_. The recorded poll requests are protected by mutex_. class PingService { public: - PingService(boost::asio::io_context& ioc, std::string poll_body) - : acceptor_(ioc, + PingService() + : acceptor_(ioc_, tcp::endpoint(boost::asio::ip::make_address("127.0.0.1"), /* port= */ 0)), - poll_body_(std::move(poll_body)) { + url_("http://127.0.0.1:" + + std::to_string(acceptor_.local_endpoint().port())) { Accept(); + thread_ = std::thread([this] { ioc_.run(); }); } - [[nodiscard]] std::string Url() const { - return "http://127.0.0.1:" + - std::to_string(acceptor_.local_endpoint().port()); + // Closes every connection. Then the handlers end and the thread exits. + ~PingService() { + boost::asio::post(ioc_, [this] { + beast::error_code ec; + acceptor_.close(ec); + for (auto const& session : sessions_) { + session->socket.close(ec); + } + }); + thread_.join(); } - // Returns the first poll request, or nullopt if no poll request arrives - // before the timeout. - std::optional WaitForPoll(std::chrono::milliseconds timeout) { - std::unique_lock lock(mutex_); - cv_.wait_for(lock, timeout, [this] { return poll_.has_value(); }); - return poll_; + [[nodiscard]] std::string const& Url() const { return url_; } + + // Sends an event on the stream. The stream must be open. + void Send(std::string event) { + boost::asio::post(ioc_, [this, event = std::move(event)]() mutable { + Write(stream_, std::move(event)); + }); } - private: - struct Session : std::enable_shared_from_this { - Session(tcp::socket socket, PingService* service) - : socket(std::move(socket)), service(service) {} - - void Run() { - http::async_read(socket, buffer, request, - [self = shared_from_this()]( - beast::error_code const& ec, std::size_t) { - if (ec) { - return; - } - if (std::string(self->request.target()) - .rfind("/meval", 0) == 0) { - self->Stream(); - } else { - self->Poll(); - } - }); + // Returns poll request number index (from 0), or nullopt if it does not + // arrive before the timeout. + std::optional WaitForPoll(std::size_t index, + std::chrono::milliseconds timeout) { + std::unique_lock lock(mutex_); + if (!cv_.wait_for(lock, timeout, + [&] { return poll_requests_.size() > index; })) { + return std::nullopt; } + return poll_requests_[index]; + } - // Writes the response head and one ping event, but does not end the - // response. The stream stays open until the client closes it. - void Stream() { - stream_text = - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/event-stream\r\n" - "\r\n" - "event: ping\n" - "data: \n" - "\n"; - boost::asio::async_write( - socket, boost::asio::buffer(stream_text), - [self = shared_from_this()](beast::error_code const& ec, - std::size_t) { - if (ec) { - return; - } - self->socket.async_wait( - tcp::socket::wait_read, - [self](beast::error_code const&) {}); - }); - } + [[nodiscard]] std::size_t PollCount() { + std::lock_guard lock(mutex_); + return poll_requests_.size(); + } - void Poll() { - service->RecordPoll(request); - response.result(http::status::ok); - response.set(http::field::content_type, "application/json"); - response.body() = service->poll_body_; - response.keep_alive(false); - response.prepare_payload(); - http::async_write( - socket, response, - [self = shared_from_this()](beast::error_code ec, std::size_t) { - self->socket.shutdown(tcp::socket::shutdown_send, ec); - }); - } + // Answers poll request number index, which must have arrived. + void RespondToPoll(std::size_t index, + http::status status, + std::string body) { + boost::asio::post( + ioc_, [this, index, status, body = std::move(body)]() mutable { + auto session = polls_.at(index); + session->response.result(status); + session->response.set(http::field::content_type, + "application/json"); + session->response.body() = std::move(body); + session->response.keep_alive(false); + session->response.prepare_payload(); + http::async_write(session->socket, session->response, + [session](beast::error_code ec, std::size_t) { + session->socket.shutdown( + tcp::socket::shutdown_send, ec); + }); + }); + } + + // Closes the connection of poll request number index without a response. + // The poll request must have arrived. + void ClosePoll(std::size_t index) { + boost::asio::post(ioc_, [this, index] { + beast::error_code ec; + polls_.at(index)->socket.close(ec); + }); + } + + private: + struct Session { + explicit Session(tcp::socket socket) : socket(std::move(socket)) {} tcp::socket socket; beast::flat_buffer buffer; Request request; http::response response; - std::string stream_text; - PingService* service; + std::deque writes; }; void Accept() { @@ -189,74 +257,146 @@ class PingService { if (ec) { return; } - std::make_shared(std::move(socket), this)->Run(); + auto session = std::make_shared(std::move(socket)); + sessions_.push_back(session); + Read(session); Accept(); }); } - void RecordPoll(Request const& request) { - std::lock_guard lock(mutex_); - if (!poll_) { - poll_ = request; + void Read(std::shared_ptr const& session) { + http::async_read( + session->socket, session->buffer, session->request, + [this, session](beast::error_code const& ec, std::size_t) { + if (ec) { + return; + } + if (std::string(session->request.target()).rfind("/meval", 0) == + 0) { + stream_ = session; + Write(session, + std::string("HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "\r\n") + + kPingEvent); + return; + } + polls_.push_back(session); + std::lock_guard lock(mutex_); + poll_requests_.push_back(session->request); + cv_.notify_all(); + }); + } + + // Writes the text after any earlier writes on the same connection. + void Write(std::shared_ptr const& session, std::string text) { + session->writes.push_back(std::move(text)); + if (session->writes.size() == 1) { + WriteNext(session); } - cv_.notify_all(); } + void WriteNext(std::shared_ptr const& session) { + boost::asio::async_write( + session->socket, boost::asio::buffer(session->writes.front()), + [this, session](beast::error_code const& ec, std::size_t) { + session->writes.pop_front(); + if (ec) { + session->writes.clear(); + return; + } + if (!session->writes.empty()) { + WriteNext(session); + } + }); + } + + boost::asio::io_context ioc_; tcp::acceptor acceptor_; - std::string const poll_body_; + std::string const url_; + std::thread thread_; + + // Used only on the thread of the service. + std::vector> sessions_; + std::vector> polls_; + std::shared_ptr stream_; // Protected by mutex_. std::mutex mutex_; std::condition_variable cv_; - std::optional poll_; + std::vector poll_requests_; }; } // namespace class StreamingDataSourcePingTest : public ::testing::Test { protected: - // Starts a streaming data source whose stream sends a ping event. Returns - // the poll request that the data source sends and the flag data that it - // gives to the SDK. - std::pair, std::optional> PingAndWait( - bool use_report) { - boost::asio::io_context ioc; - auto work = boost::asio::make_work_guard(ioc); - PingService service(ioc, R"({"flagA":{"version":1,"value":"test"}})"); + void SetUp() override { + status_connection_ = status_manager_.OnDataSourceStatusChange( + [this](DataSourceStatus status) { + std::lock_guard lock(status_mutex_); + latest_status_.emplace(std::move(status)); + status_cv_.notify_all(); + }); + } + + void TearDown() override { + if (source_ && !shut_down_) { + Shutdown(); + } + status_connection_->Disconnect(); + work_.reset(); + ioc_.stop(); + if (thread_.joinable()) { + thread_.join(); + } + } + // Starts a data source that streams from the service. The service sends + // a ping as soon as the data source connects. + void Start(bool use_report, bool with_reasons) { auto const endpoints = config::shared::builders::EndpointsBuilder() - .RelayProxyBaseURL(service.Url()) + .RelayProxyBaseURL(service_.Url()) .Build(); config::shared::built::DataSourceConfig const data_source_config{Defaults::StreamingConfig(), - /* with_reasons= */ false, use_report}; + with_reasons, use_report}; auto const http_properties = config::shared::builders::HttpPropertiesBuilder() .Build(); + source_ = std::make_shared( + *endpoints, data_source_config, http_properties, + ioc_.get_executor(), context_, sink_, status_manager_, logger_); + source_->Start(); + thread_ = std::thread([this] { ioc_.run(); }); + } - auto const logger = MakeNullLogger(); - DataSourceStatusManager status_manager; - RecordingSink sink; - auto source = std::make_shared( - *endpoints, data_source_config, http_properties, ioc.get_executor(), - context_, sink, status_manager, logger); - - source->Start(); - std::thread thread([&ioc] { ioc.run(); }); + // Shuts the data source down and waits for the shutdown to complete. + void Shutdown() { + auto done = std::make_shared>(); + boost::asio::post(ioc_, [this, done] { + source_->ShutdownAsync([done] { done->set_value(); }); + }); + shut_down_ = true; + ASSERT_EQ(std::future_status::ready, done->get_future().wait_for(5s)); + } - auto poll = service.WaitForPoll(5s); - auto data = sink.WaitForInit(5s); + // Returns the status once its state is the given state, or nullopt if + // that does not happen before the timeout. + std::optional WaitForState(DataSourceState state) { + std::unique_lock lock(status_mutex_); + if (!status_cv_.wait_for(lock, 5s, [&] { + return latest_status_ && latest_status_->State() == state; + })) { + return std::nullopt; + } + return latest_status_; + } - std::promise shutdown; - boost::asio::post(ioc, [&source, &shutdown] { - source->ShutdownAsync([&shutdown] { shutdown.set_value(); }); - }); - shutdown.get_future().wait_for(5s); - work.reset(); - ioc.stop(); - thread.join(); - return {std::move(poll), std::move(data)}; + [[nodiscard]] std::string EncodedContext() const { + return encoding::Base64UrlEncode( + boost::json::serialize(boost::json::value_from(context_))); } Context const context_ = ContextBuilder().Kind("user", "user-key").Build(); @@ -270,32 +410,156 @@ class StreamingDataSourcePingTest : public ::testing::Test { EvaluationDetailInternal(Value("test"), std::nullopt, std::nullopt)))}}; + + PingService service_; + std::shared_ptr const log_ = + std::make_shared(); + Logger const logger_{log_}; + RecordingSink sink_; + DataSourceStatusManager status_manager_; + std::unique_ptr status_connection_; + + // Protected by status_mutex_. + std::mutex status_mutex_; + std::condition_variable status_cv_; + std::optional latest_status_; + + boost::asio::io_context ioc_; + boost::asio::executor_work_guard + work_ = boost::asio::make_work_guard(ioc_); + std::shared_ptr source_; + bool shut_down_ = false; + std::thread thread_; }; TEST_F(StreamingDataSourcePingTest, PingPollsWithGetAndAppliesTheResult) { // The stream sends a ping event to a data source that uses GET. - auto const [poll, data] = PingAndWait(/* use_report= */ false); + Start(/* use_report= */ false, /* with_reasons= */ false); + auto const poll = service_.WaitForPoll(0, 5s); + ASSERT_TRUE(poll); + service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "test")); // The data source polls for its context with GET and applies the result. - ASSERT_TRUE(poll); EXPECT_EQ(http::verb::get, poll->method()); - EXPECT_EQ("/msdk/evalx/contexts/" + - encoding::Base64UrlEncode(boost::json::serialize( - boost::json::value_from(context_))), - poll->target()); - EXPECT_EQ(poll_data_, data); + EXPECT_EQ("/msdk/evalx/contexts/" + EncodedContext(), poll->target()); + EXPECT_EQ(std::vector{poll_data_}, sink_.WaitForInits(1, 5s)); + EXPECT_TRUE(WaitForState(DataSourceState::kValid)); } TEST_F(StreamingDataSourcePingTest, PingPollsWithReportAndAppliesTheResult) { // The stream sends a ping event to a data source that uses REPORT. - auto const [poll, data] = PingAndWait(/* use_report= */ true); + Start(/* use_report= */ true, /* with_reasons= */ false); + auto const poll = service_.WaitForPoll(0, 5s); + ASSERT_TRUE(poll); + service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "test")); // The data source polls for its context with REPORT and applies the // result. - ASSERT_TRUE(poll); EXPECT_EQ(http::verb::report, poll->method()); EXPECT_EQ("/msdk/evalx/context", poll->target()); EXPECT_EQ(boost::json::value_from(context_), boost::json::parse(poll->body())); - EXPECT_EQ(poll_data_, data); + EXPECT_EQ(std::vector{poll_data_}, sink_.WaitForInits(1, 5s)); +} + +TEST_F(StreamingDataSourcePingTest, PingPollRequestsReasonsWhenConfigured) { + Start(/* use_report= */ false, /* with_reasons= */ true); + + auto const poll = service_.WaitForPoll(0, 5s); + ASSERT_TRUE(poll); + EXPECT_EQ("/msdk/evalx/contexts/" + EncodedContext() + "?withReasons=true", + poll->target()); +} + +TEST_F(StreamingDataSourcePingTest, PingsDuringAPollCauseOneMorePoll) { + Start(/* use_report= */ false, /* with_reasons= */ false); + ASSERT_TRUE(service_.WaitForPoll(0, 5s)); + + // Three pings arrive while the first poll is in flight. The patch after + // them shows that the data source has handled them. + service_.Send(kPingEvent); + service_.Send(kPingEvent); + service_.Send(kPingEvent); + service_.Send( + "event: patch\n" + R"(data: {"key": "flagB", "version": 1, "value": true})" + "\n\n"); + ASSERT_EQ(1u, sink_.WaitForUpserts(1, 5s).size()); + + // The data source applies the first poll, then polls one more time and + // applies that result last. + service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "old")); + ASSERT_TRUE(service_.WaitForPoll(1, 5s)); + service_.RespondToPoll(1, http::status::ok, FlagsJson(2, "new")); + EXPECT_EQ((std::vector{"old", "new"}), + FlagAValues(sink_.WaitForInits(2, 5s))); + + // The next ping polls again. The three pings caused only one poll. + service_.Send(kPingEvent); + ASSERT_TRUE(service_.WaitForPoll(2, 5s)); + EXPECT_EQ(3u, service_.PollCount()); +} + +TEST_F(StreamingDataSourcePingTest, + ErrorStatusInterruptsAndNextPingPollsAgain) { + Start(/* use_report= */ false, /* with_reasons= */ false); + ASSERT_TRUE(service_.WaitForPoll(0, 5s)); + service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "old")); + ASSERT_TRUE(WaitForState(DataSourceState::kValid)); + + // The poll after the next ping gets a server error. + service_.Send(kPingEvent); + ASSERT_TRUE(service_.WaitForPoll(1, 5s)); + service_.RespondToPoll(1, http::status::service_unavailable, ""); + + // The data source reports the error and stays connected. + auto const interrupted = WaitForState(DataSourceState::kInterrupted); + ASSERT_TRUE(interrupted); + ASSERT_TRUE(interrupted->LastError()); + EXPECT_EQ(ErrorKind::kErrorResponse, interrupted->LastError()->Kind()); + EXPECT_EQ(503, interrupted->LastError()->StatusCode()); + EXPECT_EQ( + "HTTP error 503 for: polling request after a ping - will poll again on " + "the next ping", + interrupted->LastError()->Message()); + + // The next ping polls again and applies the result. + service_.Send(kPingEvent); + ASSERT_TRUE(service_.WaitForPoll(2, 5s)); + service_.RespondToPoll(2, http::status::ok, FlagsJson(2, "new")); + EXPECT_TRUE(WaitForState(DataSourceState::kValid)); + EXPECT_EQ((std::vector{"old", "new"}), + FlagAValues(sink_.WaitForInits(2, 5s))); +} + +TEST_F(StreamingDataSourcePingTest, NetworkErrorOnPollInterrupts) { + Start(/* use_report= */ false, /* with_reasons= */ false); + ASSERT_TRUE(service_.WaitForPoll(0, 5s)); + service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "old")); + ASSERT_TRUE(WaitForState(DataSourceState::kValid)); + + // The connection of the poll after the next ping closes with no response. + service_.Send(kPingEvent); + ASSERT_TRUE(service_.WaitForPoll(1, 5s)); + service_.ClosePoll(1); + + auto const interrupted = WaitForState(DataSourceState::kInterrupted); + ASSERT_TRUE(interrupted); + ASSERT_TRUE(interrupted->LastError()); + EXPECT_EQ(ErrorKind::kNetworkError, interrupted->LastError()->Kind()); +} + +TEST_F(StreamingDataSourcePingTest, PollThatCompletesAfterShutdownIsDiscarded) { + Start(/* use_report= */ false, /* with_reasons= */ false); + ASSERT_TRUE(service_.WaitForPoll(0, 5s)); + Shutdown(); + + // The poll completes after the data source shuts down. + service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "stale")); + + // The data source discards the result. + ASSERT_TRUE(log_->WaitForMessage( + "Discarding the result of a poll that completed after shutdown", 5s)); + EXPECT_TRUE(sink_.WaitForInits(0, 0ms).empty()); + EXPECT_EQ(DataSourceState::kInitializing, status_manager_.Status().State()); } From 81339684e925181b7cca9377f86ee243a18126d0 Mon Sep 17 00:00:00 2001 From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:19:09 +0000 Subject: [PATCH 3/3] fix: Keep the Shutdown state when a ping poll completes after the stream fails Generated-by: termag --- .../data_sources/streaming_data_source.cpp | 7 +- .../data_sources/streaming_data_source.hpp | 5 +- .../tests/streaming_data_source_ping_test.cpp | 139 ++++++++++++++---- 3 files changed, 123 insertions(+), 28 deletions(-) diff --git a/libs/client-sdk/src/data_sources/streaming_data_source.cpp b/libs/client-sdk/src/data_sources/streaming_data_source.cpp index abaf1f81e..ca80e4300 100644 --- a/libs/client-sdk/src/data_sources/streaming_data_source.cpp +++ b/libs/client-sdk/src/data_sources/streaming_data_source.cpp @@ -186,6 +186,11 @@ void StreamingDataSource::HandleErrorStateChange(sse::Error error, 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; @@ -238,7 +243,7 @@ void StreamingDataSource::PollAfterPing() { return; } LD_LOG(logger_, LogLevel::kDebug) - << "Received ping, polling for flag updates"; + << "Polling for flag updates after a ping"; ping_poll_in_flight_ = true; auto weak_self = weak_from_this(); requester_.Request(ping_request_, diff --git a/libs/client-sdk/src/data_sources/streaming_data_source.hpp b/libs/client-sdk/src/data_sources/streaming_data_source.hpp index ec052aa49..686998430 100644 --- a/libs/client-sdk/src/data_sources/streaming_data_source.hpp +++ b/libs/client-sdk/src/data_sources/streaming_data_source.hpp @@ -25,6 +25,8 @@ 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 @@ -75,7 +77,8 @@ class StreamingDataSource final bool ping_poll_in_flight_ = false; bool ping_poll_pending_ = false; - // ShutdownAsync sets this, and it can run on a different thread. + // ShutdownAsync and an unrecoverable stream error set this. ShutdownAsync + // can run on a different thread. std::atomic stopped_{false}; }; } // namespace launchdarkly::client_side::data_sources diff --git a/libs/client-sdk/tests/streaming_data_source_ping_test.cpp b/libs/client-sdk/tests/streaming_data_source_ping_test.cpp index 95565a654..a4d712d25 100644 --- a/libs/client-sdk/tests/streaming_data_source_ping_test.cpp +++ b/libs/client-sdk/tests/streaming_data_source_ping_test.cpp @@ -55,6 +55,13 @@ using Request = http::request; char const* const kPingEvent = "event: ping\ndata: \n\n"; +// A patch for "flagB". A test sends it after other events, and waits for it to +// know that the data source has handled those events. +char const* const kPatchEvent = + "event: patch\n" + R"(data: {"key": "flagB", "version": 1, "value": true})" + "\n\n"; + // Returns a poll response body with one flag, "flagA". std::string FlagsJson(int version, std::string const& value) { return R"({"flagA":{"version":)" + std::to_string(version) + @@ -100,6 +107,18 @@ class RecordingLogBackend final : public ILogBackend { }); } + // Returns the number of messages that contain the text. + std::size_t Count(std::string const& text) { + std::lock_guard lock(mutex_); + std::size_t count = 0; + for (auto const& message : messages_) { + if (message.find(text) != std::string::npos) { + ++count; + } + } + return count; + } + private: std::mutex mutex_; std::condition_variable cv_; @@ -216,18 +235,7 @@ class PingService { std::string body) { boost::asio::post( ioc_, [this, index, status, body = std::move(body)]() mutable { - auto session = polls_.at(index); - session->response.result(status); - session->response.set(http::field::content_type, - "application/json"); - session->response.body() = std::move(body); - session->response.keep_alive(false); - session->response.prepare_payload(); - http::async_write(session->socket, session->response, - [session](beast::error_code ec, std::size_t) { - session->socket.shutdown( - tcp::socket::shutdown_send, ec); - }); + Respond(polls_.at(index), status, std::move(body)); }); } @@ -240,6 +248,16 @@ class PingService { }); } + // Closes the stream, and answers each later stream request with the + // status. The stream must be open. + void FailStream(http::status status) { + boost::asio::post(ioc_, [this, status] { + stream_failure_ = status; + beast::error_code ec; + stream_->socket.close(ec); + }); + } + private: struct Session { explicit Session(tcp::socket socket) : socket(std::move(socket)) {} @@ -273,6 +291,10 @@ class PingService { } if (std::string(session->request.target()).rfind("/meval", 0) == 0) { + if (stream_failure_) { + Respond(session, *stream_failure_, ""); + return; + } stream_ = session; Write(session, std::string("HTTP/1.1 200 OK\r\n" @@ -288,6 +310,22 @@ class PingService { }); } + // Sends one response, and then closes the connection. + static void Respond(std::shared_ptr const& session, + http::status status, + std::string body) { + session->response.result(status); + session->response.set(http::field::content_type, "application/json"); + session->response.body() = std::move(body); + session->response.keep_alive(false); + session->response.prepare_payload(); + http::async_write(session->socket, session->response, + [session](beast::error_code ec, std::size_t) { + session->socket.shutdown( + tcp::socket::shutdown_send, ec); + }); + } + // Writes the text after any earlier writes on the same connection. void Write(std::shared_ptr const& session, std::string text) { session->writes.push_back(std::move(text)); @@ -320,6 +358,7 @@ class PingService { std::vector> sessions_; std::vector> polls_; std::shared_ptr stream_; + std::optional stream_failure_; // Protected by mutex_. std::mutex mutex_; @@ -359,9 +398,12 @@ class StreamingDataSourcePingTest : public ::testing::Test { config::shared::builders::EndpointsBuilder() .RelayProxyBaseURL(service_.Url()) .Build(); + // A short reconnect delay keeps the tests that close the stream fast. + config::shared::built::StreamingConfig const + streaming_config{ + 10ms, Defaults::StreamingConfig().streaming_path}; config::shared::built::DataSourceConfig const - data_source_config{Defaults::StreamingConfig(), - with_reasons, use_report}; + data_source_config{streaming_config, with_reasons, use_report}; auto const http_properties = config::shared::builders::HttpPropertiesBuilder() .Build(); @@ -480,10 +522,7 @@ TEST_F(StreamingDataSourcePingTest, PingsDuringAPollCauseOneMorePoll) { service_.Send(kPingEvent); service_.Send(kPingEvent); service_.Send(kPingEvent); - service_.Send( - "event: patch\n" - R"(data: {"key": "flagB", "version": 1, "value": true})" - "\n\n"); + service_.Send(kPatchEvent); ASSERT_EQ(1u, sink_.WaitForUpserts(1, 5s).size()); // The data source applies the first poll, then polls one more time and @@ -494,25 +533,33 @@ TEST_F(StreamingDataSourcePingTest, PingsDuringAPollCauseOneMorePoll) { EXPECT_EQ((std::vector{"old", "new"}), FlagAValues(sink_.WaitForInits(2, 5s))); - // The next ping polls again. The three pings caused only one poll. + // No poll is in flight now, so the next ping polls at once. The patch + // after it shows that the data source has handled it. service_.Send(kPingEvent); + service_.Send(kPatchEvent); + ASSERT_EQ(2u, sink_.WaitForUpserts(2, 5s).size()); + EXPECT_EQ(3u, log_->Count("Received ping during a poll")); ASSERT_TRUE(service_.WaitForPoll(2, 5s)); EXPECT_EQ(3u, service_.PollCount()); } TEST_F(StreamingDataSourcePingTest, - ErrorStatusInterruptsAndNextPingPollsAgain) { + ErrorStatusInterruptsAndLaterPingsPollAgain) { Start(/* use_report= */ false, /* with_reasons= */ false); ASSERT_TRUE(service_.WaitForPoll(0, 5s)); service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "old")); ASSERT_TRUE(WaitForState(DataSourceState::kValid)); - // The poll after the next ping gets a server error. + // The poll after the next ping gets a server error. Another ping arrives + // while that poll is in flight. service_.Send(kPingEvent); ASSERT_TRUE(service_.WaitForPoll(1, 5s)); + service_.Send(kPingEvent); + service_.Send(kPatchEvent); + ASSERT_EQ(1u, sink_.WaitForUpserts(1, 5s).size()); service_.RespondToPoll(1, http::status::service_unavailable, ""); - // The data source reports the error and stays connected. + // The data source reports the error. auto const interrupted = WaitForState(DataSourceState::kInterrupted); ASSERT_TRUE(interrupted); ASSERT_TRUE(interrupted->LastError()); @@ -523,36 +570,54 @@ TEST_F(StreamingDataSourcePingTest, "the next ping", interrupted->LastError()->Message()); - // The next ping polls again and applies the result. - service_.Send(kPingEvent); + // Then it polls for the ping that arrived during the failed poll, and + // applies the result. ASSERT_TRUE(service_.WaitForPoll(2, 5s)); service_.RespondToPoll(2, http::status::ok, FlagsJson(2, "new")); EXPECT_TRUE(WaitForState(DataSourceState::kValid)); EXPECT_EQ((std::vector{"old", "new"}), FlagAValues(sink_.WaitForInits(2, 5s))); + + // The stream stays open, so the next ping polls again. + service_.Send(kPingEvent); + EXPECT_TRUE(service_.WaitForPoll(3, 5s)); } -TEST_F(StreamingDataSourcePingTest, NetworkErrorOnPollInterrupts) { +TEST_F(StreamingDataSourcePingTest, + NetworkErrorInterruptsAndLaterPingsPollAgain) { Start(/* use_report= */ false, /* with_reasons= */ false); ASSERT_TRUE(service_.WaitForPoll(0, 5s)); service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "old")); ASSERT_TRUE(WaitForState(DataSourceState::kValid)); // The connection of the poll after the next ping closes with no response. + // Another ping arrives while that poll is in flight. service_.Send(kPingEvent); ASSERT_TRUE(service_.WaitForPoll(1, 5s)); + service_.Send(kPingEvent); + service_.Send(kPatchEvent); + ASSERT_EQ(1u, sink_.WaitForUpserts(1, 5s).size()); service_.ClosePoll(1); + // The data source reports the error, and then polls for the ping that + // arrived during the failed poll. auto const interrupted = WaitForState(DataSourceState::kInterrupted); ASSERT_TRUE(interrupted); ASSERT_TRUE(interrupted->LastError()); EXPECT_EQ(ErrorKind::kNetworkError, interrupted->LastError()->Kind()); + EXPECT_TRUE(service_.WaitForPoll(2, 5s)); } TEST_F(StreamingDataSourcePingTest, PollThatCompletesAfterShutdownIsDiscarded) { Start(/* use_report= */ false, /* with_reasons= */ false); ASSERT_TRUE(service_.WaitForPoll(0, 5s)); - Shutdown(); + + // The test thread shuts the data source down, as the client does from the + // application thread. + auto done = std::make_shared>(); + source_->ShutdownAsync([done] { done->set_value(); }); + shut_down_ = true; + ASSERT_EQ(std::future_status::ready, done->get_future().wait_for(5s)); // The poll completes after the data source shuts down. service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "stale")); @@ -563,3 +628,25 @@ TEST_F(StreamingDataSourcePingTest, PollThatCompletesAfterShutdownIsDiscarded) { EXPECT_TRUE(sink_.WaitForInits(0, 0ms).empty()); EXPECT_EQ(DataSourceState::kInitializing, status_manager_.Status().State()); } + +TEST_F(StreamingDataSourcePingTest, + PollThatCompletesAfterTheStreamShutsDownIsDiscarded) { + Start(/* use_report= */ false, /* with_reasons= */ false); + ASSERT_TRUE(service_.WaitForPoll(0, 5s)); + + // The stream closes, and the service rejects the reconnect with an error + // that the data source cannot recover from. The poll is still in flight. + service_.FailStream(http::status::unauthorized); + auto const shut_down = WaitForState(DataSourceState::kShutdown); + ASSERT_TRUE(shut_down); + ASSERT_TRUE(shut_down->LastError()); + EXPECT_EQ(401, shut_down->LastError()->StatusCode()); + + // The poll completes after that. The data source discards the result and + // stays shut down. + service_.RespondToPoll(0, http::status::ok, FlagsJson(1, "stale")); + ASSERT_TRUE(log_->WaitForMessage( + "Discarding the result of a poll that completed after shutdown", 5s)); + EXPECT_TRUE(sink_.WaitForInits(0, 0ms).empty()); + EXPECT_EQ(DataSourceState::kShutdown, status_manager_.Status().State()); +}