feat(Async): add OperationOptions, OperationState, ResumeTicket, TaskScope, and bounded executor tickets (M-ASYNC-02, M-ASYNC-03)
This commit is contained in:
1 parent
4369fde867
commit
c75056fe07
6 files changed
+2229
-4
No files matched your search
@@ -0,0 +1,138 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Async
|
||||
{
|
||||
|
||||
enum class AdmissionError {
|
||||
overloaded,
|
||||
stopped,
|
||||
deadline_expired,
|
||||
invalid_argument,
|
||||
self_join
|
||||
};
|
||||
|
||||
enum class AsyncErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
cancelled = 1,
|
||||
timeout = 2,
|
||||
overloaded = 3,
|
||||
stopped = 4,
|
||||
invalid_argument = 5,
|
||||
self_join = 6,
|
||||
backend_error = 7,
|
||||
limit_exceeded = 8
|
||||
};
|
||||
|
||||
enum class DomainOutcomeKind {
|
||||
pending,
|
||||
succeeded,
|
||||
not_committed,
|
||||
unknown,
|
||||
failed,
|
||||
cancelled
|
||||
};
|
||||
|
||||
struct OperationOptions {
|
||||
std::stop_token stop{};
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
|
||||
};
|
||||
|
||||
[[nodiscard]] inline bool is_deadline_expired(
|
||||
const OperationOptions& options,
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance()) noexcept
|
||||
{
|
||||
return options.deadline.has_value() && clock.now() >= *options.deadline;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_async_error(AsyncErrorCode code, std::string message = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case AsyncErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case AsyncErrorCode::cancelled:
|
||||
case AsyncErrorCode::stopped:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case AsyncErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case AsyncErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case AsyncErrorCode::invalid_argument:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case AsyncErrorCode::self_join:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case AsyncErrorCode::backend_error:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case AsyncErrorCode::limit_exceeded:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
}
|
||||
|
||||
const ErrorCode domain_code{
|
||||
Void::Result::kAsyncErrorDomain,
|
||||
static_cast<std::int32_t>(code)};
|
||||
return Error{kind, std::move(message), domain_code};
|
||||
}
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_async_error(AdmissionError adm, std::string message = {})
|
||||
{
|
||||
AsyncErrorCode code = AsyncErrorCode::invalid_argument;
|
||||
switch (adm) {
|
||||
case AdmissionError::overloaded:
|
||||
code = AsyncErrorCode::overloaded;
|
||||
if (message.empty()) {
|
||||
message = "Async executor or scope capacity exceeded";
|
||||
}
|
||||
break;
|
||||
case AdmissionError::stopped:
|
||||
code = AsyncErrorCode::stopped;
|
||||
if (message.empty()) {
|
||||
message = "Async executor or scope is stopped";
|
||||
}
|
||||
break;
|
||||
case AdmissionError::deadline_expired:
|
||||
code = AsyncErrorCode::timeout;
|
||||
if (message.empty()) {
|
||||
message = "Async operation deadline expired";
|
||||
}
|
||||
break;
|
||||
case AdmissionError::invalid_argument:
|
||||
code = AsyncErrorCode::invalid_argument;
|
||||
if (message.empty()) {
|
||||
message = "Invalid async admission argument";
|
||||
}
|
||||
break;
|
||||
case AdmissionError::self_join:
|
||||
code = AsyncErrorCode::self_join;
|
||||
if (message.empty()) {
|
||||
message = "Cannot blocking-join from inside the active executor thread";
|
||||
}
|
||||
break;
|
||||
}
|
||||
return make_async_error(code, std::move(message));
|
||||
}
|
||||
|
||||
} // namespace Void::Async
|
||||
@@ -1,15 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <coroutine>
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
|
||||
namespace Void::Async
|
||||
{
|
||||
|
||||
class Executor;
|
||||
|
||||
namespace detail
|
||||
{
|
||||
struct ActiveExecutorFrame {
|
||||
const Executor* exec{nullptr};
|
||||
const ActiveExecutorFrame* prev{nullptr};
|
||||
|
||||
[[nodiscard]] static inline const ActiveExecutorFrame*& head() noexcept
|
||||
{
|
||||
thread_local const ActiveExecutorFrame* slot = nullptr;
|
||||
return slot;
|
||||
}
|
||||
};
|
||||
|
||||
class ExecutorThreadGuard
|
||||
{
|
||||
public:
|
||||
explicit ExecutorThreadGuard(const Executor* exec) noexcept
|
||||
: frame_{exec, ActiveExecutorFrame::head()}
|
||||
{
|
||||
ActiveExecutorFrame::head() = &frame_;
|
||||
}
|
||||
|
||||
~ExecutorThreadGuard()
|
||||
{
|
||||
ActiveExecutorFrame::head() = frame_.prev;
|
||||
}
|
||||
|
||||
ExecutorThreadGuard(const ExecutorThreadGuard&) = delete;
|
||||
ExecutorThreadGuard& operator=(const ExecutorThreadGuard&) = delete;
|
||||
|
||||
private:
|
||||
ActiveExecutorFrame frame_;
|
||||
};
|
||||
} // namespace detail
|
||||
|
||||
// ── Executor ──────────────────────────────────────────────────────────────────
|
||||
// Minimal scheduling interface bridging Coro::Task to a driving thread.
|
||||
// post() must be safe to call from any thread.
|
||||
@@ -21,6 +62,54 @@ public:
|
||||
|
||||
// Schedule a coroutine for resumption on this executor. Thread-safe.
|
||||
virtual void post(std::coroutine_handle<> handle) = 0;
|
||||
|
||||
// Bounded non-blocking admission. Subclasses may override with queue caps.
|
||||
[[nodiscard]] virtual std::expected<void, AdmissionError>
|
||||
try_post(std::coroutine_handle<> handle)
|
||||
{
|
||||
if (!handle) {
|
||||
return std::unexpected{AdmissionError::invalid_argument};
|
||||
}
|
||||
post(handle);
|
||||
return {};
|
||||
}
|
||||
|
||||
// Reserved lane for resuming waiting/joining continuations without normal
|
||||
// work-queue backpressure rejections.
|
||||
virtual void post_completion(std::coroutine_handle<> handle)
|
||||
{
|
||||
if (handle) {
|
||||
post(handle);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual bool is_executor_thread() const noexcept
|
||||
{
|
||||
for (const auto* f = detail::ActiveExecutorFrame::head();
|
||||
f != nullptr;
|
||||
f = f->prev) {
|
||||
if (f->exec == this) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual bool supports_reservation() const noexcept { return false; }
|
||||
|
||||
[[nodiscard]] virtual std::expected<void, AdmissionError> try_reserve_slot()
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
virtual void commit_reserved(std::coroutine_handle<> handle)
|
||||
{
|
||||
post_completion(handle);
|
||||
}
|
||||
|
||||
virtual void release_reserved() noexcept {}
|
||||
|
||||
[[nodiscard]] virtual bool has_background_workers() const noexcept { return true; }
|
||||
};
|
||||
|
||||
// ── ManualExecutor ────────────────────────────────────────────────────────────
|
||||
@@ -31,18 +120,111 @@ public:
|
||||
class ManualExecutor final : public Executor
|
||||
{
|
||||
public:
|
||||
explicit ManualExecutor(std::size_t max_queue = 0) noexcept
|
||||
: max_queue_(max_queue)
|
||||
{
|
||||
}
|
||||
|
||||
void post(std::coroutine_handle<> handle) override
|
||||
{
|
||||
if (!handle) {
|
||||
return;
|
||||
}
|
||||
pending_normal_.fetch_add(1, std::memory_order_acq_rel);
|
||||
queue_.push(handle);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<void, AdmissionError>
|
||||
try_post(std::coroutine_handle<> handle) override
|
||||
{
|
||||
if (!handle) {
|
||||
return std::unexpected{AdmissionError::invalid_argument};
|
||||
}
|
||||
auto reserved = try_reserve_slot();
|
||||
if (!reserved.has_value()) {
|
||||
return reserved;
|
||||
}
|
||||
queue_.push(handle);
|
||||
return {};
|
||||
}
|
||||
|
||||
void post_completion(std::coroutine_handle<> handle) override
|
||||
{
|
||||
if (!handle) {
|
||||
return;
|
||||
}
|
||||
completion_queue_.push(handle);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool supports_reservation() const noexcept override { return true; }
|
||||
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override
|
||||
{
|
||||
std::size_t cur = pending_normal_.load(std::memory_order_acquire);
|
||||
for (;;) {
|
||||
if (!accepting_.load(std::memory_order_acquire)) {
|
||||
return std::unexpected{AdmissionError::stopped};
|
||||
}
|
||||
if (max_queue_ != 0 && cur >= max_queue_) {
|
||||
return std::unexpected{AdmissionError::overloaded};
|
||||
}
|
||||
if (pending_normal_.compare_exchange_weak(
|
||||
cur,
|
||||
cur + 1,
|
||||
std::memory_order_acq_rel,
|
||||
std::memory_order_acquire)) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void commit_reserved(std::coroutine_handle<> handle) override
|
||||
{
|
||||
if (!handle) {
|
||||
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
|
||||
return;
|
||||
}
|
||||
queue_.push(handle);
|
||||
}
|
||||
|
||||
void release_reserved() noexcept override
|
||||
{
|
||||
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool has_background_workers() const noexcept override { return false; }
|
||||
|
||||
void shutdown() noexcept
|
||||
{
|
||||
accepting_.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_accepting() const noexcept
|
||||
{
|
||||
return accepting_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t pending_normal() const noexcept
|
||||
{
|
||||
return pending_normal_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t max_queue() const noexcept { return max_queue_; }
|
||||
|
||||
// Resume one pending coroutine. Returns false if none was pending.
|
||||
bool run_one()
|
||||
{
|
||||
if (auto c = completion_queue_.try_pop(); c.has_value()) {
|
||||
detail::ExecutorThreadGuard guard{this};
|
||||
c->resume();
|
||||
return true;
|
||||
}
|
||||
auto h = queue_.try_pop();
|
||||
if (!h) {
|
||||
return false;
|
||||
}
|
||||
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
|
||||
detail::ExecutorThreadGuard guard{this};
|
||||
h->resume();
|
||||
return true;
|
||||
}
|
||||
@@ -58,10 +240,17 @@ public:
|
||||
return count;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept { return queue_.empty(); }
|
||||
[[nodiscard]] bool empty() const noexcept
|
||||
{
|
||||
return completion_queue_.empty() && queue_.empty();
|
||||
}
|
||||
|
||||
private:
|
||||
MpscQueue<std::coroutine_handle<>> queue_;
|
||||
std::size_t max_queue_{0};
|
||||
std::atomic<std::size_t> pending_normal_{0};
|
||||
std::atomic<bool> accepting_{true};
|
||||
MpscQueue<std::coroutine_handle<>> queue_{};
|
||||
MpscQueue<std::coroutine_handle<>> completion_queue_{};
|
||||
};
|
||||
|
||||
// ── schedule_on ───────────────────────────────────────────────────────────────
|
||||
@@ -112,4 +301,61 @@ inline void spawn(Executor& executor, Coro::Task<void> task)
|
||||
Detail::spawn_impl(executor, std::move(task));
|
||||
}
|
||||
|
||||
struct ScheduleStatusAwaiter {
|
||||
Executor& executor;
|
||||
OperationOptions options{};
|
||||
const Void::Time::MonotonicClock* clock{&Void::Time::SystemMonotonicClock::instance()};
|
||||
Void::Result::Result<void> pre_outcome{};
|
||||
|
||||
[[nodiscard]] bool await_ready() noexcept
|
||||
{
|
||||
if (options.stop.stop_requested()) {
|
||||
pre_outcome = std::unexpected{make_async_error(
|
||||
AsyncErrorCode::cancelled, "schedule_on cancelled before scheduling")};
|
||||
return true;
|
||||
}
|
||||
if (is_deadline_expired(options, *clock)) {
|
||||
pre_outcome = std::unexpected{make_async_error(
|
||||
AsyncErrorCode::timeout, "schedule_on deadline expired before scheduling")};
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
|
||||
{
|
||||
const auto post_res = executor.try_post(handle);
|
||||
if (!post_res.has_value()) {
|
||||
pre_outcome = std::unexpected{make_async_error(
|
||||
post_res.error(), "schedule_on rejected by executor")};
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> await_resume() noexcept
|
||||
{
|
||||
if (!pre_outcome.has_value()) {
|
||||
return pre_outcome;
|
||||
}
|
||||
if (options.stop.stop_requested()) {
|
||||
return std::unexpected{make_async_error(
|
||||
AsyncErrorCode::cancelled, "schedule_on cancelled before execution")};
|
||||
}
|
||||
if (is_deadline_expired(options, *clock)) {
|
||||
return std::unexpected{make_async_error(
|
||||
AsyncErrorCode::timeout, "schedule_on deadline expired before execution")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] inline ScheduleStatusAwaiter schedule_on(
|
||||
Executor& executor,
|
||||
OperationOptions options,
|
||||
const Void::Time::MonotonicClock& clock = Void::Time::SystemMonotonicClock::instance()) noexcept
|
||||
{
|
||||
return ScheduleStatusAwaiter{executor, std::move(options), &clock};
|
||||
}
|
||||
|
||||
} // namespace Void::Async
|
||||
@@ -0,0 +1,410 @@
|
||||
#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
|
||||
@@ -0,0 +1,798 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <condition_variable>
|
||||
#include <coroutine>
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Async
|
||||
{
|
||||
|
||||
struct TaskScopeOptions {
|
||||
std::size_t max_tasks{1024};
|
||||
std::stop_token parent_stop{};
|
||||
bool stop_on_first_error{true};
|
||||
|
||||
[[nodiscard]] static constexpr TaskScopeOptions unlimited(
|
||||
std::stop_token parent_stop = {},
|
||||
bool stop_on_first_error = true) noexcept
|
||||
{
|
||||
return TaskScopeOptions{
|
||||
std::numeric_limits<std::size_t>::max(),
|
||||
parent_stop,
|
||||
stop_on_first_error};
|
||||
}
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
|
||||
class ScopeControl;
|
||||
|
||||
class ChildTaskControl : public std::enable_shared_from_this<ChildTaskControl>
|
||||
{
|
||||
public:
|
||||
explicit ChildTaskControl(Executor& executor) noexcept
|
||||
: executor_(executor)
|
||||
{
|
||||
}
|
||||
|
||||
ChildTaskControl(const ChildTaskControl&) = delete;
|
||||
ChildTaskControl& operator=(const ChildTaskControl&) = delete;
|
||||
|
||||
[[nodiscard]] std::stop_token stop_token() const noexcept
|
||||
{
|
||||
return stop_source_.get_token();
|
||||
}
|
||||
|
||||
bool request_stop() noexcept
|
||||
{
|
||||
return stop_source_.request_stop();
|
||||
}
|
||||
|
||||
void attach_stops(std::stop_token scope_stop, std::stop_token option_stop)
|
||||
{
|
||||
if (scope_stop.stop_possible()) {
|
||||
scope_stop_cb_.emplace(scope_stop, StopForwarder{this});
|
||||
}
|
||||
if (option_stop.stop_possible()) {
|
||||
option_stop_cb_.emplace(option_stop, StopForwarder{this});
|
||||
}
|
||||
}
|
||||
|
||||
void set_error(Void::Result::Error err)
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
error_ = std::move(err);
|
||||
}
|
||||
|
||||
void mark_finished()
|
||||
{
|
||||
std::coroutine_handle<> waiter{};
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
finished_ = true;
|
||||
waiter = std::exchange(async_waiter_, {});
|
||||
}
|
||||
cv_.notify_all();
|
||||
if (waiter) {
|
||||
executor_.post_completion(waiter);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool done() const
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
return finished_;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool try_register_waiter(std::coroutine_handle<> waiter)
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
if (finished_) {
|
||||
return false;
|
||||
}
|
||||
async_waiter_ = waiter;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> take_outcome() const
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
if (error_.has_value()) {
|
||||
return std::unexpected{*error_};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> join_blocking()
|
||||
{
|
||||
if (executor_.is_executor_thread()) {
|
||||
return std::unexpected{make_async_error(
|
||||
AdmissionError::self_join,
|
||||
"JoinHandle::join_blocking called on active executor thread")};
|
||||
}
|
||||
std::unique_lock lk{mu_};
|
||||
cv_.wait(lk, [this] { return finished_; });
|
||||
if (error_.has_value()) {
|
||||
return std::unexpected{*error_};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
struct StopForwarder {
|
||||
ChildTaskControl* self{nullptr};
|
||||
void operator()() const noexcept
|
||||
{
|
||||
if (self != nullptr) {
|
||||
self->request_stop();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Executor& executor_;
|
||||
std::stop_source stop_source_{};
|
||||
mutable std::mutex mu_{};
|
||||
std::condition_variable cv_{};
|
||||
bool finished_{false};
|
||||
std::optional<Void::Result::Error> error_{};
|
||||
std::coroutine_handle<> async_waiter_{};
|
||||
// MUST stay LAST so stop callbacks synchronize before members destruct.
|
||||
std::optional<std::stop_callback<StopForwarder>> scope_stop_cb_{};
|
||||
std::optional<std::stop_callback<StopForwarder>> option_stop_cb_{};
|
||||
};
|
||||
|
||||
class ScopeControl : public std::enable_shared_from_this<ScopeControl>
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] static std::shared_ptr<ScopeControl> create(
|
||||
Executor& executor, TaskScopeOptions options)
|
||||
{
|
||||
auto ptr = std::shared_ptr<ScopeControl>(
|
||||
new ScopeControl(executor, options));
|
||||
if (options.parent_stop.stop_possible()) {
|
||||
ptr->parent_stop_cb_.emplace(options.parent_stop, StopForwarder{ptr.get()});
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
|
||||
ScopeControl(const ScopeControl&) = delete;
|
||||
ScopeControl& operator=(const ScopeControl&) = delete;
|
||||
|
||||
[[nodiscard]] Executor& executor() noexcept { return executor_; }
|
||||
|
||||
[[nodiscard]] std::stop_token stop_token() const noexcept
|
||||
{
|
||||
return stop_source_.get_token();
|
||||
}
|
||||
|
||||
bool request_stop() noexcept
|
||||
{
|
||||
return stop_source_.request_stop();
|
||||
}
|
||||
|
||||
void close() noexcept
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
closed_ = true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_reserve(
|
||||
const OperationOptions& op,
|
||||
const Void::Time::MonotonicClock& clock)
|
||||
{
|
||||
if (max_tasks_ == 0) {
|
||||
return std::unexpected{AdmissionError::invalid_argument};
|
||||
}
|
||||
if (op.stop.stop_requested()) {
|
||||
return std::unexpected{AdmissionError::stopped};
|
||||
}
|
||||
if (is_deadline_expired(op, clock)) {
|
||||
return std::unexpected{AdmissionError::deadline_expired};
|
||||
}
|
||||
std::lock_guard lk{mu_};
|
||||
if (closed_ || stop_source_.stop_requested()) {
|
||||
return std::unexpected{AdmissionError::stopped};
|
||||
}
|
||||
if (active_tasks_ >= max_tasks_) {
|
||||
return std::unexpected{AdmissionError::overloaded};
|
||||
}
|
||||
++active_tasks_;
|
||||
return {};
|
||||
}
|
||||
|
||||
void release_reservation()
|
||||
{
|
||||
on_task_finished();
|
||||
}
|
||||
|
||||
void record_exception(std::exception_ptr ex, std::string_view what)
|
||||
{
|
||||
bool trigger_stop = false;
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
++failure_count_;
|
||||
if (!first_exception_) {
|
||||
first_exception_ = ex;
|
||||
first_error_ = make_async_error(
|
||||
AsyncErrorCode::backend_error,
|
||||
what.empty()
|
||||
? std::string{"Unhandled exception in TaskScope task"}
|
||||
: std::string{what});
|
||||
trigger_stop = stop_on_first_error_;
|
||||
}
|
||||
}
|
||||
if (trigger_stop) {
|
||||
request_stop();
|
||||
}
|
||||
}
|
||||
|
||||
void on_task_finished()
|
||||
{
|
||||
std::coroutine_handle<> waiter{};
|
||||
bool notify = false;
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
--active_tasks_;
|
||||
if (active_tasks_ == 0) {
|
||||
notify = true;
|
||||
waiter = std::exchange(async_join_waiter_, {});
|
||||
}
|
||||
}
|
||||
if (notify) {
|
||||
cv_.notify_all();
|
||||
if (waiter) {
|
||||
executor_.post_completion(waiter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool try_begin_async_join(std::coroutine_handle<> waiter)
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
closed_ = true;
|
||||
if (active_tasks_ == 0) {
|
||||
return false;
|
||||
}
|
||||
async_join_waiter_ = waiter;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> finish_outcome() const
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
if (first_error_.has_value()) {
|
||||
return std::unexpected{*first_error_};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> join_blocking()
|
||||
{
|
||||
if (executor_.is_executor_thread()) {
|
||||
return std::unexpected{make_async_error(
|
||||
AdmissionError::self_join,
|
||||
"TaskScope::join_blocking called on active executor thread")};
|
||||
}
|
||||
std::unique_lock lk{mu_};
|
||||
closed_ = true;
|
||||
cv_.wait(lk, [this] { return active_tasks_ == 0; });
|
||||
if (first_error_.has_value()) {
|
||||
return std::unexpected{*first_error_};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t active_count() const
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
return active_tasks_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t failure_count() const
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
return failure_count_;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool has_exception() const
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
return static_cast<bool>(first_exception_);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::exception_ptr first_exception() const
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
return first_exception_;
|
||||
}
|
||||
|
||||
private:
|
||||
struct StopForwarder {
|
||||
ScopeControl* self{nullptr};
|
||||
void operator()() const noexcept
|
||||
{
|
||||
if (self != nullptr) {
|
||||
self->request_stop();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ScopeControl(Executor& executor, TaskScopeOptions options) noexcept
|
||||
: executor_(executor)
|
||||
, max_tasks_(options.max_tasks)
|
||||
, stop_on_first_error_(options.stop_on_first_error)
|
||||
{
|
||||
}
|
||||
|
||||
Executor& executor_;
|
||||
std::size_t max_tasks_{1024};
|
||||
bool stop_on_first_error_{true};
|
||||
std::stop_source stop_source_{};
|
||||
mutable std::mutex mu_{};
|
||||
std::condition_variable cv_{};
|
||||
std::size_t active_tasks_{0};
|
||||
std::size_t failure_count_{0};
|
||||
bool closed_{false};
|
||||
std::exception_ptr first_exception_{};
|
||||
std::optional<Void::Result::Error> first_error_{};
|
||||
std::coroutine_handle<> async_join_waiter_{};
|
||||
// MUST stay LAST: waits for any active parent stop callback on destruction.
|
||||
std::optional<std::stop_callback<StopForwarder>> parent_stop_cb_{};
|
||||
};
|
||||
|
||||
struct TakePromiseTaskTag {};
|
||||
struct GetScopePtrTag {};
|
||||
struct GetChildPtrTag {};
|
||||
|
||||
struct ScopeRunner {
|
||||
struct promise_type {
|
||||
std::shared_ptr<ScopeControl> scope{};
|
||||
std::shared_ptr<ChildTaskControl> child{};
|
||||
std::optional<Coro::Task<void>> task{};
|
||||
|
||||
ScopeRunner get_return_object() noexcept
|
||||
{
|
||||
return ScopeRunner{
|
||||
std::coroutine_handle<promise_type>::from_promise(*this)};
|
||||
}
|
||||
|
||||
std::suspend_always initial_suspend() noexcept { return {}; }
|
||||
|
||||
struct FinalAwaiter {
|
||||
bool await_ready() const noexcept { return false; }
|
||||
void await_suspend(std::coroutine_handle<promise_type> h) noexcept
|
||||
{
|
||||
auto sc = std::move(h.promise().scope);
|
||||
auto ch = std::move(h.promise().child);
|
||||
h.promise().task.reset();
|
||||
// Destroy the coroutine frame completely before decrementing active
|
||||
// task counters or waking any join waiter.
|
||||
h.destroy();
|
||||
if (ch) {
|
||||
ch->mark_finished();
|
||||
}
|
||||
if (sc) {
|
||||
sc->on_task_finished();
|
||||
}
|
||||
}
|
||||
void await_resume() const noexcept {}
|
||||
};
|
||||
|
||||
FinalAwaiter final_suspend() noexcept { return {}; }
|
||||
void return_void() noexcept {}
|
||||
void unhandled_exception() noexcept {}
|
||||
|
||||
auto await_transform(TakePromiseTaskTag) noexcept
|
||||
{
|
||||
struct Awaiter {
|
||||
promise_type* p;
|
||||
bool await_ready() const noexcept { return true; }
|
||||
void await_suspend(std::coroutine_handle<>) noexcept {}
|
||||
Coro::Task<void> await_resume() noexcept
|
||||
{
|
||||
auto t = std::move(*p->task);
|
||||
p->task.reset();
|
||||
return t;
|
||||
}
|
||||
};
|
||||
return Awaiter{this};
|
||||
}
|
||||
|
||||
auto await_transform(GetScopePtrTag) noexcept
|
||||
{
|
||||
struct Awaiter {
|
||||
promise_type* p;
|
||||
bool await_ready() const noexcept { return true; }
|
||||
void await_suspend(std::coroutine_handle<>) noexcept {}
|
||||
std::shared_ptr<ScopeControl> await_resume() noexcept
|
||||
{
|
||||
return p->scope;
|
||||
}
|
||||
};
|
||||
return Awaiter{this};
|
||||
}
|
||||
|
||||
auto await_transform(GetChildPtrTag) noexcept
|
||||
{
|
||||
struct Awaiter {
|
||||
promise_type* p;
|
||||
bool await_ready() const noexcept { return true; }
|
||||
void await_suspend(std::coroutine_handle<>) noexcept {}
|
||||
std::shared_ptr<ChildTaskControl> await_resume() noexcept
|
||||
{
|
||||
return p->child;
|
||||
}
|
||||
};
|
||||
return Awaiter{this};
|
||||
}
|
||||
|
||||
template <typename A>
|
||||
decltype(auto) await_transform(A&& awaitable) noexcept
|
||||
{
|
||||
return std::forward<A>(awaitable);
|
||||
}
|
||||
};
|
||||
|
||||
std::coroutine_handle<promise_type> handle{};
|
||||
};
|
||||
|
||||
inline ScopeRunner make_scope_runner()
|
||||
{
|
||||
auto task = co_await TakePromiseTaskTag{};
|
||||
auto scope = co_await GetScopePtrTag{};
|
||||
auto child = co_await GetChildPtrTag{};
|
||||
try {
|
||||
co_await std::move(task);
|
||||
} catch (const std::exception& ex) {
|
||||
if (child) {
|
||||
child->set_error(make_async_error(AsyncErrorCode::backend_error, ex.what()));
|
||||
}
|
||||
if (scope) {
|
||||
scope->record_exception(std::current_exception(), ex.what());
|
||||
}
|
||||
} catch (...) {
|
||||
constexpr std::string_view kUnknown =
|
||||
"Unhandled non-std exception in TaskScope task";
|
||||
if (child) {
|
||||
child->set_error(
|
||||
make_async_error(AsyncErrorCode::backend_error, std::string{kUnknown}));
|
||||
}
|
||||
if (scope) {
|
||||
scope->record_exception(std::current_exception(), kUnknown);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
class JoinHandle
|
||||
{
|
||||
public:
|
||||
explicit JoinHandle(std::shared_ptr<detail::ChildTaskControl> control) noexcept
|
||||
: control_(std::move(control))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] bool done() const
|
||||
{
|
||||
return !control_ || control_->done();
|
||||
}
|
||||
|
||||
bool request_stop() noexcept
|
||||
{
|
||||
return control_ ? control_->request_stop() : false;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::stop_token stop_token() const noexcept
|
||||
{
|
||||
return control_ ? control_->stop_token() : std::stop_token{};
|
||||
}
|
||||
|
||||
struct JoinAwaiter {
|
||||
std::shared_ptr<detail::ChildTaskControl> control;
|
||||
|
||||
[[nodiscard]] bool await_ready() const noexcept
|
||||
{
|
||||
return !control || control->done();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter)
|
||||
{
|
||||
return control->try_register_waiter(waiter);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> await_resume() const
|
||||
{
|
||||
return control ? control->take_outcome() : Void::Result::Result<void>{};
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] JoinAwaiter join() const noexcept
|
||||
{
|
||||
return JoinAwaiter{control_};
|
||||
}
|
||||
|
||||
[[nodiscard]] JoinAwaiter operator co_await() const noexcept
|
||||
{
|
||||
return join();
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> join_blocking() const
|
||||
{
|
||||
return control_ ? control_->join_blocking() : Void::Result::Result<void>{};
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<detail::ChildTaskControl> control_{};
|
||||
};
|
||||
|
||||
class TaskScope
|
||||
{
|
||||
public:
|
||||
explicit TaskScope(
|
||||
Executor& executor,
|
||||
TaskScopeOptions options = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance())
|
||||
: control_(detail::ScopeControl::create(executor, options))
|
||||
, clock_(clock)
|
||||
{
|
||||
}
|
||||
|
||||
~TaskScope()
|
||||
{
|
||||
control_->request_stop();
|
||||
control_->close();
|
||||
if (control_->active_count() > 0) {
|
||||
if (!control_->executor().has_background_workers()) {
|
||||
if (auto* manual = dynamic_cast<ManualExecutor*>(&control_->executor())) {
|
||||
(void)join_pumping(*manual);
|
||||
}
|
||||
} else if (!control_->executor().is_executor_thread()) {
|
||||
(void)control_->join_blocking();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TaskScope(const TaskScope&) = delete;
|
||||
TaskScope& operator=(const TaskScope&) = delete;
|
||||
TaskScope(TaskScope&&) = delete;
|
||||
TaskScope& operator=(TaskScope&&) = delete;
|
||||
|
||||
// Reserve-then-transfer spawn: failed admission preserves `task` intact in
|
||||
// the caller without destroying or losing its coroutine frame.
|
||||
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
|
||||
spawn(Coro::Task<void>&& task, OperationOptions options = {})
|
||||
{
|
||||
if (!task.handle() || task.done()) {
|
||||
return std::unexpected{AdmissionError::invalid_argument};
|
||||
}
|
||||
return admit_and_launch(options, &task, nullptr);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
requires (!std::same_as<std::remove_cvref_t<F>, Coro::Task<void>>) &&
|
||||
std::invocable<F, std::stop_token> &&
|
||||
std::same_as<std::invoke_result_t<F, std::stop_token>, Coro::Task<void>>
|
||||
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
|
||||
spawn(F&& factory, OperationOptions options = {})
|
||||
{
|
||||
return admit_and_launch(
|
||||
options,
|
||||
nullptr,
|
||||
[&](std::stop_token st) -> Coro::Task<void> {
|
||||
return std::invoke(std::forward<F>(factory), st);
|
||||
});
|
||||
}
|
||||
|
||||
bool request_stop() noexcept { return control_->request_stop(); }
|
||||
void close() noexcept { control_->close(); }
|
||||
[[nodiscard]] std::stop_token stop_token() const noexcept { return control_->stop_token(); }
|
||||
[[nodiscard]] std::size_t active_count() const { return control_->active_count(); }
|
||||
[[nodiscard]] std::size_t failure_count() const { return control_->failure_count(); }
|
||||
[[nodiscard]] bool has_exception() const { return control_->has_exception(); }
|
||||
[[nodiscard]] std::exception_ptr first_exception() const { return control_->first_exception(); }
|
||||
|
||||
struct ScopeJoinAwaiter {
|
||||
std::shared_ptr<detail::ScopeControl> control;
|
||||
|
||||
[[nodiscard]] bool await_ready() const noexcept
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter)
|
||||
{
|
||||
return control->try_begin_async_join(waiter);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> await_resume() const
|
||||
{
|
||||
return control->finish_outcome();
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] ScopeJoinAwaiter join() noexcept
|
||||
{
|
||||
return ScopeJoinAwaiter{control_};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> join_blocking()
|
||||
{
|
||||
return control_->join_blocking();
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> join_pumping(ManualExecutor& manual)
|
||||
{
|
||||
control_->close();
|
||||
while (control_->active_count() > 0) {
|
||||
if (manual.drain() == 0 && control_->active_count() > 0) {
|
||||
std::this_thread::yield();
|
||||
}
|
||||
}
|
||||
return control_->finish_outcome();
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> join_pumping()
|
||||
{
|
||||
auto* manual = dynamic_cast<ManualExecutor*>(&control_->executor());
|
||||
if (manual == nullptr) {
|
||||
return std::unexpected{make_async_error(
|
||||
AsyncErrorCode::invalid_argument,
|
||||
"TaskScope::join_pumping requires ManualExecutor")};
|
||||
}
|
||||
return join_pumping(*manual);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename FactoryFn = std::nullptr_t>
|
||||
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
|
||||
admit_and_launch(const OperationOptions& options,
|
||||
Coro::Task<void>* existing_task,
|
||||
FactoryFn&& factory)
|
||||
{
|
||||
if (auto sr = control_->try_reserve(options, clock_); !sr.has_value()) {
|
||||
return std::unexpected{sr.error()};
|
||||
}
|
||||
|
||||
Executor& exec = control_->executor();
|
||||
const bool use_reserved = exec.supports_reservation();
|
||||
if (use_reserved) {
|
||||
if (auto er = exec.try_reserve_slot(); !er.has_value()) {
|
||||
control_->release_reservation();
|
||||
return std::unexpected{er.error()};
|
||||
}
|
||||
}
|
||||
|
||||
auto child = std::make_shared<detail::ChildTaskControl>(exec);
|
||||
child->attach_stops(control_->stop_token(), options.stop);
|
||||
|
||||
detail::ScopeRunner runner{};
|
||||
try {
|
||||
runner = detail::make_scope_runner();
|
||||
auto& prom = runner.handle.promise();
|
||||
prom.scope = control_;
|
||||
prom.child = child;
|
||||
if (existing_task != nullptr) {
|
||||
prom.task.emplace(std::move(*existing_task));
|
||||
} else if constexpr (!std::is_null_pointer_v<std::decay_t<FactoryFn>>) {
|
||||
prom.task.emplace(factory(child->stop_token()));
|
||||
}
|
||||
} catch (...) {
|
||||
if (runner.handle) {
|
||||
if (existing_task != nullptr && runner.handle.promise().task.has_value()) {
|
||||
*existing_task = std::move(*runner.handle.promise().task);
|
||||
}
|
||||
runner.handle.promise().scope.reset();
|
||||
runner.handle.promise().child.reset();
|
||||
runner.handle.destroy();
|
||||
}
|
||||
if (use_reserved) {
|
||||
exec.release_reserved();
|
||||
}
|
||||
control_->release_reservation();
|
||||
throw;
|
||||
}
|
||||
|
||||
auto rollback_unstarted = [&]() {
|
||||
if (existing_task != nullptr && runner.handle.promise().task.has_value()) {
|
||||
*existing_task = std::move(*runner.handle.promise().task);
|
||||
}
|
||||
runner.handle.promise().scope.reset();
|
||||
runner.handle.promise().child.reset();
|
||||
runner.handle.destroy();
|
||||
if (use_reserved) {
|
||||
exec.release_reserved();
|
||||
}
|
||||
control_->release_reservation();
|
||||
};
|
||||
|
||||
if (use_reserved) {
|
||||
try {
|
||||
exec.commit_reserved(runner.handle);
|
||||
} catch (...) {
|
||||
rollback_unstarted();
|
||||
return std::unexpected{AdmissionError::overloaded};
|
||||
}
|
||||
} else {
|
||||
auto post_res = exec.try_post(runner.handle);
|
||||
if (!post_res.has_value()) {
|
||||
rollback_unstarted();
|
||||
return std::unexpected{post_res.error()};
|
||||
}
|
||||
}
|
||||
|
||||
return JoinHandle{std::move(child)};
|
||||
}
|
||||
|
||||
std::shared_ptr<detail::ScopeControl> control_;
|
||||
const Void::Time::MonotonicClock& clock_;
|
||||
};
|
||||
|
||||
// Explicit structured lifetime owner for detached/background fire-and-forget work.
|
||||
class DetachedOwner
|
||||
{
|
||||
public:
|
||||
explicit DetachedOwner(
|
||||
Executor& executor,
|
||||
TaskScopeOptions options = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance())
|
||||
: scope_(executor, options, clock)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
|
||||
spawn(Coro::Task<void>&& task, OperationOptions options = {})
|
||||
{
|
||||
return scope_.spawn(std::move(task), std::move(options));
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
requires (!std::same_as<std::remove_cvref_t<F>, Coro::Task<void>>) &&
|
||||
std::invocable<F, std::stop_token> &&
|
||||
std::same_as<std::invoke_result_t<F, std::stop_token>, Coro::Task<void>>
|
||||
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
|
||||
spawn(F&& factory, OperationOptions options = {})
|
||||
{
|
||||
return scope_.spawn(std::forward<F>(factory), std::move(options));
|
||||
}
|
||||
|
||||
bool request_stop() noexcept { return scope_.request_stop(); }
|
||||
void close() noexcept { scope_.close(); }
|
||||
[[nodiscard]] std::stop_token stop_token() const noexcept { return scope_.stop_token(); }
|
||||
[[nodiscard]] std::size_t active_count() const { return scope_.active_count(); }
|
||||
[[nodiscard]] std::size_t failure_count() const { return scope_.failure_count(); }
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> drain_blocking() { return scope_.join_blocking(); }
|
||||
[[nodiscard]] Void::Result::Result<void> drain_pumping() { return scope_.join_pumping(); }
|
||||
[[nodiscard]] Void::Result::Result<void> drain_pumping(ManualExecutor& manual)
|
||||
{
|
||||
return scope_.join_pumping(manual);
|
||||
}
|
||||
|
||||
private:
|
||||
TaskScope scope_;
|
||||
};
|
||||
|
||||
} // namespace Void::Async
|
||||
Reference in new issue
Block a user