Files
Library/include/Void/Fsm/Detail/Awaiter.hpp
T

122 lines
3.2 KiB
C++

#pragma once
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <coroutine>
#include <optional>
#include <span>
#include <stop_token>
#include <typeinfo>
#include <utility>
namespace Void::Fsm::Detail
{
struct WaiterCancelFn {
ExecutionContext* ctx{nullptr};
ExecutionContext::WaiterId waiter_id{0};
void operator()() const
{
if (ctx != nullptr && waiter_id != 0) {
(void)ctx->try_post_control(
[c = ctx, wid = waiter_id] { c->cancel_waiter(wid); });
}
}
};
/// Unified awaiter for awaiting an event (or event set), optional timeout
/// on injected clock, and cooperative stop cancellation across both
/// per-state scope stop and caller-supplied OperationOptions stop tokens.
template <typename Storage, typename Resume> struct EventAwaiter {
ExecutionContext* ctx{nullptr};
Storage types{};
EventEnvelope env{};
bool timed_out{false};
bool cancelled{false};
std::optional<Time::MonotonicClock::time_point> deadline{};
Resume resume{};
ExecutionContext::ScopeId scope{ExecutionContext::kNoScope};
std::stop_token scope_stop{};
std::stop_token user_stop{};
ExecutionContext::WaiterId waiter_id{0};
std::optional<std::stop_callback<WaiterCancelFn>> scope_cb{};
std::optional<std::stop_callback<WaiterCancelFn>> user_cb{};
[[nodiscard]] bool await_ready()
{
if (scope_stop.stop_requested() || user_stop.stop_requested()) {
cancelled = true;
return true;
}
if (ctx != nullptr && !types.empty() &&
ctx->try_take_any(span(), env)) {
return true;
}
if (deadline.has_value() && ctx != nullptr &&
ctx->clock().now() >= *deadline) {
timed_out = true;
return true;
}
return false;
}
void await_suspend(std::coroutine_handle<> h)
{
waiter_id = ctx->set_waiter(span(), h, &env, &timed_out,
deadline, scope, &cancelled);
if (scope_stop.stop_possible()) {
scope_cb.emplace(scope_stop,
WaiterCancelFn{ctx, waiter_id});
}
if (user_stop.stop_possible()) {
user_cb.emplace(user_stop, WaiterCancelFn{ctx, waiter_id});
}
}
decltype(auto) await_resume()
{
scope_cb.reset();
user_cb.reset();
if constexpr (std::is_invocable_v<Resume&, EventEnvelope&&,
bool, bool>) {
return resume(std::move(env), timed_out, cancelled);
} else {
return resume(std::move(env), timed_out);
}
}
private:
[[nodiscard]] std::span<const std::type_info* const> span() const
{
return std::span<const std::type_info* const>{types};
}
};
template <typename Storage, typename Resume>
[[nodiscard]] auto make_event_awaiter(
ExecutionContext* ctx, Storage types,
std::optional<Time::MonotonicClock::time_point> deadline,
Resume resume,
ExecutionContext::ScopeId scope = ExecutionContext::kNoScope,
std::stop_token scope_stop = {}, std::stop_token user_stop = {})
{
return EventAwaiter<Storage, Resume>{
ctx,
std::move(types),
{},
false,
false,
deadline,
std::move(resume),
scope,
std::move(scope_stop),
std::move(user_stop),
0,
std::nullopt,
std::nullopt};
}
} // namespace Void::Fsm::Detail