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

769 lines
29 KiB
C++

#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <expected>
#include <list>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <type_traits>
#include <utility>
// ── AsyncChannel ──────────────────────────────────────────────────────────────
// A bounded multi-producer / multi-consumer channel with coroutine `send` /
// `receive`, cooperative cancellation and optional injected-clock deadlines
// (C-03/C-04). Blocking waits do not exist: a waiter suspends its coroutine
// and is always resumed through `resume.post_completion(...)` (never while the
// channel lock is held; an executor that has been joined resumes the handle
// inline on the calling thread, as ThreadExecutor does after join()).
//
// Arbitration (one `std::mutex` covers the buffer and both waiter lists)
// A waiter is a heap node (`shared_ptr`) with the state
// {fresh, linked, claimed, cancelled, timed_out, closed, overloaded}.
// `fresh` is the pre-link state (callbacks that settle a fresh waiter make
// the awaiting coroutine skip suspension); `overloaded` is the internal
// result of a refused wait. Pairing a sender with a receiver happens in ONE
// critical section: the waiter is unlinked and claimed and the value is
// moved, so a value is always in exactly one place: the sender's node, the
// buffer, or the receiver's slot. Stop callbacks and timer callbacks take the
// same lock: a still-`linked` waiter is unlinked and settled
// `cancelled`/`timed_out` (a sender keeps its value and gets it back), a
// `claimed` waiter is left alone (a sender succeeded, a receiver already
// holds its value). Each operation is settled exactly once.
//
// Ordering and capacity
// FIFO means per-producer order (items of one producer are received in the
// order they were sent; items of different producers interleave). Waiting
// senders and waiting receivers are served in arrival order. `capacity` and
// `max_waiters` (per direction) must be > 0 (`create` -> invalid_argument).
// A wait that would exceed `max_waiters` returns `overloaded` (a send gets
// its value back).
//
// Close
// `close()` is idempotent and noexcept. Waiting senders complete `closed`
// and get their value back; waiting receivers complete `closed`. Items
// already buffered stay receivable: receivers drain the buffer in FIFO order
// and then get `closed`. `send`/`try_send` on a closed channel return
// `closed` with the value.
//
// Options checks (send/receive with OperationOptions), in this order and
// BEFORE any state change (a send returns its value in `SendFailure`):
// 1. stop already requested -> cancelled
// 2. a deadline is set: it is judged by
// `timers->clock()`; already reached -> timed_out
// no `timers` configured -> invalid_argument
// 3. the fast path (value moved / received)
// 4. a deadline timer is armed (schedule_at failure: overloaded ->
// overloaded, stopped -> cancelled; the value is returned)
// 5. the waiter is linked and the coroutine suspends.
// `TimerEvent::closed` (queue closed or destroyed) settles the wait
// `cancelled`. The system clock is never consulted.
//
// Lifetime and caller errors
// * `send`/`receive` return lazy Tasks; their frames hold
// `shared_from_this()`, so the channel outlives every pending operation.
// * Destroying a Task that is suspended inside a channel operation is a
// caller error (the waiter would be resumed into a destroyed frame).
// * The resume executor and the TimerQueue must outlive the channel and every
// pending operation.
// * Timer callbacks hold only weak references (channel + waiter); a stop or
// timer callback that races with completion finds a settled waiter and
// does nothing. No raw pointer into a coroutine frame is ever captured.
// * A `std::stop_callback` is never constructed or destroyed while the
// channel lock is held, and a timer is never cancelled under the lock.
// * Exceptions: if `T`'s move constructor throws, the exception propagates
// from the operation; the channel's structural invariants (lists, bound)
// are preserved, but the value being moved is then unspecified (strong
// guarantee only for T with a non-throwing move constructor).
namespace Void::Async
{
enum class ChannelError : std::uint8_t {
closed,
empty,
full,
cancelled,
timed_out,
overloaded,
invalid_argument
};
// closed -> AsyncErrorCode::closed, cancelled -> cancelled, timed_out ->
// timeout, overloaded/full -> overloaded, empty/invalid_argument ->
// invalid_argument.
[[nodiscard]] inline Void::Result::Error
make_async_error(ChannelError error, std::string message = {})
{
AsyncErrorCode code = AsyncErrorCode::invalid_argument;
const char* text = "Invalid async channel argument";
switch (error) {
case ChannelError::closed:
code = AsyncErrorCode::closed;
text = "Async channel is closed";
break;
case ChannelError::empty:
code = AsyncErrorCode::invalid_argument;
text = "Async channel is empty";
break;
case ChannelError::full:
code = AsyncErrorCode::overloaded;
text = "Async channel is full";
break;
case ChannelError::cancelled:
code = AsyncErrorCode::cancelled;
text = "Async channel operation cancelled";
break;
case ChannelError::timed_out:
code = AsyncErrorCode::timeout;
text = "Async channel operation deadline expired";
break;
case ChannelError::overloaded:
code = AsyncErrorCode::overloaded;
text = "Async channel waiter capacity exceeded";
break;
case ChannelError::invalid_argument:
code = AsyncErrorCode::invalid_argument;
text = "Invalid async channel argument";
break;
}
if (message.empty()) {
message = text;
}
return make_async_error(code, std::move(message));
}
struct ChannelOptions {
std::size_t capacity{1024};
std::size_t max_waiters{1024};
// Required only for waits with a deadline; must outlive the channel.
TimerQueue* timers{nullptr};
};
template <class T>
struct SendFailure {
ChannelError error;
T value;
};
namespace detail
{
enum class ChannelWaiterState : std::uint8_t {
fresh,
linked,
claimed,
cancelled,
timed_out,
closed,
overloaded
};
// Heap-allocated so stop/timer callbacks can reference it through shared or
// weak ownership instead of a pointer into a coroutine frame. All members
// except `sender` are protected by the owning channel's mutex (the waiter's
// owner may read `value` without the lock only after the state is terminal).
template <class T>
struct ChannelWaiter {
explicit ChannelWaiter(bool is_sender) noexcept : sender(is_sender) {}
const bool sender;
ChannelWaiterState state{ChannelWaiterState::fresh};
// Sender: the value to deliver. Receiver: the delivered value.
std::optional<T> value{};
std::coroutine_handle<> handle{};
TimerHandle timer{};
typename std::list<std::shared_ptr<ChannelWaiter>>::iterator position{};
};
} // namespace detail
template <class T>
class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>>
{
static_assert(std::is_object_v<T> && std::is_move_constructible_v<T>,
"AsyncChannel<T> requires a move-constructible object type");
using Waiter = detail::ChannelWaiter<T>;
using WaiterPtr = std::shared_ptr<Waiter>;
using WaiterList = std::list<WaiterPtr>;
using WaiterState = detail::ChannelWaiterState;
using SendResult = std::expected<void, SendFailure<T>>;
using ReceiveResult = std::expected<T, ChannelError>;
public:
// Errors: invalid_argument when capacity == 0 or max_waiters == 0.
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>>
create(Executor& resume, ChannelOptions options = {})
{
if (options.capacity == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"AsyncChannel capacity must be greater than zero")};
}
if (options.max_waiters == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"AsyncChannel max_waiters must be greater than zero")};
}
return std::shared_ptr<AsyncChannel>(new AsyncChannel(resume, options));
}
AsyncChannel(const AsyncChannel&) = delete;
AsyncChannel& operator=(const AsyncChannel&) = delete;
AsyncChannel(AsyncChannel&&) = delete;
AsyncChannel& operator=(AsyncChannel&&) = delete;
~AsyncChannel() = default;
// Non-blocking send. Errors (the value is returned): closed, full.
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T value)
{
WaiterPtr woken;
SendAttempt attempt{};
{
std::lock_guard lk{mu_};
attempt = try_send_locked(value, woken);
}
resume_waiter(woken);
switch (attempt) {
case SendAttempt::sent:
return {};
case SendAttempt::closed:
return std::unexpected{SendFailure<T>{ChannelError::closed, std::move(value)}};
case SendAttempt::full:
break;
}
return std::unexpected{SendFailure<T>{ChannelError::full, std::move(value)}};
}
// Suspends until the value is delivered (to a waiting receiver or the
// buffer). Results: success; or SendFailure with the value returned:
// closed, cancelled, timed_out, overloaded, invalid_argument (see the
// header comment for the check order).
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>>
send(T value, OperationOptions options = {})
{
return send_impl(this->shared_from_this(), std::move(value), std::move(options));
}
// Non-blocking receive. Errors: empty, closed (closed AND drained).
[[nodiscard]] std::expected<T, ChannelError> try_receive()
{
std::optional<T> out;
WaiterPtr woken;
ReceiveAttempt attempt{};
{
std::lock_guard lk{mu_};
attempt = try_receive_locked(out, woken);
}
resume_waiter(woken);
switch (attempt) {
case ReceiveAttempt::received:
return std::move(*out);
case ReceiveAttempt::closed:
return std::unexpected{ChannelError::closed};
case ReceiveAttempt::empty:
break;
}
return std::unexpected{ChannelError::empty};
}
// Suspends until a value arrives. Errors: closed (closed AND drained),
// cancelled, timed_out, overloaded, invalid_argument.
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>>
receive(OperationOptions options = {})
{
return receive_impl(this->shared_from_this(), std::move(options));
}
// Idempotent. See the header comment.
void close() noexcept
{
WaiterList senders;
WaiterList receivers;
{
std::lock_guard lk{mu_};
if (closed_) {
return;
}
closed_ = true;
senders.splice(senders.end(), senders_);
receivers.splice(receivers.end(), receivers_);
for (auto& waiter : senders) {
waiter->state = WaiterState::closed;
}
for (auto& waiter : receivers) {
waiter->state = WaiterState::closed;
}
}
for (auto& waiter : senders) {
resume_waiter(waiter);
}
for (auto& waiter : receivers) {
resume_waiter(waiter);
}
}
// Number of buffered items.
[[nodiscard]] std::size_t size() const
{
std::lock_guard lk{mu_};
return buffer_.size();
}
[[nodiscard]] bool is_closed() const
{
std::lock_guard lk{mu_};
return closed_;
}
private:
enum class SendAttempt : std::uint8_t { sent, closed, full };
enum class ReceiveAttempt : std::uint8_t { received, closed, empty };
AsyncChannel(Executor& resume, const ChannelOptions& options)
: resume_(resume)
, capacity_(options.capacity)
, max_waiters_(options.max_waiters)
, timers_(options.timers)
{
}
// ── locked primitives (mu_ held) ──────────────────────────────────────
// Moves from `value` only on success. A waiting receiver implies an empty
// buffer, so a direct hand-off preserves FIFO order.
[[nodiscard]] SendAttempt try_send_locked(T& value, WaiterPtr& woken)
{
if (closed_) {
return SendAttempt::closed;
}
if (!receivers_.empty()) {
WaiterPtr receiver = receivers_.front();
receiver->value.emplace(std::move(value));
receivers_.pop_front();
receiver->state = WaiterState::claimed;
woken = std::move(receiver);
return SendAttempt::sent;
}
if (buffer_.size() < capacity_) {
buffer_.push_back(std::move(value));
return SendAttempt::sent;
}
return SendAttempt::full;
}
// A waiting sender implies a full buffer: the freed slot is refilled from
// the first waiting sender, which is claimed (it succeeded).
[[nodiscard]] ReceiveAttempt try_receive_locked(std::optional<T>& out, WaiterPtr& woken)
{
if (!buffer_.empty()) {
out.emplace(std::move(buffer_.front()));
buffer_.pop_front();
if (!senders_.empty()) {
WaiterPtr sender = senders_.front();
try {
buffer_.push_back(std::move(*sender->value));
} catch (...) {
// Best effort: put the received value back so it is not lost.
try {
buffer_.push_front(std::move(*out));
} catch (...) {
}
throw;
}
senders_.pop_front();
sender->state = WaiterState::claimed;
woken = std::move(sender);
}
return ReceiveAttempt::received;
}
if (closed_) {
return ReceiveAttempt::closed;
}
return ReceiveAttempt::empty;
}
void link_locked(WaiterList& list, const WaiterPtr& waiter)
{
waiter->position = list.insert(list.end(), waiter);
waiter->state = WaiterState::linked;
}
// ── settlement (no lock held) ─────────────────────────────────────────
// Cancels the waiter's deadline timer and resumes its coroutine through
// the completion lane. The waiter must already be in a terminal state.
void resume_waiter(WaiterPtr& waiter)
{
if (!waiter) {
return;
}
(void)waiter->timer.cancel();
resume_.post_completion(waiter->handle);
waiter.reset();
}
// Stop/timer callback entry point. A `fresh` waiter is only marked (the
// awaiting coroutine will not suspend); a `linked` waiter is unlinked and
// resumed; anything else was already settled and is left alone.
void settle_pending(const WaiterPtr& waiter, WaiterState to) noexcept
{
{
std::lock_guard lk{mu_};
if (waiter->state == WaiterState::fresh) {
waiter->state = to;
return;
}
if (waiter->state != WaiterState::linked) {
return;
}
(waiter->sender ? senders_ : receivers_).erase(waiter->position);
waiter->state = to;
}
WaiterPtr settled = waiter;
resume_waiter(settled);
}
// ── option handling ───────────────────────────────────────────────────
[[nodiscard]] std::optional<ChannelError> precheck(const OperationOptions& options) const
{
if (options.stop.stop_requested()) {
return ChannelError::cancelled;
}
if (options.deadline.has_value()) {
if (timers_ == nullptr) {
return ChannelError::invalid_argument;
}
if (timers_->clock().now() >= *options.deadline) {
return ChannelError::timed_out;
}
}
return std::nullopt;
}
// Arms the deadline timer while the waiter is still `fresh` (so a failure
// leaves no state behind and a timer that fires early settles the fresh
// waiter without a ticket). The callback holds only weak references.
[[nodiscard]] std::optional<ChannelError>
arm_deadline(const WaiterPtr& waiter, Void::Time::MonotonicClock::time_point deadline)
{
auto scheduled = timers_->schedule_at(
deadline,
TimerCallback{[channel = this->weak_from_this(),
target = std::weak_ptr<Waiter>{waiter}](TimerEvent event) noexcept {
const auto chan = channel.lock();
const auto settled = target.lock();
if (chan && settled) {
chan->settle_pending(
settled,
event == TimerEvent::expired ? WaiterState::timed_out
: WaiterState::cancelled);
}
}});
if (!scheduled.has_value()) {
switch (scheduled.error()) {
case AdmissionError::overloaded:
return ChannelError::overloaded;
case AdmissionError::stopped:
return ChannelError::cancelled;
case AdmissionError::deadline_expired:
return ChannelError::timed_out;
case AdmissionError::invalid_argument:
case AdmissionError::self_join:
return ChannelError::invalid_argument;
}
return ChannelError::invalid_argument;
}
bool settled_meanwhile = false;
{
std::lock_guard lk{mu_};
if (waiter->state == WaiterState::fresh) {
waiter->timer = std::move(*scheduled);
} else {
settled_meanwhile = true;
}
}
if (settled_meanwhile) {
(void)scheduled->cancel();
}
return std::nullopt;
}
struct StopFn {
std::weak_ptr<AsyncChannel> channel;
WaiterPtr waiter;
void operator()() const noexcept
{
// Copy first: once the waiter is settled the resumed frame may
// destroy the stop_callback that owns this object.
const auto chan = channel.lock();
const WaiterPtr target = waiter;
if (chan) {
chan->settle_pending(target, WaiterState::cancelled);
}
}
};
// ── awaiters ──────────────────────────────────────────────────────────
// Links the waiter (re-running the fast path under the same lock so no
// wake-up can be lost) and suspends. Once the waiter is visible to other
// threads the frame may be resumed and destroyed concurrently, so
// everything after the unlock touches locals only.
struct SendAwaiter {
std::shared_ptr<AsyncChannel> channel;
WaiterPtr waiter;
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
{
std::shared_ptr<AsyncChannel> chan = channel;
WaiterPtr self = waiter;
WaiterPtr woken;
bool suspended = false;
try {
std::lock_guard lk{chan->mu_};
if (self->state == WaiterState::fresh) {
switch (chan->try_send_locked(*self->value, woken)) {
case SendAttempt::sent:
self->state = WaiterState::claimed;
break;
case SendAttempt::closed:
self->state = WaiterState::closed;
break;
case SendAttempt::full:
if (chan->senders_.size() >= chan->max_waiters_) {
self->state = WaiterState::overloaded;
} else {
self->handle = handle;
chan->link_locked(chan->senders_, self);
suspended = true;
}
break;
}
}
} catch (...) {
(void)self->timer.cancel();
throw;
}
if (suspended) {
return true;
}
(void)self->timer.cancel();
chan->resume_waiter(woken);
return false;
}
[[nodiscard]] SendResult await_resume()
{
WaiterState state{};
{
std::lock_guard lk{channel->mu_};
state = waiter->state;
}
switch (state) {
case WaiterState::claimed:
return {};
case WaiterState::closed:
return fail(ChannelError::closed);
case WaiterState::timed_out:
return fail(ChannelError::timed_out);
case WaiterState::overloaded:
return fail(ChannelError::overloaded);
case WaiterState::cancelled:
case WaiterState::fresh:
case WaiterState::linked:
break;
}
return fail(ChannelError::cancelled);
}
private:
[[nodiscard]] SendResult fail(ChannelError error)
{
return std::unexpected{SendFailure<T>{error, std::move(*waiter->value)}};
}
};
struct ReceiveAwaiter {
std::shared_ptr<AsyncChannel> channel;
WaiterPtr waiter;
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
{
std::shared_ptr<AsyncChannel> chan = channel;
WaiterPtr self = waiter;
WaiterPtr woken;
bool suspended = false;
try {
std::lock_guard lk{chan->mu_};
if (self->state == WaiterState::fresh) {
switch (chan->try_receive_locked(self->value, woken)) {
case ReceiveAttempt::received:
self->state = WaiterState::claimed;
break;
case ReceiveAttempt::closed:
self->state = WaiterState::closed;
break;
case ReceiveAttempt::empty:
if (chan->receivers_.size() >= chan->max_waiters_) {
self->state = WaiterState::overloaded;
} else {
self->handle = handle;
chan->link_locked(chan->receivers_, self);
suspended = true;
}
break;
}
}
} catch (...) {
(void)self->timer.cancel();
throw;
}
if (suspended) {
return true;
}
(void)self->timer.cancel();
chan->resume_waiter(woken);
return false;
}
[[nodiscard]] ReceiveResult await_resume()
{
WaiterState state{};
{
std::lock_guard lk{channel->mu_};
state = waiter->state;
}
switch (state) {
case WaiterState::claimed:
return std::move(*waiter->value);
case WaiterState::closed:
return std::unexpected{ChannelError::closed};
case WaiterState::timed_out:
return std::unexpected{ChannelError::timed_out};
case WaiterState::overloaded:
return std::unexpected{ChannelError::overloaded};
case WaiterState::cancelled:
case WaiterState::fresh:
case WaiterState::linked:
break;
}
return std::unexpected{ChannelError::cancelled};
}
};
// ── operations (free-standing coroutines holding the channel) ─────────
static Coro::Task<SendResult>
send_impl(std::shared_ptr<AsyncChannel> self, T value, OperationOptions options)
{
if (const auto refused = self->precheck(options); refused.has_value()) {
co_return std::unexpected{SendFailure<T>{*refused, std::move(value)}};
}
{
WaiterPtr woken;
SendAttempt attempt{};
{
std::lock_guard lk{self->mu_};
attempt = self->try_send_locked(value, woken);
}
self->resume_waiter(woken);
if (attempt == SendAttempt::sent) {
co_return SendResult{};
}
if (attempt == SendAttempt::closed) {
co_return std::unexpected{SendFailure<T>{ChannelError::closed, std::move(value)}};
}
}
auto waiter = std::make_shared<Waiter>(true);
waiter->value.emplace(std::move(value));
std::optional<std::stop_callback<StopFn>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter});
}
if (options.deadline.has_value()) {
if (const auto failure = self->arm_deadline(waiter, *options.deadline);
failure.has_value()) {
co_return std::unexpected{SendFailure<T>{*failure, std::move(*waiter->value)}};
}
}
SendResult result = co_await SendAwaiter{self, waiter};
// Waits for a stop callback that is mid-settle (no lock is held here).
stop_cb.reset();
co_return result;
}
static Coro::Task<ReceiveResult>
receive_impl(std::shared_ptr<AsyncChannel> self, OperationOptions options)
{
if (const auto refused = self->precheck(options); refused.has_value()) {
co_return std::unexpected{*refused};
}
{
std::optional<T> out;
WaiterPtr woken;
ReceiveAttempt attempt{};
{
std::lock_guard lk{self->mu_};
attempt = self->try_receive_locked(out, woken);
}
self->resume_waiter(woken);
if (attempt == ReceiveAttempt::received) {
co_return ReceiveResult{std::move(*out)};
}
if (attempt == ReceiveAttempt::closed) {
co_return std::unexpected{ChannelError::closed};
}
}
auto waiter = std::make_shared<Waiter>(false);
std::optional<std::stop_callback<StopFn>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter});
}
if (options.deadline.has_value()) {
if (const auto failure = self->arm_deadline(waiter, *options.deadline);
failure.has_value()) {
co_return std::unexpected{*failure};
}
}
ReceiveResult result = co_await ReceiveAwaiter{self, waiter};
stop_cb.reset();
co_return result;
}
Executor& resume_;
const std::size_t capacity_;
const std::size_t max_waiters_;
TimerQueue* const timers_;
mutable std::mutex mu_{};
std::deque<T> buffer_{};
WaiterList senders_{};
WaiterList receivers_{};
bool closed_{false};
};
} // namespace Void::Async