xbot/watchdog_thread.cpp
2024-03-03 12:27:36 -08:00

81 lines
1.6 KiB
C++

#include "watchdog_thread.hpp"
#include "connection.hpp"
#include "irc_parse_thread.hpp"
#include "write_irc.hpp"
#include <boost/asio/steady_timer.hpp>
#include <chrono>
#include <memory>
WatchdogThread::WatchdogThread(Connection& connection)
: connection_{connection}
, timer_{connection.get_executor()}
, stalled_{false}
{
}
auto WatchdogThread::on_activity() -> void
{
stalled_ = false;
timer_.expires_from_now(WatchdogThread::TIMEOUT);
}
auto WatchdogThread::start_timer()
{
timer_.async_wait([weak = weak_from_this()](auto const& error)
{
if (not error)
{
if (auto self = weak.lock())
{
self->on_timeout();
}
}
});
}
auto WatchdogThread::on_timeout() -> void
{
if (stalled_)
{
connection_.close();
}
else
{
send_ping(connection_, "watchdog");
stalled_ = true;
timer_.expires_from_now(WatchdogThread::TIMEOUT);
start_timer();
}
}
auto WatchdogThread::on_connect() -> void
{
on_activity();
start_timer();
}
auto WatchdogThread::on_disconnect() -> void
{
timer_.cancel();
}
auto WatchdogThread::start(Connection& connection) -> void
{
auto const thread = std::make_shared<WatchdogThread>(connection);
connection.add_listener<ConnectEvent>([thread](auto&)
{
thread->on_connect();
});
connection.add_listener<DisconnectEvent>([thread](auto&)
{
thread->on_disconnect();
});
connection.add_listener<IrcMsgEvent>([thread](auto&)
{
thread->on_activity();
});
}