Skip to content

Commit

Permalink
Add cleanup on Connection destruction
Browse files Browse the repository at this point in the history
  • Loading branch information
MPogotsky committed Nov 6, 2024
1 parent 6517e71 commit af86ff5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
19 changes: 15 additions & 4 deletions xapi/Connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ Connection::Connection(Connection &&other) noexcept
{
}

Connection::~Connection()
{
cancelAsyncOperations();
}

boost::asio::awaitable<void> Connection::connect(const boost::url &url)
{
const auto executor = co_await boost::asio::this_coro::executor;
Expand Down Expand Up @@ -74,10 +79,7 @@ boost::asio::awaitable<void> Connection::establishSSLConnection(

boost::asio::awaitable<void> Connection::disconnect()
{
m_cancellationSignal.emit(boost::asio::cancellation_type::all);
// Cancel all pending asynchronous operations
m_websocket.next_layer().next_layer().cancel();

cancelAsyncOperations();
try
{
co_await m_websocket.async_close(boost::beast::websocket::close_code::normal, boost::asio::use_awaitable);
Expand Down Expand Up @@ -177,5 +179,14 @@ boost::asio::awaitable<void> Connection::startKeepAlive(boost::asio::cancellatio
}
}

void Connection::cancelAsyncOperations() noexcept
{
m_cancellationSignal.emit(boost::asio::cancellation_type::all);
if (m_websocket.is_open())
{
m_websocket.next_layer().next_layer().cancel();
}
}

} // namespace internals
} // namespace xapi
12 changes: 9 additions & 3 deletions xapi/Connection.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ class Connection
public:
Connection() = delete;

Connection(const Connection &) = delete;
Connection &operator=(const Connection &) = delete;
Connection(const Connection &other) = delete;
Connection &operator=(const Connection &other) = delete;

Connection(Connection &&other) noexcept;
// Move assignment operator is not supported because of boost::beast::websocket::stream
Expand All @@ -47,7 +47,7 @@ class Connection
*/
explicit Connection(boost::asio::io_context &ioContext);

virtual ~Connection() = default;
virtual ~Connection();

/**
* @brief Asynchronously establishes secure WebSocket connection to the server.
Expand Down Expand Up @@ -101,6 +101,12 @@ class Connection
*/
boost::asio::awaitable<void> startKeepAlive(boost::asio::cancellation_slot cancellationSlot);

/**
* @brief Cancels all pending asynchronous operations and stops the keep-alive coroutine.
* @return void.
*/
void cancelAsyncOperations() noexcept;

// SSL context, stores certificates.
boost::asio::ssl::context m_sslContext;

Expand Down

0 comments on commit af86ff5

Please sign in to comment.