Files
Library/include/Void/Resilience/AsyncPolicy.hpp
T

713 lines
24 KiB
C++

#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Retry.hpp>
#include <Void/Resilience/Resilience.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <stop_token>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Resilience
{
struct BulkheadConfig {
std::size_t max_active{64};
std::size_t max_waiting{128};
std::size_t max_retained_bytes{8ULL * 1024ULL * 1024ULL};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (max_active == 0 || max_retained_bytes == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BulkheadConfig::max_active and max_retained_bytes must be positive"));
}
return {};
}
};
class Bulkhead;
namespace Detail
{
struct BulkheadState;
struct BulkheadAccess;
} // namespace Detail
class BulkheadPermit
{
public:
BulkheadPermit() noexcept = default;
~BulkheadPermit() noexcept { release(); }
BulkheadPermit(BulkheadPermit&& other) noexcept
: state_(std::move(other.state_))
, active_(std::exchange(other.active_, false))
{
}
BulkheadPermit& operator=(BulkheadPermit&& other) noexcept
{
if (this != &other) {
release();
state_ = std::move(other.state_);
active_ = std::exchange(other.active_, false);
}
return *this;
}
BulkheadPermit(const BulkheadPermit&) = delete;
BulkheadPermit& operator=(const BulkheadPermit&) = delete;
void release() noexcept;
[[nodiscard]] explicit operator bool() const noexcept { return active_; }
private:
friend class Bulkhead;
friend struct Detail::BulkheadState;
friend struct Detail::BulkheadAccess;
BulkheadPermit(std::shared_ptr<Detail::BulkheadState> state,
bool active) noexcept
: state_(std::move(state)), active_(active)
{
}
std::shared_ptr<Detail::BulkheadState> state_{};
bool active_{false};
};
namespace Detail
{
struct WaiterNode;
struct BulkheadState : std::enable_shared_from_this<BulkheadState> {
static constexpr std::size_t kWaiterFootprintBytes = 256;
BulkheadConfig config{};
const Void::Time::MonotonicClock* clock{nullptr};
std::mutex mutex{};
bool closed{false};
std::size_t active{0};
std::size_t retained_bytes{0};
std::deque<std::shared_ptr<WaiterNode>> waiters{};
std::uint64_t expired_evictions{0};
BulkheadState(BulkheadConfig cfg, const Void::Time::MonotonicClock* clk)
: config(cfg)
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
{
}
};
struct WaiterNode {
std::shared_ptr<Async::OperationState<BulkheadPermit>> op{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
std::atomic<bool> resolved{false};
struct StopHandler {
std::weak_ptr<BulkheadState> state;
std::weak_ptr<WaiterNode> node;
void operator()() const noexcept;
};
std::optional<std::stop_callback<StopHandler>> stop_cb{};
};
struct PendingSettlement {
std::shared_ptr<Async::OperationState<BulkheadPermit>> op;
bool granted{false};
ResilienceErrorCode err_code{ResilienceErrorCode::cancelled};
std::string message{};
};
struct BulkheadAccess {
[[nodiscard]] static BulkheadPermit make_permit(
std::shared_ptr<BulkheadState> state) noexcept
{
return BulkheadPermit{std::move(state), true};
}
};
inline void dispatch_settlements(const std::shared_ptr<BulkheadState>& state,
std::vector<PendingSettlement>& list) noexcept
{
for (auto& item : list) {
if (!item.op) {
continue;
}
if (item.granted) {
if (auto ticket = item.op->try_commit_value(
BulkheadAccess::make_permit(state));
ticket.has_value()) {
ticket->dispatch();
}
} else {
const auto kind =
item.err_code == ResilienceErrorCode::timeout
? Async::DomainOutcomeKind::failed
: Async::DomainOutcomeKind::cancelled;
if (auto ticket = item.op->try_commit_error(
make_resilience_error(item.err_code, std::move(item.message)),
kind);
ticket.has_value()) {
ticket->dispatch();
}
}
}
}
inline void evict_expired_locked(BulkheadState& st,
std::vector<PendingSettlement>& settlements)
{
const auto now = st.clock->now();
std::deque<std::shared_ptr<WaiterNode>> remaining;
while (!st.waiters.empty()) {
auto node = std::move(st.waiters.front());
st.waiters.pop_front();
if (node->resolved.load(std::memory_order_acquire)) {
continue;
}
const bool stopped = node->op->stop_requested();
const bool timed_out =
node->deadline.has_value() && now >= *node->deadline;
if (stopped || timed_out) {
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
st.retained_bytes =
st.retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st.retained_bytes - BulkheadState::kWaiterFootprintBytes)
: 0;
if (timed_out) {
++st.expired_evictions;
}
settlements.push_back(PendingSettlement{
node->op,
false,
timed_out ? ResilienceErrorCode::timeout
: ResilienceErrorCode::cancelled,
timed_out ? "Bulkhead waiter deadline expired"
: "Bulkhead waiter cancelled"});
}
} else {
remaining.push_back(std::move(node));
}
}
st.waiters = std::move(remaining);
}
inline void grant_available_locked(BulkheadState& st,
std::vector<PendingSettlement>& settlements)
{
while (!st.closed && st.active < st.config.max_active && !st.waiters.empty()) {
auto node = std::move(st.waiters.front());
st.waiters.pop_front();
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
st.retained_bytes =
st.retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st.retained_bytes - BulkheadState::kWaiterFootprintBytes)
: 0;
++st.active;
settlements.push_back(PendingSettlement{
node->op, true, ResilienceErrorCode::cancelled, {}});
}
}
}
inline void WaiterNode::StopHandler::operator()() const noexcept
{
auto st = state.lock();
auto nd = node.lock();
if (!st || !nd) {
return;
}
std::vector<PendingSettlement> settlements;
{
std::lock_guard lock{st->mutex};
if (!nd->resolved.exchange(true, std::memory_order_acq_rel)) {
for (auto it = st->waiters.begin(); it != st->waiters.end(); ++it) {
if (it->get() == nd.get()) {
st->waiters.erase(it);
st->retained_bytes =
st->retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st->retained_bytes -
BulkheadState::kWaiterFootprintBytes)
: 0;
break;
}
}
settlements.push_back(PendingSettlement{
nd->op,
false,
ResilienceErrorCode::cancelled,
"Bulkhead waiter cancelled"});
}
}
dispatch_settlements(st, settlements);
}
} // namespace Detail
inline void BulkheadPermit::release() noexcept
{
if (!state_ || !active_) {
return;
}
active_ = false;
auto st = std::move(state_);
std::vector<Detail::PendingSettlement> settlements;
{
std::lock_guard lock{st->mutex};
if (st->active > 0) {
--st->active;
}
Detail::evict_expired_locked(*st, settlements);
Detail::grant_available_locked(*st, settlements);
}
Detail::dispatch_settlements(st, settlements);
}
/// Asynchronous FIFO concurrency bulkhead with bounded active + waiting queue,
/// expired-waiter eviction before admission, stop cancellation, and graceful close().
class Bulkhead
{
public:
[[nodiscard]] static Void::Result::Result<Bulkhead> create(
BulkheadConfig config = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance())
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
return Bulkhead{std::make_shared<Detail::BulkheadState>(config, &clock)};
}
[[nodiscard]] Void::Result::Result<BulkheadPermit> try_acquire()
{
std::vector<Detail::PendingSettlement> settlements;
bool granted = false;
bool is_closed = false;
{
std::lock_guard lock{state_->mutex};
Detail::evict_expired_locked(*state_, settlements);
if (state_->closed) {
is_closed = true;
} else if (state_->waiters.empty() &&
state_->active < state_->config.max_active) {
++state_->active;
granted = true;
}
}
Detail::dispatch_settlements(state_, settlements);
if (is_closed) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::closed, "Bulkhead is closed"));
}
if (!granted) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::bulkhead_full,
"Bulkhead active concurrency limit reached"));
}
return BulkheadPermit{state_, true};
}
[[nodiscard]] Void::Coro::Task<Void::Result::Result<BulkheadPermit>>
acquire_async(Async::OperationOptions options = {},
Async::Executor* resume_exec = nullptr)
{
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Bulkhead acquisition cancelled before queueing"));
}
if (Async::is_deadline_expired(options, *state_->clock)) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Bulkhead acquisition deadline expired before queueing"));
}
std::vector<Detail::PendingSettlement> settlements;
std::shared_ptr<Detail::WaiterNode> node;
std::optional<Void::Result::Error> immediate_error;
bool immediate_grant = false;
{
std::lock_guard lock{state_->mutex};
Detail::evict_expired_locked(*state_, settlements);
if (state_->closed) {
immediate_error = make_resilience_error(
ResilienceErrorCode::closed, "Bulkhead is closed");
} else if (state_->waiters.empty() &&
state_->active < state_->config.max_active) {
++state_->active;
immediate_grant = true;
} else if (state_->waiters.size() >= state_->config.max_waiting ||
Detail::BulkheadState::kWaiterFootprintBytes >
state_->config.max_retained_bytes -
std::min(state_->retained_bytes,
state_->config.max_retained_bytes)) {
immediate_error = make_resilience_error(
ResilienceErrorCode::bulkhead_full,
"Bulkhead waiting queue full");
} else {
node = std::make_shared<Detail::WaiterNode>();
node->op = Async::OperationState<BulkheadPermit>::create(
options, resume_exec, Async::StopBehavior::notify_only);
node->deadline = options.deadline;
state_->retained_bytes += Detail::BulkheadState::kWaiterFootprintBytes;
state_->waiters.push_back(node);
if (options.stop.stop_possible()) {
node->stop_cb.emplace(
options.stop,
Detail::WaiterNode::StopHandler{state_, node});
}
}
}
Detail::dispatch_settlements(state_, settlements);
if (immediate_error.has_value()) {
co_return Void::Result::fail(std::move(*immediate_error));
}
if (immediate_grant) {
co_return BulkheadPermit{state_, true};
}
auto res = co_await node->op->awaitable(resume_exec);
node->stop_cb.reset();
co_return res;
}
std::size_t evict_expired()
{
std::vector<Detail::PendingSettlement> settlements;
std::size_t evicted = 0;
{
std::lock_guard lock{state_->mutex};
const auto before = state_->waiters.size();
Detail::evict_expired_locked(*state_, settlements);
Detail::grant_available_locked(*state_, settlements);
evicted = before >= state_->waiters.size()
? (before - state_->waiters.size())
: 0;
}
Detail::dispatch_settlements(state_, settlements);
return evicted;
}
void close()
{
std::vector<Detail::PendingSettlement> settlements;
{
std::lock_guard lock{state_->mutex};
state_->closed = true;
while (!state_->waiters.empty()) {
auto node = std::move(state_->waiters.front());
state_->waiters.pop_front();
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
state_->retained_bytes =
state_->retained_bytes >=
Detail::BulkheadState::kWaiterFootprintBytes
? (state_->retained_bytes -
Detail::BulkheadState::kWaiterFootprintBytes)
: 0;
settlements.push_back(Detail::PendingSettlement{
node->op,
false,
ResilienceErrorCode::closed,
"Bulkhead closed"});
}
}
}
Detail::dispatch_settlements(state_, settlements);
}
[[nodiscard]] std::size_t active_count() const
{
std::lock_guard lock{state_->mutex};
return state_->active;
}
[[nodiscard]] std::size_t waiting_count() const
{
std::lock_guard lock{state_->mutex};
return state_->waiters.size();
}
[[nodiscard]] std::size_t retained_bytes() const
{
std::lock_guard lock{state_->mutex};
return state_->retained_bytes;
}
[[nodiscard]] std::uint64_t expired_evictions() const
{
std::lock_guard lock{state_->mutex};
return state_->expired_evictions;
}
private:
explicit Bulkhead(std::shared_ptr<Detail::BulkheadState> state) noexcept
: state_(std::move(state))
{
}
std::shared_ptr<Detail::BulkheadState> state_;
};
// ── Composition & Retry Pipeline ─────────────────────────────────────────────
struct ResilientRetryConfig {
std::size_t max_attempts{3};
std::chrono::milliseconds base_delay{100};
std::chrono::milliseconds max_delay{2000};
Void::Retry::JitterMode jitter{Void::Retry::JitterMode::Full};
bool replay_safe{false};
std::optional<std::uint64_t> deterministic_seed{};
};
struct AttemptClassification {
Outcome outcome{Outcome::neutral};
bool retryable{false};
};
struct ResiliencePipeline {
TokenBucket* rate_limiter{nullptr};
double rate_cost{1.0};
Bulkhead* bulkhead{nullptr};
Breaker* breaker{nullptr};
ResilientRetryConfig retry{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
Observability::HookSlot* hooks{nullptr};
std::function<bool(std::chrono::nanoseconds, const Async::OperationOptions&)>
wait_fn{};
};
namespace Detail
{
template <typename T>
struct IsCoroTask : std::false_type {};
template <typename T>
struct IsCoroTask<Void::Coro::Task<T>> : std::true_type {};
template <typename T>
struct UnwrapTask {
using type = T;
};
template <typename T>
struct UnwrapTask<Void::Coro::Task<T>> {
using type = T;
};
[[nodiscard]] inline std::chrono::nanoseconds compute_jittered_backoff(
const ResilientRetryConfig& cfg,
std::size_t attempt,
std::optional<std::mt19937_64>& seeded_rng)
{
const Void::Retry::ExponentialBackoff backoff{cfg.base_delay, cfg.max_delay, 2.0};
const auto base = backoff.delay(attempt);
if (base.count() <= 0) {
return std::chrono::nanoseconds{0};
}
const long long base_ms = base.count();
const long long floor_ms =
(cfg.jitter == Void::Retry::JitterMode::Equal) ? (base_ms / 2) : 0;
std::uniform_int_distribution<long long> dist{0, base_ms - floor_ms};
long long drawn = 0;
if (seeded_rng.has_value()) {
drawn = dist(*seeded_rng);
} else {
thread_local std::mt19937_64 tls_rng{std::random_device{}()};
drawn = dist(tls_rng);
}
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::milliseconds{floor_ms + drawn});
}
[[nodiscard]] inline bool wait_with_stop(
std::chrono::nanoseconds delay,
const Async::OperationOptions& options,
const Void::Time::MonotonicClock& clock)
{
if (delay.count() <= 0) {
return !options.stop.stop_requested() &&
!Async::is_deadline_expired(options, clock);
}
const auto slice = std::chrono::milliseconds{5};
auto remaining = delay;
while (remaining.count() > 0) {
if (options.stop.stop_requested() ||
Async::is_deadline_expired(options, clock)) {
return false;
}
const auto step = std::min<std::chrono::nanoseconds>(remaining, slice);
std::this_thread::sleep_for(step);
remaining -= step;
}
return !options.stop.stop_requested() &&
!Async::is_deadline_expired(options, clock);
}
} // namespace Detail
/// Execute `fn` under bounded composition:
/// deadline/stop -> rate_limiter -> bulkhead -> breaker -> single attempt ->
/// classify -> release permits -> retry policy (only if replay_safe && retryable).
template <typename Fn, typename Classify>
[[nodiscard]] auto execute_resilient(
ResiliencePipeline pipeline,
Fn fn,
Classify classify,
Async::OperationOptions options = {},
Async::Executor* resume_exec = nullptr)
-> Void::Coro::Task<typename Detail::UnwrapTask<std::invoke_result_t<Fn>>::type>
{
using ResultType = typename Detail::UnwrapTask<std::invoke_result_t<Fn>>::type;
const auto& clock =
pipeline.clock != nullptr
? *pipeline.clock
: Void::Time::SystemMonotonicClock::instance();
if (pipeline.retry.max_attempts == 0) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"ResilientRetryConfig::max_attempts must be >= 1"));
}
std::optional<std::mt19937_64> seeded_rng;
if (pipeline.retry.deterministic_seed.has_value()) {
seeded_rng.emplace(*pipeline.retry.deterministic_seed);
}
ResultType last_result = Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument, "No resilience attempt ran"));
for (std::size_t attempt = 0; attempt < pipeline.retry.max_attempts; ++attempt) {
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Resilient operation stopped before attempt"));
}
if (Async::is_deadline_expired(options, clock)) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation deadline expired"));
}
if (pipeline.rate_limiter != nullptr) {
auto adm = pipeline.rate_limiter->try_acquire_at_checked(
clock.now(), pipeline.rate_cost);
if (!adm) {
co_return Void::Result::fail(std::move(adm).error());
}
if (!adm->allowed) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::rate_limited,
"Resilient operation rate-limited"));
}
}
std::optional<BulkheadPermit> bulkhead_permit;
if (pipeline.bulkhead != nullptr) {
auto bh = co_await pipeline.bulkhead->acquire_async(options, resume_exec);
if (!bh) {
co_return Void::Result::fail(std::move(bh).error());
}
bulkhead_permit = std::move(*bh);
}
std::optional<BreakerPermit> breaker_permit;
if (pipeline.breaker != nullptr) {
auto br = pipeline.breaker->acquire();
if (!br) {
co_return Void::Result::fail(std::move(br).error());
}
breaker_permit = std::move(*br);
}
if constexpr (Detail::IsCoroTask<std::invoke_result_t<Fn>>::value) {
last_result = co_await fn();
} else {
last_result = fn();
}
const AttemptClassification cls = classify(last_result);
if (breaker_permit.has_value()) {
breaker_permit->finish(cls.outcome);
breaker_permit.reset();
}
if (bulkhead_permit.has_value()) {
bulkhead_permit->release();
bulkhead_permit.reset();
}
if (last_result.has_value()) {
co_return last_result;
}
if (!pipeline.retry.replay_safe || !cls.retryable ||
attempt + 1 >= pipeline.retry.max_attempts) {
co_return last_result;
}
auto delay = Detail::compute_jittered_backoff(
pipeline.retry, attempt, seeded_rng);
if (options.deadline.has_value()) {
const auto now = clock.now();
if (now >= *options.deadline) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation total deadline expired before retry"));
}
const auto rem = *options.deadline - now;
if (delay > rem) {
delay = rem;
}
}
const bool slept_ok = pipeline.wait_fn
? pipeline.wait_fn(delay, options)
: Detail::wait_with_stop(delay, options, clock);
if (!slept_ok) {
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Resilient operation cancelled during retry backoff"));
}
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation timed out during retry backoff"));
}
}
co_return last_result;
}
} // namespace Void::Resilience