Files
Library/include/Void/Async/Operation.hpp
T

410 lines
13 KiB
C++

#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <atomic>
#include <coroutine>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <type_traits>
#include <utility>
namespace Void::Async
{
enum class StopBehavior {
notify_only,
settle_cancelled
};
// Move-only, single-delivery handle for resuming a suspended continuation on
// its bound completion lane (or inline when no executor was supplied).
class ResumeTicket
{
public:
ResumeTicket() noexcept = default;
explicit ResumeTicket(std::coroutine_handle<> handle,
Executor* executor = nullptr) noexcept
: handle_(handle)
, executor_(executor)
{
}
ResumeTicket(ResumeTicket&& other) noexcept
: handle_(std::exchange(other.handle_, {}))
, executor_(std::exchange(other.executor_, nullptr))
{
}
ResumeTicket& operator=(ResumeTicket&& other) noexcept
{
if (this != &other) {
handle_ = std::exchange(other.handle_, {});
executor_ = std::exchange(other.executor_, nullptr);
}
return *this;
}
ResumeTicket(const ResumeTicket&) = delete;
ResumeTicket& operator=(const ResumeTicket&) = delete;
[[nodiscard]] explicit operator bool() const noexcept
{
return static_cast<bool>(handle_);
}
[[nodiscard]] std::coroutine_handle<> handle() const noexcept { return handle_; }
[[nodiscard]] Executor* executor() const noexcept { return executor_; }
void dispatch()
{
auto h = std::exchange(handle_, {});
auto* ex = std::exchange(executor_, nullptr);
if (!h) {
return;
}
if (ex != nullptr) {
ex->post_completion(h);
} else {
h.resume();
}
}
void resume_inline()
{
auto h = std::exchange(handle_, {});
executor_ = nullptr;
if (h) {
h.resume();
}
}
[[nodiscard]] std::coroutine_handle<> release() noexcept
{
executor_ = nullptr;
return std::exchange(handle_, {});
}
private:
std::coroutine_handle<> handle_{};
Executor* executor_{nullptr};
};
// Thread-safe shared operation state arbitrating backend work refs, external
// stop intent, single-winner outcome selection, and post-backend-release
// continuation delivery.
template <typename T = void>
class OperationState : public std::enable_shared_from_this<OperationState<T>>
{
public:
using OutcomeType = std::expected<T, Void::Result::Error>;
struct Awaitable {
std::shared_ptr<OperationState<T>> state;
Executor* resume_executor{nullptr};
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) noexcept
{
return state->try_arm_suspend(handle, resume_executor);
}
[[nodiscard]] OutcomeType await_resume()
{
return state->take_result();
}
};
[[nodiscard]] static std::shared_ptr<OperationState<T>> create(
OperationOptions options = {},
Executor* resume_executor = nullptr,
StopBehavior stop_behavior = StopBehavior::notify_only)
{
auto ptr = std::shared_ptr<OperationState<T>>(
new OperationState<T>(resume_executor, stop_behavior, options.deadline));
if (options.stop.stop_possible()) {
ptr->stop_cb_.emplace(options.stop, StopForwarder{ptr.get()});
}
return ptr;
}
OperationState(const OperationState&) = delete;
OperationState& operator=(const OperationState&) = delete;
OperationState(OperationState&&) = delete;
OperationState& operator=(OperationState&&) = delete;
[[nodiscard]] std::stop_token stop_token() const noexcept
{
return stop_source_.get_token();
}
[[nodiscard]] bool stop_requested() const noexcept
{
return (sync_.load(std::memory_order_acquire) & kStopRequestedFlag) != 0 ||
stop_source_.stop_requested();
}
[[nodiscard]] const std::optional<Void::Time::MonotonicClock::time_point>&
deadline() const noexcept
{
return deadline_;
}
[[nodiscard]] bool is_deadline_expired(
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance()) const noexcept
{
return deadline_.has_value() && clock.now() >= *deadline_;
}
bool request_stop() noexcept
{
sync_.fetch_or(kStopRequestedFlag, std::memory_order_acq_rel);
const bool triggered = stop_source_.request_stop();
if (stop_behavior_ == StopBehavior::settle_cancelled) {
if (auto ticket = try_commit_cancelled("Operation cancelled");
ticket.has_value()) {
ticket->dispatch();
}
}
return triggered;
}
void acquire_backend_ref() noexcept
{
sync_.fetch_add(kRefStep, std::memory_order_acq_rel);
}
[[nodiscard]] std::optional<ResumeTicket> release_backend_ref() noexcept
{
const std::uint64_t prev = sync_.fetch_sub(kRefStep, std::memory_order_acq_rel);
const std::uint64_t cur = prev - kRefStep;
if ((cur >> kRefShift) != 0) {
return std::nullopt;
}
return maybe_claim_ticket();
}
void release_backend_ref_and_dispatch()
{
if (auto ticket = release_backend_ref(); ticket.has_value()) {
ticket->dispatch();
}
}
template <typename U = T>
requires (!std::is_void_v<U>)
[[nodiscard]] std::optional<ResumeTicket> try_commit_value(U value)
{
return settle_with(DomainOutcomeKind::succeeded,
[&](std::optional<OutcomeType>& slot) {
slot.emplace(std::in_place, std::move(value));
});
}
template <typename U = T>
requires (std::is_void_v<U>)
[[nodiscard]] std::optional<ResumeTicket> try_commit_value()
{
return settle_with(DomainOutcomeKind::succeeded,
[](std::optional<OutcomeType>& slot) {
slot.emplace();
});
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_error(
Void::Result::Error err,
DomainOutcomeKind kind = DomainOutcomeKind::failed)
{
return settle_with(kind, [&](std::optional<OutcomeType>& slot) {
slot.emplace(std::unexpected{std::move(err)});
});
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_not_committed(
std::string message = "Operation stopped before commit")
{
return try_commit_error(
make_async_error(AsyncErrorCode::cancelled, std::move(message)),
DomainOutcomeKind::not_committed);
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_unknown(
std::string message = "Commit state unknown after backend failure")
{
return try_commit_error(
make_async_error(AsyncErrorCode::backend_error, std::move(message)),
DomainOutcomeKind::unknown);
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_cancelled(
std::string message = "Operation cancelled")
{
return try_commit_error(
make_async_error(AsyncErrorCode::cancelled, std::move(message)),
DomainOutcomeKind::cancelled);
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_timeout(
std::string message = "Operation deadline expired")
{
return try_commit_error(
make_async_error(AsyncErrorCode::timeout, std::move(message)),
DomainOutcomeKind::failed);
}
[[nodiscard]] bool try_arm_suspend(std::coroutine_handle<> continuation,
Executor* resume_exec = nullptr) noexcept
{
continuation_ = continuation;
if (resume_exec != nullptr) {
resume_executor_ = resume_exec;
}
std::uint64_t cur = sync_.load(std::memory_order_acquire);
for (;;) {
if ((cur & kSettledFlag) != 0 &&
(cur >> kRefShift) == 0 &&
(cur & kDispatchedFlag) == 0) {
if (sync_.compare_exchange_weak(
cur,
cur | kSuspendedFlag | kDispatchedFlag,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
continuation_ = {};
resume_executor_ = nullptr;
return false;
}
} else {
if (sync_.compare_exchange_weak(
cur,
cur | kSuspendedFlag,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
return true;
}
}
}
}
[[nodiscard]] bool is_settled() const noexcept
{
return (sync_.load(std::memory_order_acquire) & kSettledFlag) != 0;
}
[[nodiscard]] std::uint64_t backend_ref_count() const noexcept
{
return sync_.load(std::memory_order_acquire) >> kRefShift;
}
[[nodiscard]] DomainOutcomeKind outcome_kind() const noexcept
{
return domain_outcome_.load(std::memory_order_acquire);
}
[[nodiscard]] OutcomeType take_result()
{
// Acquire on sync_ ensures visibility of the winner's write to outcome_.
(void)sync_.load(std::memory_order_acquire);
if (!outcome_.has_value()) {
return std::unexpected{make_async_error(
AsyncErrorCode::backend_error,
"OperationState result accessed before settlement")};
}
return std::move(*outcome_);
}
[[nodiscard]] Awaitable awaitable(Executor* resume_exec = nullptr) noexcept
{
return Awaitable{this->shared_from_this(), resume_exec};
}
[[nodiscard]] Awaitable operator co_await() noexcept
{
return awaitable(nullptr);
}
private:
static constexpr std::uint64_t kSettledFlag = 1ULL << 0;
static constexpr std::uint64_t kSuspendedFlag = 1ULL << 1;
static constexpr std::uint64_t kDispatchedFlag = 1ULL << 2;
static constexpr std::uint64_t kStopRequestedFlag = 1ULL << 3;
static constexpr std::uint64_t kRefShift = 4;
static constexpr std::uint64_t kRefStep = 1ULL << kRefShift;
struct StopForwarder {
OperationState* self{nullptr};
void operator()() const noexcept
{
if (self != nullptr) {
self->request_stop();
}
}
};
OperationState(Executor* resume_executor,
StopBehavior stop_behavior,
std::optional<Void::Time::MonotonicClock::time_point> deadline) noexcept
: stop_behavior_(stop_behavior)
, deadline_(deadline)
, resume_executor_(resume_executor)
{
}
template <typename InitFn>
[[nodiscard]] std::optional<ResumeTicket> settle_with(
DomainOutcomeKind kind, InitFn&& init_fn)
{
if (outcome_claimed_.exchange(true, std::memory_order_acq_rel)) {
return std::nullopt;
}
init_fn(outcome_);
domain_outcome_.store(kind, std::memory_order_release);
sync_.fetch_or(kSettledFlag, std::memory_order_acq_rel);
return maybe_claim_ticket();
}
[[nodiscard]] std::optional<ResumeTicket> maybe_claim_ticket() noexcept
{
std::uint64_t cur = sync_.load(std::memory_order_acquire);
for (;;) {
if ((cur & kSettledFlag) == 0 ||
(cur & kSuspendedFlag) == 0 ||
(cur & kDispatchedFlag) != 0 ||
(cur >> kRefShift) != 0) {
return std::nullopt;
}
if (sync_.compare_exchange_weak(
cur,
cur | kDispatchedFlag,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
return ResumeTicket{
std::exchange(continuation_, {}),
std::exchange(resume_executor_, nullptr)};
}
}
}
std::stop_source stop_source_{};
StopBehavior stop_behavior_{StopBehavior::notify_only};
std::optional<Void::Time::MonotonicClock::time_point> deadline_{};
std::atomic<std::uint64_t> sync_{0};
std::atomic<bool> outcome_claimed_{false};
std::atomic<DomainOutcomeKind> domain_outcome_{DomainOutcomeKind::pending};
std::optional<OutcomeType> outcome_{};
std::coroutine_handle<> continuation_{};
Executor* resume_executor_{nullptr};
// MUST stay LAST: destroyed first in ~OperationState() to synchronize any
// in-flight external stop callback before members above are torn down.
std::optional<std::stop_callback<StopForwarder>> stop_cb_{};
};
} // namespace Void::Async