xbot/watchdog_thread.cpp

94 lines
1.9 KiB
C++
Raw Normal View History

2023-11-25 09:22:55 -08:00
#include "watchdog_thread.hpp"
#include "connection.hpp"
#include "irc_parse_thread.hpp"
2023-11-25 20:09:20 -08:00
#include "write_irc.hpp"
#include <boost/asio/steady_timer.hpp>
2023-11-25 09:22:55 -08:00
#include <chrono>
2023-11-25 20:09:20 -08:00
#include <memory>
2023-11-25 09:22:55 -08:00
using namespace std::chrono_literals;
2023-11-25 20:09:20 -08:00
namespace {
2023-11-25 09:22:55 -08:00
2023-11-25 20:09:20 -08:00
struct WatchdogThread : std::enable_shared_from_this<WatchdogThread>
2023-11-25 09:22:55 -08:00
{
2023-11-26 15:32:52 -08:00
WatchdogThread(Connection& connection)
2023-11-25 20:09:20 -08:00
: connection_{connection}
2023-11-26 15:32:52 -08:00
, timer_{connection.get_executor()}
2023-11-25 20:09:20 -08:00
, tried_ping{false}
{
}
2023-11-25 09:22:55 -08:00
2023-11-26 15:32:52 -08:00
Connection& connection_;
2023-11-25 20:09:20 -08:00
boost::asio::steady_timer timer_;
bool tried_ping;
auto on_activity() -> void
2023-11-25 09:22:55 -08:00
{
2023-11-25 20:09:20 -08:00
tried_ping = false;
2023-11-25 09:22:55 -08:00
timer_.expires_from_now(30s);
}
2023-11-25 20:09:20 -08:00
auto timeout_token()
2023-11-25 09:22:55 -08:00
{
2023-11-25 20:09:20 -08:00
return [weak = weak_from_this()](auto const& error)
2023-11-25 09:22:55 -08:00
{
if (not error)
{
if (auto self = weak.lock())
{
2023-11-25 20:09:20 -08:00
self->on_timeout();
2023-11-25 09:22:55 -08:00
}
}
2023-11-25 20:09:20 -08:00
};
2023-11-25 09:22:55 -08:00
}
2023-11-25 20:09:20 -08:00
auto on_timeout() -> void
{
if (tried_ping)
{
2023-11-26 15:32:52 -08:00
connection_.close();
2023-11-25 20:09:20 -08:00
}
else
{
2023-11-26 15:32:52 -08:00
send_ping(connection_, "watchdog");
2023-11-25 20:09:20 -08:00
tried_ping = true;
timer_.expires_from_now(30s);
timer_.async_wait(timeout_token());
}
}
auto on_connect() -> void
{
on_activity();
timer_.async_wait(timeout_token());
}
auto on_disconnect() -> void
{
timer_.cancel();
}
};
} // namespace
2023-11-26 15:32:52 -08:00
auto watchdog_thread(Connection& connection) -> void
2023-11-25 20:09:20 -08:00
{
auto const thread = std::make_shared<WatchdogThread>(connection);
2023-11-26 15:32:52 -08:00
connection.add_listener<ConnectEvent>([thread](auto&)
2023-11-25 20:09:20 -08:00
{
thread->on_connect();
});
2023-11-26 15:32:52 -08:00
connection.add_listener<DisconnectEvent>([thread](auto&)
2023-11-25 20:09:20 -08:00
{
thread->on_disconnect();
});
2023-11-26 15:32:52 -08:00
connection.add_listener<IrcMsgEvent>([thread](auto&)
2023-11-25 20:09:20 -08:00
{
thread->on_activity();
});
2023-11-25 09:22:55 -08:00
}