Skip to content

Commit

Permalink
better error handling in persistent connection read finisher
Browse files Browse the repository at this point in the history
  • Loading branch information
mrbald committed Apr 30, 2024
1 parent 17734af commit d6f2bd0
Showing 1 changed file with 26 additions and 20 deletions.
46 changes: 26 additions & 20 deletions CRUD/service/persistent_connection.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,16 +76,20 @@ class persistent_connection
[this](boost::system::error_code ec, std::size_t bytes_transferred)
{

if (!ec)
if (!ec) [[likely]]
{
request_parser::result_type result;
char * data = nullptr;
std::tie(result, data) = request_parser_.parse(
request_, buffer_.data(), buffer_.data() + bytes_transferred);

if (result == request_parser::good) {
read_data_if(data, bytes_transferred);
request_handler_.handle_request(request_, reply_);
if (result == request_parser::good) [[likely]]
{
ec = read_data_if(data, bytes_transferred);
if (!ec) [[likely]]
{
request_handler_.handle_request(request_, reply_);
}
do_write();
}
else if (result == request_parser::bad)
Expand Down Expand Up @@ -122,24 +126,26 @@ class persistent_connection
});
}

void read_data_if(char *data, std::size_t bytes_transferred) {
boost::system::error_code read_data_if(char *data, std::size_t bytes_transferred) {
static constexpr auto is_content_length = [](const header &h) noexcept { return h.name == "content-length" ; };

auto itr = std::find_if( request_.headers.begin(),
request_.headers.end(),
[](const header &h) { return h.name == "content-length" ; }
) ;
boost::system::error_code ec{};
if (data) {
auto itr = find_if(begin(request_.headers), end(request_.headers), is_content_length);

if (data && itr != request_.headers.end()) {
auto received_data_size = std::distance(data, buffer_.data() + bytes_transferred);
auto content_length_value = boost::lexical_cast<long>(itr->value);
request_.data = std::string(data, content_length_value);
if (received_data_size < content_length_value) {
auto left_over_size = content_length_value - received_data_size;
auto end_data_ptr = request_.data.data() + received_data_size;
auto left_over_buffer = boost::asio::buffer(end_data_ptr, left_over_size);
boost::asio::read(socket_, left_over_buffer);
}
}
if (itr != end(request_.headers)) {
auto received_data_size = std::distance(data, buffer_.data() + bytes_transferred);
auto content_length_value = boost::lexical_cast<long>(itr->value);
request_.data = std::string(data, content_length_value);
if (received_data_size < content_length_value) {
auto left_over_size = content_length_value - received_data_size;
auto end_data_ptr = request_.data.data() + received_data_size;
auto left_over_buffer = boost::asio::buffer(end_data_ptr, left_over_size);
boost::asio::read(socket_, left_over_buffer, ec);
}
}
}
return ec;
}

/// Socket for the persistent_connection.
Expand Down

0 comments on commit d6f2bd0

Please sign in to comment.