Skip to content

Commit

Permalink
[C++] Use weak ref to ClientConnection for timeout task (apache#12409)
Browse files Browse the repository at this point in the history
### Motivation

Fixes apache#12408. Using a weak reference in the timeout task for `ClientConnection` to break a circular reference dependency between the connection instance and the task.
  • Loading branch information
merlimat authored Oct 19, 2021
1 parent 4da4310 commit 4e43a1d
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions pulsar-client-cpp/lib/ClientConnection.cc
Original file line number Diff line number Diff line change
Expand Up @@ -532,18 +532,25 @@ void ClientConnection::handleResolve(const boost::system::error_code& err,
return;
}

auto self = shared_from_this();
connectTimeoutTask_->setCallback([this, self](const PeriodicTask::ErrorCode& ec) {
if (state_ != Ready) {
LOG_ERROR(cnxString_ << "Connection was not established in " << connectTimeoutTask_->getPeriodMs()
<< " ms, close the socket");
auto self = ClientConnectionWeakPtr(shared_from_this());

connectTimeoutTask_->setCallback([self](const PeriodicTask::ErrorCode& ec) {
ClientConnectionPtr ptr = self.lock();
if (!ptr) {
// Connection was already destroyed
return;
}

if (ptr->state_ != Ready) {
LOG_ERROR(ptr->cnxString_ << "Connection was not established in "
<< ptr->connectTimeoutTask_->getPeriodMs() << " ms, close the socket");
PeriodicTask::ErrorCode err;
socket_->close(err);
ptr->socket_->close(err);
if (err) {
LOG_WARN(cnxString_ << "Failed to close socket: " << err.message());
LOG_WARN(ptr->cnxString_ << "Failed to close socket: " << err.message());
}
}
connectTimeoutTask_->stop();
ptr->connectTimeoutTask_->stop();
});

LOG_DEBUG(cnxString_ << "Connecting to " << endpointIterator->endpoint() << "...");
Expand Down

0 comments on commit 4e43a1d

Please sign in to comment.