Skip to content

Commit

Permalink
feat: Adds timeout to Connect()
Browse files Browse the repository at this point in the history
Only in HttpSocket. HttpsSocket will be addressed
in later commit.
  • Loading branch information
aritosteles committed Dec 13, 2024
1 parent 9a9a3c2 commit 5d7da1e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/agent/communicator/src/http_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ namespace http_client

boost::system::error_code ec;

socket->Connect(results, ec);
socket->Connect(io_context, results, ec, std::chrono::seconds(2));

if (ec)
{
Expand Down
29 changes: 26 additions & 3 deletions src/agent/communicator/src/http_socket.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,37 @@ namespace http_client
}

/// @brief Connects the socket to the given endpoints
/// @param io_context The io_context associated to the socket
/// @param endpoints The endpoints to connect to
/// @param ec The error code, if any occurred
void Connect(const boost::asio::ip::tcp::resolver::results_type& endpoints,
boost::system::error_code& ec) override
/// @param timeOut The timeout for the connection
void Connect(boost::asio::io_context& io_context,
const boost::asio::ip::tcp::resolver::results_type& endpoints,
boost::system::error_code& ec,
const std::chrono::seconds timeOut = std::chrono::seconds(TIMEOUT_DEFAULT)) override
{
try
{
boost::asio::connect(m_socket, endpoints, ec);
bool connectionSuccess = false;

boost::asio::async_connect(m_socket,
endpoints,
[&](const boost::system::error_code& errorCode, const auto&)
{
if (!errorCode)
{
connectionSuccess = true;
ec = errorCode;
LogDebug("Connected successfully");
}
});

io_context.run_for(timeOut); // Run for 2 seconds();
if (!connectionSuccess)
{
ec = boost::asio::error::timed_out;
LogDebug("Connection timed out");
}
}
catch (const std::exception& e)
{
Expand Down
6 changes: 4 additions & 2 deletions src/agent/communicator/src/https_socket.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ namespace http_client
/// @brief Connects the socket to the given endpoints
/// @param endpoints The endpoints to connect to
/// @param ec The error code, if any occurred
void Connect(const boost::asio::ip::tcp::resolver::results_type& endpoints,
boost::system::error_code& ec) override
void Connect([[maybe_unused]] boost::asio::io_context& io_context,
const boost::asio::ip::tcp::resolver::results_type& endpoints,
boost::system::error_code& ec,
[[maybe_unused]] const std::chrono::seconds timeout = std::chrono::seconds(2)) override
{
try
{
Expand Down

0 comments on commit 5d7da1e

Please sign in to comment.