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
15 changes: 11 additions & 4 deletions libs/client-sdk/src/data_sources/streaming_data_source.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@

StreamingDataSource::StreamingDataSource(
config::shared::built::ServiceEndpoints const& endpoints,
config::shared::built::DataSourceConfig<config::shared::ClientSDK> const&

Check warning on line 24 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:24:5 [modernize-pass-by-value]

pass by value and use std::move
data_source_config,
config::shared::built::HttpProperties const& http_properties,

Check warning on line 26 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:26:5 [modernize-pass-by-value]

pass by value and use std::move
boost::asio::any_io_executor ioc,

Check warning on line 27 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:27:5 [modernize-pass-by-value]

pass by value and use std::move
Context context,
IDataSourceUpdateSink& handler,
DataSourceStatusManager& status_manager,
Logger const& logger)
: exec_(ioc),

Check warning on line 32 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:32:13 [performance-unnecessary-value-param]

parameter 'ioc' is passed by value and only copied once; consider moving it to avoid unnecessary copies
logger_(logger),
context_(std::move(context)),
status_manager_(status_manager),
Expand All @@ -39,7 +39,7 @@
data_source_config_(data_source_config),
streaming_endpoint_(endpoints.StreamingBaseUrl()) {}

void StreamingDataSource::Start() {

Check warning on line 42 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:42:27 [readability-function-cognitive-complexity]

function 'Start' has cognitive complexity of 27 (threshold 25)
status_manager_.SetState(DataSourceStatus::DataSourceState::kInitializing);
auto string_context =
boost::json::serialize(boost::json::value_from(context_));
Expand Down Expand Up @@ -129,10 +129,17 @@

client_builder.receiver([weak_self](launchdarkly::sse::Event const& event) {
if (auto self = weak_self.lock()) {
self->data_source_handler_.HandleMessage(event.type(),
event.data());
// TODO: Use the result of handle message to restart the
// event source if we got bad data. sc-204387
auto const status = self->data_source_handler_.HandleMessage(
event.type(), event.data());
if (status ==
DataSourceEventHandler::MessageStatus::kInvalidMessage) {
LD_LOG(self->logger_, LogLevel::kWarn)
<< "Received invalid data from stream, restarting "
"connection";
if (self->client_) {
self->client_->async_restart("invalid data in stream");
}
}
}
});

Expand Down Expand Up @@ -175,11 +182,11 @@
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 185 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:185: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 189 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:189: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 +195,21 @@
state,
static_cast<DataSourceStatusManager::StatusCodeType>(
error.status),
std::move(error_string));

Check warning on line 198 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:198: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 205 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:205: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 212 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:212: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 Down
230 changes: 230 additions & 0 deletions libs/client-sdk/tests/streaming_data_source_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
#include <gtest/gtest.h>

#include "data_sources/data_source_status_manager.hpp"
#include "data_sources/data_source_update_sink.hpp"
#include "data_sources/streaming_data_source.hpp"

#include <launchdarkly/config/shared/builders/endpoints_builder.hpp>
#include <launchdarkly/config/shared/builders/http_properties_builder.hpp>
#include <launchdarkly/context_builder.hpp>
#include <launchdarkly/logging/logger.hpp>

#include <boost/asio/executor_work_guard.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/write.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>

#include <chrono>
#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>

using namespace launchdarkly;
using namespace launchdarkly::client_side;
using namespace launchdarkly::client_side::data_sources;
using namespace std::chrono_literals;

using config::shared::ClientSDK;

namespace beast = boost::beast;
namespace http = beast::http;
using tcp = boost::asio::ip::tcp;

namespace {

Logger MakeNullLogger() {
struct NullBackend : ILogBackend {
bool Enabled(LogLevel) noexcept override { return false; }
void Write(LogLevel, std::string) noexcept override {}
};
return Logger{std::make_shared<NullBackend>()};
}

class NoopSink final : public IDataSourceUpdateSink {
public:
void Init(Context const&,
std::unordered_map<std::string, ItemDescriptor>) override {}
void Upsert(Context const&, std::string, ItemDescriptor) override {}
void Apply(Context const&, FlagChangeSet, bool) override {}
};

// Serves a stream that sends a fixed event on the first connection. Every
// connection stays open until the client closes it. Counts the connections.
//
// Thread safety: the accept and session handlers run on the io_context passed
// to the constructor. WaitForConnections is safe from any thread. The
// connection count is protected by mutex_.
class StreamService {
public:
StreamService(boost::asio::io_context& ioc, std::string first_event)
: acceptor_(ioc,
tcp::endpoint(boost::asio::ip::make_address("127.0.0.1"),
/* port= */ 0)),
first_event_(std::move(first_event)) {
Accept();
}

[[nodiscard]] std::string Url() const {
return "http://127.0.0.1:" +
std::to_string(acceptor_.local_endpoint().port());
}

// Returns true when the service has received at least count stream
// connections before the timeout.
bool WaitForConnections(int count, std::chrono::milliseconds timeout) {
std::unique_lock lock(mutex_);
return cv_.wait_for(lock, timeout,
[this, count] { return connections_ >= count; });
}

private:
struct Session : std::enable_shared_from_this<Session> {
Session(tcp::socket socket, StreamService* 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;
}
self->Stream(self->service->CountConnection());
});
}

