#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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::max(), parent_stop, stop_on_first_error}; } }; namespace detail { class ScopeControl; class ChildTaskControl : public std::enable_shared_from_this { 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 take_outcome() const { std::lock_guard lk{mu_}; if (error_.has_value()) { return std::unexpected{*error_}; } return {}; } [[nodiscard]] Void::Result::Result 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 error_{}; std::coroutine_handle<> async_waiter_{}; // MUST stay LAST so stop callbacks synchronize before members destruct. std::optional> scope_stop_cb_{}; std::optional> option_stop_cb_{}; }; class ScopeControl : public std::enable_shared_from_this { public: [[nodiscard]] static std::shared_ptr create( Executor& executor, TaskScopeOptions options) { auto ptr = std::shared_ptr( 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 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 finish_outcome() const { std::lock_guard lk{mu_}; if (first_error_.has_value()) { return std::unexpected{*first_error_}; } return {}; } [[nodiscard]] Void::Result::Result 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(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 first_error_{}; std::coroutine_handle<> async_join_waiter_{}; // MUST stay LAST: waits for any active parent stop callback on destruction. std::optional> parent_stop_cb_{}; }; struct TakePromiseTaskTag {}; struct GetScopePtrTag {}; struct GetChildPtrTag {}; struct ScopeRunner { struct promise_type { std::shared_ptr scope{}; std::shared_ptr child{}; std::optional> task{}; ScopeRunner get_return_object() noexcept { return ScopeRunner{ std::coroutine_handle::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 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 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 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 await_resume() noexcept { return p->child; } }; return Awaiter{this}; } template decltype(auto) await_transform(A&& awaitable) noexcept { return std::forward(awaitable); } }; std::coroutine_handle 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 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 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 await_resume() const { return control ? control->take_outcome() : Void::Result::Result{}; } }; [[nodiscard]] JoinAwaiter join() const noexcept { return JoinAwaiter{control_}; } [[nodiscard]] JoinAwaiter operator co_await() const noexcept { return join(); } [[nodiscard]] Void::Result::Result join_blocking() const { return control_ ? control_->join_blocking() : Void::Result::Result{}; } private: std::shared_ptr 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(&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 spawn(Coro::Task&& task, OperationOptions options = {}) { if (!task.handle() || task.done()) { return std::unexpected{AdmissionError::invalid_argument}; } return admit_and_launch(options, &task, nullptr); } template requires (!std::same_as, Coro::Task>) && std::invocable && std::same_as, Coro::Task> [[nodiscard]] std::expected spawn(F&& factory, OperationOptions options = {}) { return admit_and_launch( options, nullptr, [&](std::stop_token st) -> Coro::Task { return std::invoke(std::forward(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 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 await_resume() const { return control->finish_outcome(); } }; [[nodiscard]] ScopeJoinAwaiter join() noexcept { return ScopeJoinAwaiter{control_}; } [[nodiscard]] Void::Result::Result join_blocking() { return control_->join_blocking(); } [[nodiscard]] Void::Result::Result 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 join_pumping() { auto* manual = dynamic_cast(&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 [[nodiscard]] std::expected admit_and_launch(const OperationOptions& options, Coro::Task* 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(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>) { 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 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 spawn(Coro::Task&& task, OperationOptions options = {}) { return scope_.spawn(std::move(task), std::move(options)); } template requires (!std::same_as, Coro::Task>) && std::invocable && std::same_as, Coro::Task> [[nodiscard]] std::expected spawn(F&& factory, OperationOptions options = {}) { return scope_.spawn(std::forward(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 drain_blocking() { return scope_.join_blocking(); } [[nodiscard]] Void::Result::Result drain_pumping() { return scope_.join_pumping(); } [[nodiscard]] Void::Result::Result drain_pumping(ManualExecutor& manual) { return scope_.join_pumping(manual); } private: TaskScope scope_; }; } // namespace Void::Async