Files
Library/include/Void/Runtime/Detail/HostCore.hpp
T

1673 lines
62 KiB
C++

#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Pump.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Memory/BudgetResource.hpp>
#include <Void/Runtime/Lifecycle.hpp>
#include <Void/Runtime/Options.hpp>
#include <Void/Runtime/ResourceGraph.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <cstdio>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <system_error>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Runtime::detail
{
[[nodiscard]] inline const void*& tl_reactor_host() noexcept
{
thread_local const void* current = nullptr;
return current;
}
class ReactorThreadGuard
{
public:
explicit ReactorThreadGuard(const void* host) noexcept
: prev_(tl_reactor_host())
{
tl_reactor_host() = host;
}
~ReactorThreadGuard()
{
tl_reactor_host() = prev_;
}
ReactorThreadGuard(const ReactorThreadGuard&) = delete;
ReactorThreadGuard& operator=(const ReactorThreadGuard&) = delete;
private:
const void* prev_{nullptr};
};
struct DetachedCoro {
struct promise_type {
DetachedCoro get_return_object() noexcept
{
return DetachedCoro{
std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() noexcept {}
void unhandled_exception() noexcept { std::terminate(); }
};
std::coroutine_handle<promise_type> handle{};
};
struct ProbeSignal {
std::mutex mu{};
std::condition_variable cv{};
bool done{false};
};
inline DetachedCoro make_readiness_probe(std::shared_ptr<ProbeSignal> sig)
{
{
std::lock_guard lk{sig->mu};
sig->done = true;
}
sig->cv.notify_all();
sig.reset();
co_return;
}
struct StopSync {
std::mutex mu{};
std::condition_variable cv{};
};
struct ComponentEntry {
std::string id{};
ResourceKind kind{ResourceKind::service};
bool critical{true};
std::shared_ptr<Component> component{};
bool started{false};
bool stop_launched{false};
std::atomic<bool> stop_done{false};
std::optional<Void::Result::Result<void>> stop_result{};
std::shared_ptr<StopSync> sync{std::make_shared<StopSync>()};
};
inline DetachedCoro run_component_stop(
std::shared_ptr<Component> comp,
Async::OperationOptions opts,
std::shared_ptr<ComponentEntry> entry)
{
Void::Result::Result<void> res{};
try {
{
auto task = comp->stop(std::move(opts));
res = co_await std::move(task);
}
} catch (const std::exception& e) {
res = std::unexpected{make_runtime_error(
RuntimeErrorCode::internal, e.what())};
} catch (...) {
res = std::unexpected{make_runtime_error(
RuntimeErrorCode::internal,
"Unhandled exception in Component::stop")};
}
// Drop local Component ref BEFORE signalling done so releasing_components
// deterministically owns component destruction (exporter_stopped < exporter_destroyed).
comp.reset();
{
std::lock_guard lk{entry->sync->mu};
entry->stop_result = std::move(res);
entry->stop_done.store(true, std::memory_order_release);
}
entry->sync->cv.notify_all();
co_return;
}
struct HostCore {
using TimePoint = Void::Time::MonotonicClock::time_point;
Options options{};
LifecyclePlan plan{};
EmbeddedResources embedded{};
std::unique_ptr<Void::Memory::BudgetResource> owned_budget{};
std::unordered_map<std::string, std::shared_ptr<ComponentEntry>>
registered_components{};
mutable std::mutex mu{};
std::condition_variable cv{};
HostState state{HostState::constructed};
bool ready{false};
bool admission_closed{false};
std::size_t started_workers{0};
std::optional<std::thread::id> owner_thread{};
StartOptions start_options{};
SignalGate* signal_gate{nullptr};
bool gate_installed{false};
std::function<void(ShutdownPhase)> on_phase{};
std::unique_ptr<Async::ThreadExecutor> owned_executor{};
std::unique_ptr<IO::Driver> owned_driver{};
std::unique_ptr<Async::TaskScope> business_scope{};
std::stop_source business_stop_source{};
std::stop_source exporter_stop_source{};
std::stop_source reactor_stop_source{};
std::thread reactor_thread{};
std::atomic<std::size_t> reactor_turns{0};
std::vector<std::string> started_component_ids{};
ShutdownPhase phase{ShutdownPhase::not_started};
bool start_running{false};
bool shutdown_running{false};
bool begin_shutdown_called{false};
bool failed_start_incomplete{false};
std::optional<TimePoint> drain_deadline{};
std::optional<TimePoint> flush_deadline{};
bool drain_grace_expired{false};
bool export_flush_expired{false};
bool owner_release_pending{false};
std::optional<ShutdownReport> last_report{};
HostCore(
Options opts,
LifecyclePlan lifecycle_plan,
EmbeddedResources emb,
std::unique_ptr<Void::Memory::BudgetResource> budget,
std::vector<std::shared_ptr<ComponentEntry>> comps) noexcept
: options(std::move(opts))
, plan(std::move(lifecycle_plan))
, embedded(emb)
, owned_budget(std::move(budget))
{
for (auto& c : comps) {
if (c) {
registered_components.emplace(c->id, std::move(c));
}
}
}
~HostCore() noexcept
{
if (is_on_owned_worker_thread()) {
std::fputs(
"Void::Runtime::Host destroyed on an owned Runtime worker, reactor, or IO "
"worker thread; terminating\n",
stderr);
std::terminate();
}
bool needs_teardown = false;
{
std::lock_guard lk{mu};
needs_teardown =
state == HostState::starting ||
state == HostState::running ||
state == HostState::stopping_admission ||
state == HostState::draining ||
state == HostState::joining ||
state == HostState::shutdown_incomplete ||
(state == HostState::failed_start && failed_start_incomplete);
}
if (needs_teardown) {
if (options.embedded_mode) {
if (auto* manual =
dynamic_cast<Async::ManualExecutor*>(embedded.executor)) {
for (;;) {
auto r = shutdown_pumping_impl(
*manual,
Async::OperationOptions{.deadline = TimePoint::max()},
nullptr,
/*unbounded=*/true);
if (!r.has_value()) {
std::fputs(
"Void::Runtime::Host embedded destructor could not pump "
"shutdown; terminating\n",
stderr);
std::terminate();
}
if (r->complete) {
break;
}
}
} else if (embedded.executor != nullptr &&
embedded.executor->has_background_workers()) {
for (;;) {
auto r = shutdown_blocking_impl(
Async::OperationOptions{.deadline = TimePoint::max()},
/*unbounded=*/true);
if (!r.has_value()) {
std::fputs(
"Void::Runtime::Host (embedded background-worker executor) "
"destructor could not complete shutdown; terminating\n",
stderr);
std::terminate();
}
if (r->complete) {
break;
}
}
} else {
std::fputs(
"Void::Runtime::Host (embedded non-ManualExecutor) destroyed before "
"shutdown completed; terminating\n",
stderr);
std::terminate();
}
} else {
for (;;) {
auto r = shutdown_blocking_impl(
Async::OperationOptions{.deadline = TimePoint::max()},
/*unbounded=*/true);
if (!r.has_value()) {
std::fputs(
"Void::Runtime::Host destructor could not complete shutdown; "
"terminating\n",
stderr);
std::terminate();
}
if (r->complete) {
break;
}
}
}
}
// Release SignalGate at most once if still installed (e.g. off-owner shutdown
// deferred uninstall until destructor ran).
SignalGate* gate_to_drop = nullptr;
bool on_owner = false;
{
std::lock_guard lk{mu};
if (gate_installed && signal_gate != nullptr) {
gate_to_drop = signal_gate;
on_owner = owner_thread.has_value() &&
std::this_thread::get_id() == *owner_thread;
gate_installed = false;
owner_release_pending = false;
}
}
if (gate_to_drop != nullptr) {
gate_to_drop->uninstall(on_owner);
}
}
HostCore(const HostCore&) = delete;
HostCore& operator=(const HostCore&) = delete;
HostCore(HostCore&&) = delete;
HostCore& operator=(HostCore&&) = delete;
[[nodiscard]] HostState current_state() const noexcept
{
std::lock_guard lk{mu};
return state;
}
[[nodiscard]] bool current_ready() const noexcept
{
std::lock_guard lk{mu};
return ready;
}
[[nodiscard]] std::size_t current_workers() const noexcept
{
std::lock_guard lk{mu};
return started_workers;
}
[[nodiscard]] std::optional<std::thread::id> current_owner_thread() const noexcept
{
std::lock_guard lk{mu};
return owner_thread;
}
[[nodiscard]] std::optional<ShutdownReport> current_last_report() const
{
std::lock_guard lk{mu};
return last_report;
}
[[nodiscard]] const Void::Time::MonotonicClock& active_clock() const noexcept
{
return embedded.clock ? *embedded.clock
: Void::Time::SystemMonotonicClock::instance();
}
[[nodiscard]] Void::Memory::BudgetResource& active_budget() noexcept
{
return embedded.memory_budget ? *embedded.memory_budget : *owned_budget;
}
[[nodiscard]] Async::Executor* active_executor() noexcept
{
return options.embedded_mode ? embedded.executor : owned_executor.get();
}
[[nodiscard]] IO::Driver* get_io() noexcept
{
return options.embedded_mode ? embedded.io : owned_driver.get();
}
[[nodiscard]] std::size_t cpu_admitted_count() const noexcept
{
std::lock_guard lk{mu};
if (options.embedded_mode || !owned_executor) {
return 0;
}
return owned_executor->admitted();
}
[[nodiscard]] bool is_on_owned_worker_thread() const noexcept
{
if (tl_reactor_host() == this) {
return true;
}
if (options.embedded_mode) {
if (embedded.executor != nullptr &&
embedded.executor->is_executor_thread()) {
return true;
}
return false;
}
Async::ThreadExecutor* exec = nullptr;
bool has_drv = false;
{
std::lock_guard lk{mu};
exec = owned_executor.get();
has_drv = (owned_driver != nullptr);
}
if (exec != nullptr && exec->is_executor_thread()) {
return true;
}
if (has_drv && IO::is_io_worker_thread()) {
return true;
}
return false;
}
void emit_phase(ShutdownPhase p) noexcept
{
std::function<void(ShutdownPhase)> cb;
{
std::lock_guard lk{mu};
phase = p;
cb = on_phase;
}
if (cb) {
try {
cb(p);
} catch (...) {
}
}
}
[[nodiscard]] ShutdownReport build_report_locked(bool complete) noexcept
{
ShutdownReport rep;
rep.complete = complete;
rep.state = state;
rep.phase = phase;
rep.pending_business_tasks =
business_scope ? business_scope->active_count() : 0;
if (!options.embedded_mode && owned_executor) {
rep.pending_cpu_admitted = owned_executor->admitted();
}
if (auto* drv = get_io()) {
const auto tel = drv->telemetry();
rep.pending_io_operations = tel.active_operations;
const std::size_t io_bytes =
tel.owned_buffer_bytes + tel.borrowed_buffer_bytes;
const std::size_t budget_bytes =
active_budget().stats().committed_live;
rep.retained_buffer_bytes = std::max(io_bytes, budget_bytes);
} else {
rep.retained_buffer_bytes = active_budget().stats().committed_live;
}
rep.drain_grace_expired = drain_grace_expired;
rep.export_flush_expired = export_flush_expired;
rep.owner_release_pending = owner_release_pending;
if (!complete) {
if (rep.pending_business_tasks > 0) {
rep.pending_owner_ids.emplace_back("business_tasks");
}
for (const auto& id : started_component_ids) {
auto it = registered_components.find(id);
if (it != registered_components.end() && it->second &&
!it->second->stop_done.load(std::memory_order_acquire)) {
rep.pending_owner_ids.push_back(id);
}
}
if (!options.embedded_mode && owned_driver &&
!owned_driver->shutdown_complete()) {
rep.pending_owner_ids.emplace_back("io_driver");
}
if (!options.embedded_mode && owned_executor &&
phase == ShutdownPhase::stopping_workers &&
started_workers > 0) {
rep.pending_owner_ids.emplace_back("cpu_executor");
}
rep.pending_owners = rep.pending_owner_ids.size();
}
return rep;
}
template <typename Pred>
[[nodiscard]] bool wait_until_clock(
Pred&& pred,
TimePoint deadline,
std::stop_token stop = {})
{
for (;;) {
if (pred()) {
return true;
}
if (stop.stop_requested()) {
return false;
}
if (deadline != TimePoint::max() && active_clock().now() >= deadline) {
return pred();
}
std::mutex local_mu;
std::condition_variable local_cv;
std::unique_lock lk{local_mu};
local_cv.wait_for(lk, std::chrono::milliseconds{1});
}
}
template <typename Pred>
[[nodiscard]] bool wait_component_entry(
const std::shared_ptr<ComponentEntry>& entry,
Pred&& pred,
TimePoint deadline,
std::stop_token stop = {})
{
for (;;) {
if (pred()) {
return true;
}
if (stop.stop_requested()) {
return false;
}
if (deadline != TimePoint::max() && active_clock().now() >= deadline) {
return pred();
}
std::unique_lock lk{entry->sync->mu};
entry->sync->cv.wait_for(lk, std::chrono::milliseconds{1}, [&] {
return pred() || stop.stop_requested();
});
}
}
template <typename Pred>
[[nodiscard]] bool pump_wait(
Async::ManualExecutor& manual,
Pred&& pred,
TimePoint deadline,
std::stop_token stop,
Async::TimerQueue* timers,
bool single_drain_if_poll)
{
if (pred()) {
return true;
}
if (single_drain_if_poll && !stop.stop_requested()) {
(void)manual.drain();
if (pred()) {
return true;
}
}
IO::Driver* drv = nullptr;
{
std::lock_guard lk{mu};
drv = get_io();
}
if (drv == nullptr) {
return pred();
}
IO::PumpOptions opts{};
opts.max_wait = std::chrono::milliseconds{1};
opts.operation.stop = stop;
if (deadline != TimePoint::max()) {
opts.operation.deadline = deadline;
}
opts.timers = timers;
for (;;) {
auto r = IO::pump_until(*drv, manual, pred, opts);
if (pred()) {
return true;
}
if (single_drain_if_poll || stop.stop_requested()) {
return false;
}
if (deadline != TimePoint::max() && active_clock().now() >= deadline) {
return pred();
}
if (!r.has_value() &&
r.error().code().domain == Void::Result::kIoErrorDomain &&
r.error().code().value ==
static_cast<std::int32_t>(IO::IoErrorCode::exhausted)) {
continue;
}
return pred();
}
}
void run_reactor_loop()
{
ReactorThreadGuard guard{this};
const auto stop = reactor_stop_source.get_token();
constexpr auto kMaxWait = std::chrono::milliseconds{5};
auto wait_stop_aware = [&](std::chrono::nanoseconds budget) {
if (budget <= std::chrono::nanoseconds{0} ||
stop.stop_requested() || owned_driver->shutdown_complete()) {
return;
}
std::mutex local_mu;
std::condition_variable local_cv;
std::stop_callback cb(stop, [&]() noexcept {
std::lock_guard lk{local_mu};
local_cv.notify_all();
});
std::unique_lock lk{local_mu};
auto remaining = budget;
constexpr auto kSlice =
std::chrono::nanoseconds{std::chrono::milliseconds{1}};
while (remaining > std::chrono::nanoseconds{0} &&
!stop.stop_requested() &&
!owned_driver->shutdown_complete()) {
const auto step = std::min(remaining, kSlice);
local_cv.wait_for(lk, step, [&]() {
return stop.stop_requested() ||
owned_driver->shutdown_complete();
});
remaining -= step;
}
};
std::size_t consecutive_fast_zero = 0;
while (!stop.stop_requested() && !owned_driver->shutdown_complete()) {
const auto poll_start = std::chrono::steady_clock::now();
auto r = owned_driver->poll_once(kMaxWait);
const auto poll_elapsed = std::chrono::steady_clock::now() - poll_start;
if (!r.has_value()) {
if (r.error().code().domain == Void::Result::kIoErrorDomain &&
r.error().code().value ==
static_cast<std::int32_t>(IO::IoErrorCode::busy)) {
consecutive_fast_zero = 0;
wait_stop_aware(std::chrono::milliseconds{1});
continue;
}
break;
}
reactor_turns.fetch_add(1, std::memory_order_release);
cv.notify_all();
if (*r == 0 && poll_elapsed < kMaxWait) {
const auto remain = std::chrono::duration_cast<std::chrono::nanoseconds>(
kMaxWait - poll_elapsed);
if (owned_driver->active_backend() == IO::BackendPreference::mock) {
wait_stop_aware(remain);
} else if (++consecutive_fast_zero >= 2) {
wait_stop_aware(std::min(
remain,
std::chrono::nanoseconds{std::chrono::milliseconds{1}}));
}
} else {
consecutive_fast_zero = 0;
}
}
}
[[nodiscard]] Void::Result::Error
wrap_start_failure(StartStep step, Void::Result::Error root) const
{
const char* label = "unknown";
switch (step) {
case StartStep::signal_gate: label = "signal_gate"; break;
case StartStep::memory_budget: label = "memory_budget"; break;
case StartStep::cpu_executor: label = "cpu_executor"; break;
case StartStep::io_driver: label = "io_driver"; break;
case StartStep::file_workers: label = "file_workers"; break;
case StartStep::reactor: label = "reactor"; break;
case StartStep::components: label = "components"; break;
case StartStep::readiness: label = "readiness"; break;
}
return std::move(root).with_context(
std::string{"Host start failed at step "} + label);
}
void cleanup_after_start_failure(TimePoint cleanup_dl) noexcept
{
Async::Executor* exec = active_executor();
Async::ManualExecutor* manual =
options.embedded_mode
? dynamic_cast<Async::ManualExecutor*>(embedded.executor)
: nullptr;
if (!started_component_ids.empty()) {
emit_phase(ShutdownPhase::stopping_components);
for (auto it = started_component_ids.rbegin();
it != started_component_ids.rend();
++it) {
auto found = registered_components.find(*it);
if (found == registered_components.end() || !found->second) {
continue;
}
auto entry = found->second;
if (!entry->started ||
entry->stop_done.load(std::memory_order_acquire)) {
continue;
}
if (!entry->stop_launched && exec != nullptr) {
entry->stop_launched = true;
auto coro = run_component_stop(
entry->component,
Async::OperationOptions{.deadline = cleanup_dl},
entry);
exec->post_completion(coro.handle);
}
bool finished = false;
auto pred = [&]() {
return entry->stop_done.load(std::memory_order_acquire);
};
if (manual != nullptr) {
finished = pump_wait(
*manual, pred, cleanup_dl, {}, nullptr, false);
} else {
finished = wait_component_entry(entry, pred, cleanup_dl);
}
if (!finished) {
std::lock_guard lk{mu};
failed_start_incomplete = true;
last_report = build_report_locked(false);
return;
}
}
emit_phase(ShutdownPhase::releasing_components);
std::unordered_map<std::string, std::shared_ptr<ComponentEntry>> dropped;
{
std::lock_guard lk{mu};
dropped.swap(registered_components);
started_component_ids.clear();
}
for (auto& [k, c] : dropped) {
(void)k;
if (c) {
c->component.reset();
}
}
dropped.clear();
}
if (!options.embedded_mode) {
if (reactor_thread.joinable() || owned_driver) {
emit_phase(ShutdownPhase::stopping_io);
}
reactor_stop_source.request_stop();
if (owned_driver) {
owned_driver->wake();
}
if (reactor_thread.joinable()) {
reactor_thread.join();
}
if (owned_driver) {
auto io_rep = owned_driver->shutdown(
Async::OperationOptions{.deadline = cleanup_dl});
if (!io_rep.has_value() || !io_rep->complete) {
const std::size_t file_workers_alive =
owned_driver->telemetry().file_workers_running;
std::lock_guard lk{mu};
started_workers =
(owned_executor ? options.cpu_workers : 0) +
file_workers_alive;
failed_start_incomplete = true;
last_report = build_report_locked(false);
return;
}
}
if (owned_executor) {
emit_phase(ShutdownPhase::stopping_workers);
owned_executor->close();
if (!wait_until_clock(
[&]() { return owned_executor->idle(); },
cleanup_dl)) {
std::lock_guard lk{mu};
started_workers = options.cpu_workers;
failed_start_incomplete = true;
last_report = build_report_locked(false);
return;
}
(void)owned_executor->join();
}
std::unique_ptr<Async::TaskScope> drop_scope;
std::unique_ptr<IO::Driver> drop_drv;
std::unique_ptr<Async::ThreadExecutor> drop_exec;
{
std::lock_guard lk{mu};
drop_scope = std::move(business_scope);
drop_drv = std::move(owned_driver);
drop_exec = std::move(owned_executor);
started_workers = 0;
}
drop_scope.reset();
drop_drv.reset();
drop_exec.reset();
} else {
std::lock_guard lk{mu};
business_scope.reset();
}
SignalGate* gate_to_drop = nullptr;
bool on_owner = false;
{
std::lock_guard lk{mu};
if (gate_installed && signal_gate != nullptr) {
gate_to_drop = signal_gate;
on_owner = owner_thread.has_value() &&
std::this_thread::get_id() == *owner_thread;
gate_installed = false;
owner_release_pending = false;
}
}
if (gate_to_drop != nullptr) {
gate_to_drop->uninstall(on_owner);
}
{
std::lock_guard lk{mu};
failed_start_incomplete = false;
phase = ShutdownPhase::stopped;
last_report = build_report_locked(true);
}
}
[[nodiscard]] Void::Result::Result<void> start_impl(StartOptions opts)
{
{
std::lock_guard lk{mu};
if (state != HostState::constructed) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_state,
"Host::start requires HostState::constructed")};
}
state = HostState::starting;
start_running = true;
owner_thread = std::this_thread::get_id();
start_options = std::move(opts);
signal_gate = start_options.signal_gate;
on_phase = start_options.on_phase;
}
struct StartGuard {
HostCore& self;
~StartGuard()
{
std::lock_guard lk{self.mu};
self.start_running = false;
self.cv.notify_all();
}
} start_guard{*this};
const auto fail_at = [&](StartStep step, Void::Result::Error err)
-> Void::Result::Result<void> {
{
std::lock_guard lk{mu};
state = HostState::failed_start;
ready = false;
}
const auto dl = Void::Time::deadline_after(
active_clock(), start_options.cleanup_timeout);
cleanup_after_start_failure(dl);
return std::unexpected{wrap_start_failure(step, std::move(err))};
};
const auto run_before_step = [&](StartStep step)
-> Void::Result::Result<void> {
if (start_options.before_step) {
return start_options.before_step(step);
}
return {};
};
// Step 1: signal_gate
if (auto sr = run_before_step(StartStep::signal_gate); !sr.has_value()) {
return fail_at(StartStep::signal_gate, std::move(sr.error()));
}
if (signal_gate != nullptr) {
auto gr = signal_gate->install();
if (!gr.has_value()) {
return fail_at(StartStep::signal_gate, std::move(gr.error()));
}
std::lock_guard lk{mu};
gate_installed = true;
}
// Step 2: memory_budget
if (auto sr = run_before_step(StartStep::memory_budget); !sr.has_value()) {
return fail_at(StartStep::memory_budget, std::move(sr.error()));
}
if (!options.embedded_mode) {
// Step 3: cpu_executor
if (auto sr = run_before_step(StartStep::cpu_executor); !sr.has_value()) {
return fail_at(StartStep::cpu_executor, std::move(sr.error()));
}
Async::ThreadExecutorOptions tex_opts;
tex_opts.workers = options.cpu_workers;
tex_opts.max_admitted = options.limits.max_cpu_tasks;
if (start_options.before_thread_start) {
tex_opts.before_worker_start =
[hook = start_options.before_thread_start](std::size_t idx) {
return hook(StartStep::cpu_executor, idx);
};
}
auto exec_res = Async::ThreadExecutor::create(std::move(tex_opts));
if (!exec_res.has_value()) {
return fail_at(StartStep::cpu_executor, std::move(exec_res.error()));
}
Async::ThreadExecutor* exec_raw = exec_res->get();
{
std::lock_guard lk{mu};
owned_executor = std::move(*exec_res);
}
if (auto st = exec_raw->start(); !st.has_value()) {
return fail_at(StartStep::cpu_executor, std::move(st.error()));
}
auto scope_local = std::make_unique<Async::TaskScope>(
*exec_raw,
Async::TaskScopeOptions{
.max_tasks = options.limits.max_cpu_tasks,
.stop_on_first_error = false,
},
active_clock());
{
std::lock_guard lk{mu};
business_scope = std::move(scope_local);
if (admission_closed) {
business_scope->close();
}
}
// Step 4: io_driver
if (auto sr = run_before_step(StartStep::io_driver); !sr.has_value()) {
return fail_at(StartStep::io_driver, std::move(sr.error()));
}
IO::BackendOptions io_opts = options.io;
io_opts.limits.file_workers = options.file_workers;
if (start_options.before_thread_start) {
io_opts.before_file_worker_start =
[hook = start_options.before_thread_start](std::size_t idx) {
return hook(StartStep::file_workers, idx);
};
}
auto drv_res = IO::Driver::create(
*exec_raw, std::move(io_opts), active_clock(), &active_budget());
if (!drv_res.has_value()) {
return fail_at(StartStep::io_driver, std::move(drv_res.error()));
}
IO::Driver* drv_raw = drv_res->get();
{
std::lock_guard lk{mu};
owned_driver = std::move(*drv_res);
}
// Step 5: file_workers
if (auto sr = run_before_step(StartStep::file_workers); !sr.has_value()) {
return fail_at(StartStep::file_workers, std::move(sr.error()));
}
if (auto fw = drv_raw->start_file_workers(); !fw.has_value()) {
return fail_at(StartStep::file_workers, std::move(fw.error()));
}
// Step 6: reactor
if (auto sr = run_before_step(StartStep::reactor); !sr.has_value()) {
return fail_at(StartStep::reactor, std::move(sr.error()));
}
if (start_options.before_thread_start) {
if (auto th = start_options.before_thread_start(
StartStep::reactor, 0);
!th.has_value()) {
return fail_at(StartStep::reactor, std::move(th.error()));
}
}
try {
reactor_thread = std::thread([this]() { run_reactor_loop(); });
} catch (const std::system_error& e) {
return fail_at(
StartStep::reactor,
make_runtime_error(RuntimeErrorCode::internal, e.what()));
}
{
std::lock_guard lk{mu};
started_workers = options.cpu_workers + options.file_workers + 1;
}
} else {
auto scope_local = std::make_unique<Async::TaskScope>(
*embedded.executor,
Async::TaskScopeOptions{
.max_tasks = options.limits.max_cpu_tasks,
.stop_on_first_error = false,
},
active_clock());
std::lock_guard lk{mu};
business_scope = std::move(scope_local);
if (admission_closed) {
business_scope->close();
}
}
// Step 7: components in startup_order (outside mu)
if (auto sr = run_before_step(StartStep::components); !sr.has_value()) {
return fail_at(StartStep::components, std::move(sr.error()));
}
if (!registered_components.empty()) {
HostContext ctx{
*active_executor(),
get_io(),
active_clock(),
active_budget(),
business_stop_source.get_token()};
for (const auto& id : plan.startup_order) {
std::shared_ptr<ComponentEntry> entry;
{
std::lock_guard lk{mu};
auto it = registered_components.find(id);
if (it != registered_components.end()) {
entry = it->second;
}
}
if (!entry) {
continue;
}
auto comp_res = entry->component->start(ctx);
if (!comp_res.has_value()) {
return fail_at(
StartStep::components, std::move(comp_res.error()));
}
{
std::lock_guard lk{mu};
entry->started = true;
started_component_ids.push_back(id);
}
}
}
// Step 8: readiness
if (auto sr = run_before_step(StartStep::readiness); !sr.has_value()) {
return fail_at(StartStep::readiness, std::move(sr.error()));
}
if (!options.embedded_mode) {
const auto dl = Void::Time::deadline_after(
active_clock(), start_options.readiness_timeout);
auto sig = std::make_shared<ProbeSignal>();
auto probe = make_readiness_probe(sig);
auto post_res = owned_executor->try_post(probe.handle);
if (!post_res.has_value()) {
probe.handle.destroy();
return fail_at(
StartStep::readiness,
Async::make_async_error(post_res.error()));
}
owned_driver->wake();
for (;;) {
bool probe_ok = false;
{
std::lock_guard lk{sig->mu};
probe_ok = sig->done;
}
const bool rx_ok =
reactor_turns.load(std::memory_order_acquire) >= 1;
if (probe_ok && rx_ok) {
break;
}
if (active_clock().now() >= dl) {
return fail_at(
StartStep::readiness,
make_runtime_error(
RuntimeErrorCode::shutdown_incomplete,
"Host readiness probe timed out"));
}
std::unique_lock lk{sig->mu};
sig->cv.wait_for(lk, std::chrono::milliseconds{1});
}
}
{
std::lock_guard lk{mu};
if (admission_closed || begin_shutdown_called) {
state = HostState::stopping_admission;
ready = false;
if (business_scope) {
business_scope->close();
}
} else {
state = HostState::running;
ready = true;
}
}
return {};
}
[[nodiscard]] std::expected<Async::JoinHandle, Async::AdmissionError>
spawn_impl(Coro::Task<void>&& task, Async::OperationOptions opts)
{
std::lock_guard lk{mu};
if (!business_scope || admission_closed ||
state != HostState::running) {
return std::unexpected{Async::AdmissionError::stopped};
}
return business_scope->spawn(std::move(task), std::move(opts));
}
void begin_shutdown_impl() noexcept
{
std::lock_guard lk{mu};
begin_shutdown_called = true;
admission_closed = true;
if (business_scope) {
business_scope->close();
}
if (state == HostState::running) {
state = HostState::stopping_admission;
ready = false;
}
}
[[nodiscard]] Void::Result::Result<ShutdownReport>
shutdown_blocking_impl(Async::OperationOptions opts, bool unbounded)
{
if (is_on_owned_worker_thread()) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::self_join,
"Host::shutdown_blocking called from an owned worker, reactor, or IO "
"worker thread")};
}
bool lacks_bg_workers = false;
{
std::lock_guard lk{mu};
if (auto* exec = active_executor();
exec != nullptr && !exec->has_background_workers()) {
lacks_bg_workers = true;
}
}
if (lacks_bg_workers) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"Host::shutdown_blocking requires background workers; use shutdown_pumping")};
}
return drive_shutdown(opts, nullptr, nullptr, /*allow_wait=*/true, unbounded);
}
[[nodiscard]] Void::Result::Result<ShutdownReport>
poll_shutdown_impl(Async::OperationOptions opts)
{
if (is_on_owned_worker_thread()) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::self_join,
"Host::poll_shutdown called from an owned worker thread")};
}
if (options.embedded_mode) {
if (auto* manual =
dynamic_cast<Async::ManualExecutor*>(embedded.executor)) {
return drive_shutdown(
opts, manual, nullptr, opts.deadline.has_value(), false);
}
}
return drive_shutdown(
opts, nullptr, nullptr, opts.deadline.has_value(), false);
}
[[nodiscard]] Void::Result::Result<ShutdownReport>
shutdown_pumping_impl(Async::ManualExecutor& manual,
Async::OperationOptions opts,
Async::TimerQueue* timers,
bool unbounded)
{
if (!options.embedded_mode || embedded.executor != &manual) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"Host::shutdown_pumping requires embedded mode with a matching ManualExecutor")};
}
return drive_shutdown(opts, &manual, timers, /*allow_wait=*/true, unbounded);
}
private:
[[nodiscard]] TimePoint compute_call_deadline(
const Async::OperationOptions& opts,
bool allow_wait,
bool unbounded) const noexcept
{
if (unbounded) {
return TimePoint::max();
}
if (!allow_wait && !opts.deadline.has_value()) {
return active_clock().now();
}
const auto policy_dl = Void::Time::deadline_after(
active_clock(), options.shutdown.total_timeout);
if (opts.deadline.has_value()) {
return std::min(*opts.deadline, policy_dl);
}
return policy_dl;
}
[[nodiscard]] Void::Result::Result<ShutdownReport> drive_shutdown(
Async::OperationOptions opts,
Async::ManualExecutor* manual,
Async::TimerQueue* timers,
bool allow_wait,
bool unbounded)
{
const TimePoint call_dl =
compute_call_deadline(opts, allow_wait, unbounded);
const bool single_drain_if_poll =
!allow_wait && !opts.deadline.has_value() && manual != nullptr;
{
std::unique_lock lk{mu};
if (start_running && owner_thread.has_value() &&
std::this_thread::get_id() == *owner_thread) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_state,
"Host shutdown cannot be called reentrantly from Host::start")};
}
while (start_running || shutdown_running) {
if (!unbounded && opts.stop.stop_requested()) {
return build_report_locked(false);
}
if (!unbounded && call_dl != TimePoint::max() &&
active_clock().now() >= call_dl) {
if (last_report.has_value()) {
return *last_report;
}
return build_report_locked(phase == ShutdownPhase::stopped);
}
cv.wait_for(lk, std::chrono::milliseconds{1});
}
if (phase == ShutdownPhase::stopped) {
if (owner_release_pending && gate_installed &&
signal_gate != nullptr &&
owner_thread.has_value() &&
std::this_thread::get_id() == *owner_thread) {
SignalGate* g = signal_gate;
gate_installed = false;
owner_release_pending = false;
lk.unlock();
g->uninstall(true);
lk.lock();
last_report = build_report_locked(true);
}
if (last_report.has_value()) {
return *last_report;
}
return build_report_locked(true);
}
shutdown_running = true;
}
struct TurnGuard {
HostCore& self;
~TurnGuard()
{
std::lock_guard lk{self.mu};
self.shutdown_running = false;
self.cv.notify_all();
}
} turn_guard{*this};
const auto return_incomplete = [&]() -> ShutdownReport {
std::lock_guard lk{mu};
state = HostState::shutdown_incomplete;
last_report = build_report_locked(false);
return *last_report;
};
const auto deadline_or_stop = [&]() -> bool {
if (!unbounded && opts.stop.stop_requested()) {
return true;
}
return call_dl != TimePoint::max() && active_clock().now() >= call_dl;
};
ShutdownPhase cur_phase{};
{
std::lock_guard lk{mu};
if (phase == ShutdownPhase::not_started) {
cur_phase = ShutdownPhase::closing_admission;
} else {
cur_phase = phase;
}
}
if (cur_phase == ShutdownPhase::closing_admission) {
emit_phase(ShutdownPhase::closing_admission);
}
for (;;) {
{
std::lock_guard lk{mu};
cur_phase = phase;
}
switch (cur_phase) {
case ShutdownPhase::not_started:
case ShutdownPhase::closing_admission: {
{
std::lock_guard lk{mu};
state = HostState::stopping_admission;
ready = false;
admission_closed = true;
if (business_scope) {
business_scope->close();
}
state = HostState::draining;
}
emit_phase(ShutdownPhase::draining);
break;
}
case ShutdownPhase::draining: {
TimePoint drain_dl{};
{
std::lock_guard lk{mu};
state = HostState::draining;
if (!drain_deadline.has_value()) {
drain_deadline = Void::Time::deadline_after(
active_clock(), options.shutdown.drain_grace);
}
drain_dl = *drain_deadline;
}
const auto eff_dl =
call_dl == TimePoint::max()
? drain_dl
: std::min(call_dl, drain_dl);
auto pred = [&]() {
return !business_scope ||
business_scope->active_count() == 0;
};
const bool ok =
manual != nullptr
? pump_wait(
*manual, pred, eff_dl, opts.stop, timers,
single_drain_if_poll)
: wait_until_clock(pred, eff_dl, opts.stop);
if (ok) {
emit_phase(ShutdownPhase::cancelling);
break;
}
if (active_clock().now() >= drain_dl) {
{
std::lock_guard lk{mu};
drain_grace_expired = true;
}
emit_phase(ShutdownPhase::cancelling);
break;
}
return return_incomplete();
}
case ShutdownPhase::cancelling: {
(void)business_stop_source.request_stop();
{
std::lock_guard lk{mu};
if (business_scope) {
(void)business_scope->request_stop();
}
state = HostState::joining;
}
emit_phase(ShutdownPhase::joining_business);
break;
}
case ShutdownPhase::joining_business: {
{
std::lock_guard lk{mu};
state = HostState::joining;
}
auto pred = [&]() {
return !business_scope ||
business_scope->active_count() == 0;
};
const bool ok =
manual != nullptr
? pump_wait(
*manual, pred, call_dl, opts.stop, timers,
single_drain_if_poll)
: wait_until_clock(pred, call_dl, opts.stop);
if (!ok) {
return return_incomplete();
}
emit_phase(ShutdownPhase::stopping_components);
break;
}
case ShutdownPhase::stopping_components: {
Async::Executor* exec = active_executor();
for (const auto& id : plan.shutdown_order) {
std::shared_ptr<ComponentEntry> entry;
{
std::lock_guard lk{mu};
auto it = registered_components.find(id);
if (it != registered_components.end()) {
entry = it->second;
}
}
if (!entry || !entry->started ||
entry->kind == ResourceKind::exporter) {
continue;
}
if (entry->stop_done.load(std::memory_order_acquire)) {
continue;
}
if (!entry->stop_launched && exec != nullptr) {
entry->stop_launched = true;
Async::OperationOptions stop_op{
.stop = opts.stop,
.deadline =
call_dl == TimePoint::max()
? std::nullopt
: std::optional<TimePoint>{call_dl}};
auto coro = run_component_stop(
entry->component, std::move(stop_op), entry);
exec->post_completion(coro.handle);
}
auto pred = [&]() {
return entry->stop_done.load(
std::memory_order_acquire);
};
const bool ok =
manual != nullptr
? pump_wait(
*manual, pred, call_dl, opts.stop, timers,
single_drain_if_poll)
: wait_component_entry(
entry, pred, call_dl, opts.stop);
if (!ok) {
return return_incomplete();
}
}
emit_phase(ShutdownPhase::flushing_exporters);
break;
}
case ShutdownPhase::flushing_exporters: {
TimePoint flush_dl{};
{
std::lock_guard lk{mu};
if (!flush_deadline.has_value()) {
flush_deadline = Void::Time::deadline_after(
active_clock(), options.shutdown.export_flush_timeout);
}
flush_dl = *flush_deadline;
}
Async::Executor* exec = active_executor();
std::vector<std::shared_ptr<ComponentEntry>> exporters;
for (const auto& id : plan.shutdown_order) {
std::shared_ptr<ComponentEntry> entry;
{
std::lock_guard lk{mu};
auto it = registered_components.find(id);
if (it != registered_components.end()) {
entry = it->second;
}
}
if (!entry || !entry->started ||
entry->kind != ResourceKind::exporter) {
continue;
}
exporters.push_back(entry);
if (!entry->stop_launched &&
!entry->stop_done.load(std::memory_order_acquire) &&
exec != nullptr) {
entry->stop_launched = true;
Async::OperationOptions exp_op{
.stop = exporter_stop_source.get_token(),
.deadline = flush_dl};
auto coro = run_component_stop(
entry->component, std::move(exp_op), entry);
exec->post_completion(coro.handle);
}
}
auto all_exporters_done = [&]() {
for (const auto& e : exporters) {
if (!e->stop_done.load(std::memory_order_acquire)) {
return false;
}
}
return true;
};
bool polled_once = false;
for (;;) {
if (all_exporters_done()) {
break;
}
bool flushed_expired_now = false;
{
std::lock_guard lk{mu};
if (active_clock().now() >= flush_dl &&
!export_flush_expired) {
export_flush_expired = true;
flushed_expired_now = true;
}
}
if (flushed_expired_now) {
(void)exporter_stop_source.request_stop();
}
if (single_drain_if_poll && !polled_once &&
manual != nullptr && !opts.stop.stop_requested()) {
polled_once = true;
(void)manual->drain();
if (all_exporters_done()) {
break;
}
}
if (deadline_or_stop()) {
return return_incomplete();
}
const TimePoint next_dl =
export_flush_expired
? call_dl
: (call_dl == TimePoint::max()
? flush_dl
: std::min(call_dl, flush_dl));
if (manual != nullptr) {
(void)pump_wait(
*manual,
all_exporters_done,
next_dl,
opts.stop,
timers,
single_drain_if_poll);
} else {
for (const auto& e : exporters) {
if (!e->stop_done.load(
std::memory_order_acquire)) {
(void)wait_component_entry(
e,
[&] {
return e->stop_done.load(
std::memory_order_acquire);
},
next_dl,
opts.stop);
break;
}
}
}
if (all_exporters_done()) {
break;
}
bool expired_after_wait = false;
{
std::lock_guard lk{mu};
if (active_clock().now() >= flush_dl &&
!export_flush_expired) {
export_flush_expired = true;
expired_after_wait = true;
}
}
if (expired_after_wait) {
(void)exporter_stop_source.request_stop();
}
if (deadline_or_stop()) {
return return_incomplete();
}
}
emit_phase(ShutdownPhase::releasing_components);
break;
}
case ShutdownPhase::releasing_components: {
std::unordered_map<std::string, std::shared_ptr<ComponentEntry>>
dropped;
{
std::lock_guard lk{mu};
dropped.swap(registered_components);
started_component_ids.clear();
}
for (auto& [k, c] : dropped) {
(void)k;
if (c) {
c->component.reset();
}
}
dropped.clear();
if (options.embedded_mode) {
emit_phase(ShutdownPhase::releasing);
} else {
emit_phase(ShutdownPhase::stopping_io);
}
break;
}
case ShutdownPhase::stopping_io: {
(void)reactor_stop_source.request_stop();
if (owned_driver) {
owned_driver->wake();
}
if (reactor_thread.joinable()) {
reactor_thread.join();
}
if (owned_driver && !owned_driver->shutdown_complete()) {
Async::OperationOptions io_op{.stop = opts.stop};
if (call_dl != TimePoint::max()) {
io_op.deadline = call_dl;
}
auto io_rep = owned_driver->shutdown(std::move(io_op));
if (!io_rep.has_value() || !io_rep->complete) {
const std::size_t file_workers_alive =
owned_driver->telemetry().file_workers_running;
std::lock_guard lk{mu};
started_workers =
(owned_executor ? options.cpu_workers : 0) +
file_workers_alive;
state = HostState::shutdown_incomplete;
last_report = build_report_locked(false);
return *last_report;
}
}
{
std::lock_guard lk{mu};
started_workers = options.cpu_workers;
}
emit_phase(ShutdownPhase::stopping_workers);
break;
}
case ShutdownPhase::stopping_workers: {
if (owned_executor) {
owned_executor->close();
if (!wait_until_clock(
[&]() { return owned_executor->idle(); },
call_dl,
opts.stop)) {
return return_incomplete();
}
(void)owned_executor->join();
}
{
std::lock_guard lk{mu};
started_workers = 0;
}
emit_phase(ShutdownPhase::releasing);
break;
}
case ShutdownPhase::releasing: {
SignalGate* gate_to_drop = nullptr;
{
std::lock_guard lk{mu};
business_scope.reset();
if (gate_installed && signal_gate != nullptr) {
const bool on_owner =
owner_thread.has_value() &&
std::this_thread::get_id() == *owner_thread;
if (on_owner) {
gate_to_drop = signal_gate;
gate_installed = false;
owner_release_pending = false;
} else {
owner_release_pending = true;
}
}
state = HostState::stopped;
ready = false;
failed_start_incomplete = false;
}
if (gate_to_drop != nullptr) {
gate_to_drop->uninstall(true);
}
emit_phase(ShutdownPhase::stopped);
{
std::lock_guard lk{mu};
last_report = build_report_locked(true);
return *last_report;
}
}
case ShutdownPhase::stopped: {
std::lock_guard lk{mu};
state = HostState::stopped;
ready = false;
last_report = build_report_locked(true);
return *last_report;
}
}
}
}
};
} // namespace Void::Runtime::detail