// Writes the response head, and the event if this is the first
// connection, but does not end the response.
void Stream(int connection) {
stream_text =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/event-stream\r\n"
"\r\n";
if (connection == 1) {
stream_text += service->first_event_;
}
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&) {});
});
}

tcp::socket socket;
beast::flat_buffer buffer;
http::request<http::string_body> request;
std::string stream_text;
StreamService* service;
};

void Accept() {
acceptor_.async_accept(
[this](beast::error_code const& ec, tcp::socket socket) {
if (ec) {
return;
}
std::make_shared<Session>(std::move(socket), this)->Run();
Accept();
});
}

// Returns the number of connections, this one included.
int CountConnection() {
std::lock_guard lock(mutex_);
++connections_;
cv_.notify_all();
return connections_;
}

tcp::acceptor acceptor_;
std::string const first_event_;

// Protected by mutex_.
std::mutex mutex_;
std::condition_variable cv_;
int connections_ = 0;
};

struct InvalidEvent {
std::string name;
std::string event;
};

} // namespace

class StreamingDataSourceInvalidDataTest
: public ::testing::TestWithParam<InvalidEvent> {};

TEST_P(StreamingDataSourceInvalidDataTest, RestartsTheStream) {
boost::asio::io_context ioc;
auto work = boost::asio::make_work_guard(ioc);
StreamService service(ioc, GetParam().event);

auto const endpoints =
config::shared::builders::EndpointsBuilder<ClientSDK>()
.RelayProxyBaseURL(service.Url())
.Build();
ASSERT_TRUE(endpoints);
config::shared::built::DataSourceConfig<ClientSDK> const data_source_config{
config::shared::built::StreamingConfig<ClientSDK>{
/* initial_reconnect_delay= */ 1ms, /* streaming_path= */ "/meval"},
/* with_reasons= */ false, /* use_report= */ false};
auto const http_properties =
config::shared::builders::HttpPropertiesBuilder<ClientSDK>().Build();

auto const logger = MakeNullLogger();
DataSourceStatusManager status_manager;
NoopSink sink;
auto source = std::make_shared<StreamingDataSource>(
*endpoints, data_source_config, http_properties, ioc.get_executor(),
ContextBuilder().Kind("user", "user-key").Build(), sink, status_manager,
logger);

// Start the data source. The stream sends the invalid event and stays
// open.
source->Start();
std::thread thread([&ioc] { ioc.run(); });

// The data source must close the stream and open a new one.
EXPECT_TRUE(service.WaitForConnections(2, 5s));

std::promise<void> 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();
}

INSTANTIATE_TEST_SUITE_P(
InvalidEvents,
StreamingDataSourceInvalidDataTest,
::testing::Values(
InvalidEvent{"MalformedPut", "event: put\ndata: {sorry\n\n"},
InvalidEvent{"MalformedPatch", "event: patch\ndata: {sorry\n\n"},
InvalidEvent{"MalformedDelete", "event: delete\ndata: {sorry\n\n"},
InvalidEvent{"SchemaMismatchPut",
"event: put\ndata: {\"potato\": {}}\n\n"},
InvalidEvent{"SchemaMismatchPatch",
"event: patch\ndata: {\"potato\": {}}\n\n"},
InvalidEvent{"SchemaMismatchDelete",
"event: delete\ndata: {\"potato\": {}}\n\n"}),
[](::testing::TestParamInfo<InvalidEvent> const& info) {
return info.param.name;
});
10 changes: 8 additions & 2 deletions libs/server-sent-events/src/curl_client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
#include "parser.hpp"

#include <curl/curl.h>
#ifndef _WIN32
#include <sys/socket.h>
#endif
#include <boost/asio/any_io_executor.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/beast/http/string_body.hpp>
Expand Down Expand Up @@ -199,10 +202,13 @@ class CurlClient final : public Client,
return;
}
if (curl_socket_ != CURL_SOCKET_BAD) {
// Shut down the socket, but do not close it. CURL then reads
// the end of the stream and ends the transfer. CURL does not
// get a notification when other code closes its socket.
#ifdef _WIN32
closesocket(curl_socket_);
::shutdown(curl_socket_, SD_BOTH);
#else
close(curl_socket_);
::shutdown(curl_socket_, SHUT_RDWR);
#endif
curl_socket_ = CURL_SOCKET_BAD;
}
Expand Down
Loading