From 18a623aa62b5adea089acc8bb0281788c58e3486 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 10:06:35 +0300 Subject: [PATCH] feat(Resilience): add validated configs, RAII breaker/resource permits, bounded keyed cleanup, ResilienceAsync composition, and reserve P2 error domains (M-RESILIENCE-01..04) --- docs/agent-workflow/tasks/M-LOG-01-05.md | 2 +- .../tasks/M-RESILIENCE-01-04.md | 2 +- .../tasks/M-STACKTRACE-01-04.md | 2 +- .../tasks/S-OBSERVABILITY-01-04.md | 2 +- include/Void/Functional/Error.hpp | 9 +- include/Void/Resilience/AsyncPolicy.hpp | 712 ++++++++++++++++++ include/Void/Resilience/CircuitBreaker.hpp | 529 ++++++++++--- include/Void/Resilience/KeyedRateLimiter.hpp | 504 +++++++++---- include/Void/Resilience/RateLimiter.hpp | 393 ++++++++-- include/Void/Resilience/Resilience.hpp | 8 +- include/Void/Resilience/ResourceMonitor.hpp | 372 ++++++--- include/Void/Resilience/Types.hpp | 176 +++++ src/Resilience/module.cmake | 5 +- src/ResilienceAsync/module.cmake | 4 + tests/package/InstalledComponents.cmake | 5 + tests/package/ResilienceOnly/CMakeLists.txt | 10 + tests/package/ResilienceOnly/main.cpp | 22 + .../Resilience/ResilienceHardening.cpp | 272 +++++++ .../ResilienceAsync/AsyncPolicy.cpp | 252 +++++++ 19 files changed, 2854 insertions(+), 427 deletions(-) create mode 100644 include/Void/Resilience/AsyncPolicy.hpp create mode 100644 include/Void/Resilience/Types.hpp create mode 100644 src/ResilienceAsync/module.cmake create mode 100644 tests/package/ResilienceOnly/CMakeLists.txt create mode 100644 tests/package/ResilienceOnly/main.cpp create mode 100644 tests/standalone/Resilience/ResilienceHardening.cpp create mode 100644 tests/standalone/ResilienceAsync/AsyncPolicy.cpp diff --git a/docs/agent-workflow/tasks/M-LOG-01-05.md b/docs/agent-workflow/tasks/M-LOG-01-05.md index 0591ef5..6e09e2e 100644 --- a/docs/agent-workflow/tasks/M-LOG-01-05.md +++ b/docs/agent-workflow/tasks/M-LOG-01-05.md @@ -11,7 +11,7 @@ Contracts: C-01, C-02, C-03, C-04, C-05, C-11 - Split `LogConfig` (`src/LogConfig/module.cmake`, `FromConfig.hpp`/`src/LogConfig/FromConfig.cpp`) out of `Log` (`src/Log/module.cmake`: `INTERNAL_DEPS Async Core Data Functional Memory Time LogState`, `OPTIONAL_DEPS Stacktrace`, `EXCLUDE_HEADERS Void/Log/Log.hpp Void/Log/FromConfig.hpp`). - `include/Void/Log/Log.hpp` & `src/LogState/State.cpp`: immutable `SinkRegistration`, `register_sink`, `detach_and_drain` (`DrainResult` with `would_deadlock`), outer-of-lock callback invocation & owner destruction, reentrancy guard (depth <= 8) + emergency hook. - `include/Void/Log/Entry.hpp`: `bool truncated{false};`. -- `include/Void/Log/Logger.hpp` & `src/Log/Logger.cpp`: `LogErrorCode`, `make_log_error` (`kLogErrorDomain = 11`), `DeliveryLimits`, `FailurePolicy`, `LoggerOptions`, `SubmitState`, `Ticket`, `SubmitReceipt`, `FlushDurability`, `FlushOptions`, `CloseOptions`, `FlushReport`, bounded deque with queued+in-flight entry and byte accounting, contiguous ticket watermark, `try_submit`, `flush_through`, `close`, quarantine & reset, admission-barrier `set_mode`, `sync_files()`. +- `include/Void/Log/Logger.hpp` & `src/Log/Logger.cpp`: `LogErrorCode`, `make_log_error` (`kLogErrorDomain = 12`), `DeliveryLimits`, `FailurePolicy`, `LoggerOptions`, `SubmitState`, `Ticket`, `SubmitReceipt`, `FlushDurability`, `FlushOptions`, `CloseOptions`, `FlushReport`, bounded deque with queued+in-flight entry and byte accounting, contiguous ticket watermark, `try_submit`, `flush_through`, `close`, quarantine & reset, admission-barrier `set_mode`, `sync_files()`. - `include/Void/Log/Sinks.hpp`: `CallbackLogger(Callback, LoggerOptions)`, `MultiLogger::try_add` with max 8 children and cycle check. - `include/Void/Log/Formatter.hpp` & `src/Log/Formatter.cpp`: field redaction in `FieldFilter`, `LogfmtFormatter` control-char escaping, `JsonLinesFormatter` int64 line numbers, `format_bounded`. - `FileLogger` / `RotatingFileLogger` / `RollingFile`: explicit `create_directories`, `RotatingFileOptions::roadmap_defaults()`, stream write-error surfacing, `reopen()`, POSIX `::fsync` in `sync_files()`. diff --git a/docs/agent-workflow/tasks/M-RESILIENCE-01-04.md b/docs/agent-workflow/tasks/M-RESILIENCE-01-04.md index ee38041..7e5862b 100644 --- a/docs/agent-workflow/tasks/M-RESILIENCE-01-04.md +++ b/docs/agent-workflow/tasks/M-RESILIENCE-01-04.md @@ -10,7 +10,7 @@ Contracts: C-02, C-03, C-04, C-05, C-11, C-13 ## 2. Deliverables - `src/Resilience/module.cmake` (`INTERNAL_DEPS Functional Time ObservabilityHooks`, `EXCLUDE_HEADERS Void/Resilience/AsyncPolicy.hpp`) - `src/ResilienceAsync/module.cmake` (`INTERNAL_DEPS Resilience Async Functional Time ObservabilityHooks`, `EXTRA_HEADERS Void/Resilience/AsyncPolicy.hpp`) -- `include/Void/Resilience/Types.hpp`: `ResilienceErrorCode`, `make_resilience_error` (`kResilienceErrorDomain = 14`), `Outcome`, `Admission`, validated `BucketConfig`, `KeyedBucketConfig`, `BreakerConfig`, `MonitorConfig` +- `include/Void/Resilience/Types.hpp`: `ResilienceErrorCode`, `make_resilience_error` (`kResilienceErrorDomain = 15`), `Outcome`, `Admission`, validated `BucketConfig`, `KeyedBucketConfig`, `BreakerConfig`, `MonitorConfig` - Upgrades in `RateLimiter.hpp`, `KeyedRateLimiter.hpp`, `CircuitBreaker.hpp`, `ResourceMonitor.hpp`, `Resilience.hpp` (`TokenBucket::create`/`try_acquire_checked`/`try_acquire_all`, `BoundedKeyedRateLimiter`, `Breaker`/`BreakerPermit`, overflow-safe `ResourceMonitor`/`ResourcePermit`) - `include/Void/Resilience/AsyncPolicy.hpp`: `BulkheadConfig`, `Bulkhead`, `BulkheadPermit`, `ResilientRetryConfig` (using `Void::Retry::ExponentialBackoff` + `JitterMode::Full`), `execute_resilient` - `tests/standalone/Resilience/ResilienceHardening.cpp`, `tests/standalone/ResilienceAsync/AsyncPolicy.cpp` diff --git a/docs/agent-workflow/tasks/M-STACKTRACE-01-04.md b/docs/agent-workflow/tasks/M-STACKTRACE-01-04.md index e308e49..43c1f18 100644 --- a/docs/agent-workflow/tasks/M-STACKTRACE-01-04.md +++ b/docs/agent-workflow/tasks/M-STACKTRACE-01-04.md @@ -11,7 +11,7 @@ Contracts: C-01, C-02, C-03, C-04, C-05 - `src/Stacktrace/module.cmake`: add `Time` (`INTERNAL_DEPS Functional Time LogState`) - `include/Void/Stacktrace/Stacktrace.hpp` & `src/Stacktrace/Stacktrace.cpp`: - Legacy `StackFrame`, `capture_stacktrace`, `read_source_snippet`, `format_stacktrace`, `print_stacktrace` preserved. - - `kStacktraceErrorDomain = 12` `StacktraceErrorCode` + `make_stacktrace_error`. + - `kStacktraceErrorDomain = 13` `StacktraceErrorCode` + `make_stacktrace_error`. - `Capabilities` (`raw_capture`, `symbols`, `line_info`, `async_signal_safe = false`, `backend_name`) + `capabilities() noexcept`. - `CaptureOptions`, owned `RawFrame` (`address`, `module_offset`, `module_path`, `module_id`), `RawTrace`, `capture()` (validates `1 <= max_frames <= 256`, zero source IO, zero `Void::Log` calls). - `FrameResolveStatus`, `ResolvedFrame`, `ResolvedTrace`, `ResolveOptions`, `Resolver` (bounded `1024` entries / `4 MiB` cache keyed by `(module_id, module_offset)`, `invalidate_module`, `clear_cache`), `read_source_snippet_checked` (allowed roots, symlink-escape rejection, overflow-safe line math, byte limits), `format_resolved_trace`, `write_fatal_signal_marker(int fd, int sig) noexcept`. diff --git a/docs/agent-workflow/tasks/S-OBSERVABILITY-01-04.md b/docs/agent-workflow/tasks/S-OBSERVABILITY-01-04.md index 33ae20f..cd27e9c 100644 --- a/docs/agent-workflow/tasks/S-OBSERVABILITY-01-04.md +++ b/docs/agent-workflow/tasks/S-OBSERVABILITY-01-04.md @@ -11,7 +11,7 @@ Contracts: C-01, C-02, C-03, C-04, C-05 - `src/ObservabilityHooks/module.cmake` (header-only `Void/Observability/Hooks.hpp`, zero deps) - `src/Observability/module.cmake` (`INTERNAL_DEPS ObservabilityHooks Core Functional Time Memory`, `EXCLUDE_HEADERS Void/Observability/Hooks.hpp`) - `include/Void/Observability/Hooks.hpp`: `MetricKind`, `AttributeView`, `MetricPoint`, `DiagnosticEvent`, `ObservationHooks`, `kNullObservationHooks`, `DrainStatus`, `HookRegistrationId`, `HookLease`, `HookSlot` -- `include/Void/Observability/Context.hpp`: `ObservabilityErrorCode`, `make_observability_error` (`kObservabilityErrorDomain = 13`), `TraceId`, `SpanId`, `TraceContext`, `ContextLimits`, `ContextSnapshot`, `ScopedContext` +- `include/Void/Observability/Context.hpp`: `ObservabilityErrorCode`, `make_observability_error` (`kObservabilityErrorDomain = 14`), `TraceId`, `SpanId`, `TraceContext`, `ContextLimits`, `ContextSnapshot`, `ScopedContext` - `include/Void/Observability/AsyncContext.hpp`: `bind_context`, `ContextAwaitable` (no `#include `) - `include/Void/Observability/Metrics.hpp` & `src/Observability/Metrics.cpp`: `MetricsLimits`, `InstrumentSpec`, `InstrumentHandle`, `HistogramSnapshot`, `SeriesSnapshot`, `MetricsSnapshot`, `MetricRegistry` - `include/Void/Observability/Tracing.hpp` & `src/Observability/Tracing.cpp`: `TracingLimits`, `SpanStatus`, `SpanSpec`, `SpanEvent`, `CompletedSpan`, `ExportBatch`, `ExportReport`, `ExportOptions`, `Span`, `SpanExporter`, `CallbackSpanExporter`, `TextSnapshotExporter`, `Tracer` diff --git a/include/Void/Functional/Error.hpp b/include/Void/Functional/Error.hpp index e0c78ce..7578df5 100644 --- a/include/Void/Functional/Error.hpp +++ b/include/Void/Functional/Error.hpp @@ -60,10 +60,11 @@ namespace Void::Result inline constexpr std::uint32_t kIoErrorDomain = 8; inline constexpr std::uint32_t kStorageErrorDomain = 9; inline constexpr std::uint32_t kSystemErrorDomain = 10; - inline constexpr std::uint32_t kLogErrorDomain = 11; - inline constexpr std::uint32_t kStacktraceErrorDomain = 12; - inline constexpr std::uint32_t kObservabilityErrorDomain = 13; - inline constexpr std::uint32_t kResilienceErrorDomain = 14; + inline constexpr std::uint32_t kRuntimeErrorDomain = 11; + inline constexpr std::uint32_t kLogErrorDomain = 12; + inline constexpr std::uint32_t kStacktraceErrorDomain = 13; + inline constexpr std::uint32_t kObservabilityErrorDomain = 14; + inline constexpr std::uint32_t kResilienceErrorDomain = 15; struct ErrorCode { std::uint32_t domain{kGenericErrorDomain}; diff --git a/include/Void/Resilience/AsyncPolicy.hpp b/include/Void/Resilience/AsyncPolicy.hpp new file mode 100644 index 0000000..8872a32 --- /dev/null +++ b/include/Void/Resilience/AsyncPolicy.hpp @@ -0,0 +1,712 @@ +#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::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 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 state, + bool active) noexcept + : state_(std::move(state)), active_(active) + { + } + + std::shared_ptr state_{}; + bool active_{false}; +}; + +namespace Detail +{ + +struct WaiterNode; + +struct BulkheadState : std::enable_shared_from_this { + 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> 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> op{}; + std::optional deadline{}; + std::atomic resolved{false}; + + struct StopHandler { + std::weak_ptr state; + std::weak_ptr node; + + void operator()() const noexcept; + }; + + std::optional> stop_cb{}; +}; + +struct PendingSettlement { + std::shared_ptr> op; + bool granted{false}; + ResilienceErrorCode err_code{ResilienceErrorCode::cancelled}; + std::string message{}; +}; + +struct BulkheadAccess { + [[nodiscard]] static BulkheadPermit make_permit( + std::shared_ptr state) noexcept + { + return BulkheadPermit{std::move(state), true}; + } +}; + +inline void dispatch_settlements(const std::shared_ptr& state, + std::vector& 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& settlements) +{ + const auto now = st.clock->now(); + std::deque> 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& 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 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 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 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(config, &clock)}; + } + + [[nodiscard]] Void::Result::Result try_acquire() + { + std::vector 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> + 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 settlements; + std::shared_ptr node; + std::optional 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(); + node->op = Async::OperationState::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 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 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 state) noexcept + : state_(std::move(state)) + { + } + + std::shared_ptr 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 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 + wait_fn{}; +}; + +namespace Detail +{ + +template +struct IsCoroTask : std::false_type {}; + +template +struct IsCoroTask> : std::true_type {}; + +template +struct UnwrapTask { + using type = T; +}; + +template +struct UnwrapTask> { + using type = T; +}; + +[[nodiscard]] inline std::chrono::nanoseconds compute_jittered_backoff( + const ResilientRetryConfig& cfg, + std::size_t attempt, + std::optional& 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 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::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(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 +[[nodiscard]] auto execute_resilient( + ResiliencePipeline pipeline, + Fn fn, + Classify classify, + Async::OperationOptions options = {}, + Async::Executor* resume_exec = nullptr) + -> Void::Coro::Task>::type> +{ + using ResultType = typename Detail::UnwrapTask>::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 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 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 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>::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 diff --git a/include/Void/Resilience/CircuitBreaker.hpp b/include/Void/Resilience/CircuitBreaker.hpp index 729b874..5d87794 100644 --- a/include/Void/Resilience/CircuitBreaker.hpp +++ b/include/Void/Resilience/CircuitBreaker.hpp @@ -1,140 +1,449 @@ #pragma once +#include +#include + #include #include #include +#include #include +#include #include #include +#include #include namespace Void::Resilience { - // ── CircuitBreaker - // ──────────────────────────────────────────────────────────── A - // three-state breaker that stops hammering a failing dependency. - // - // Closed calls flow; `failure_threshold` consecutive failures trip it - // Open. Open calls are rejected until `cooldown` elapses, then one - // probe is let - // through (HalfOpen). - // HalfOpen `success_threshold` probe successes close it; any failure - // re-opens. - // - // Use allow()/record_success()/record_failure() to gate work directly, or - // execute() to wrap a std::expected-returning step. Thread-safe; clock - // injectable for deterministic tests. +// ── CircuitBreaker (legacy compatibility) ──────────────────────────────────── - template - concept HasHasValue = requires(const R& r) { - { r.has_value() } -> std::convertible_to; - }; +template +concept HasHasValue = requires(const R& r) { + { r.has_value() } -> std::convertible_to; +}; - class CircuitBreaker - { - public: +class CircuitBreaker +{ +public: + enum class State { Closed, Open, HalfOpen }; - enum class State { Closed, Open, HalfOpen }; + using Clock = std::function; + using Duration = std::chrono::steady_clock::duration; + using TimePoint = std::chrono::steady_clock::time_point; - using Clock = - std::function; - using Duration = std::chrono::steady_clock::duration; - using TimePoint = std::chrono::steady_clock::time_point; + CircuitBreaker(std::size_t failure_threshold, + Duration cooldown, + std::size_t success_threshold = 1, + Clock clock = default_clock()) + : failure_threshold_{failure_threshold > 0 ? failure_threshold : 1} + , cooldown_{cooldown.count() >= 0 ? cooldown : Duration::zero()} + , success_threshold_{success_threshold > 0 ? success_threshold : 1} + , clock_{std::move(clock)} + { + } - CircuitBreaker(std::size_t failure_threshold, Duration cooldown, - std::size_t success_threshold = 1, - Clock clock = default_clock()) - : failure_threshold_{failure_threshold}, cooldown_{cooldown}, - success_threshold_{success_threshold}, - clock_{std::move(clock)} - { - } + [[nodiscard]] bool allow() + { + std::lock_guard lock{mu_}; + if (state_ == State::Open) { + const auto now = clock_(); + if (now >= opened_at_ && now - opened_at_ >= cooldown_) { + state_ = State::HalfOpen; + successes_ = 0; + } + } + return state_ != State::Open; + } - // Whether a call may proceed now. Transitions Open -> HalfOpen once - // the cooldown has elapsed (admitting a probe). - [[nodiscard]] bool allow() - { - std::lock_guard lock{mu_}; - if (state_ == State::Open && - clock_() - opened_at_ >= cooldown_) { - state_ = State::HalfOpen; - successes_ = 0; - } - return state_ != State::Open; - } + void record_success() + { + std::lock_guard lock{mu_}; + if (state_ == State::HalfOpen) { + if (++successes_ >= success_threshold_) { + state_ = State::Closed; + failures_ = 0; + } + } else { + failures_ = 0; + } + } - void record_success() - { - std::lock_guard lock{mu_}; - if (state_ == State::HalfOpen) { - if (++successes_ >= success_threshold_) { - state_ = State::Closed; - failures_ = 0; - } - } else { - failures_ = 0; - } - } + void record_failure() + { + std::lock_guard lock{mu_}; + if (state_ == State::HalfOpen) { + trip(); + } else if (++failures_ >= failure_threshold_) { + trip(); + } + } - void record_failure() - { - std::lock_guard lock{mu_}; - if (state_ == State::HalfOpen) { - trip(); - } else if (++failures_ >= failure_threshold_) { - trip(); - } - } + [[nodiscard]] State state() + { + std::lock_guard lock{mu_}; + return state_; + } - [[nodiscard]] State state() - { - std::lock_guard lock{mu_}; - return state_; - } + template + requires HasHasValue> + auto execute(F&& fn) -> std::optional> + { + if (!allow()) { + return std::nullopt; + } + auto result = std::forward(fn)(); + if (result.has_value()) { + record_success(); + } else { + record_failure(); + } + return result; + } - // Gate a std::expected-returning callable. Returns nullopt when the - // circuit rejects the call; otherwise runs it, records the outcome, - // and returns its result. - template - requires HasHasValue> - auto execute(F&& fn) -> std::optional> - { - if (!allow()) { - return std::nullopt; - } - auto result = std::forward(fn)(); - if (result.has_value()) { - record_success(); - } else { - record_failure(); - } - return result; - } +private: + static Clock default_clock() + { + return [] { return std::chrono::steady_clock::now(); }; + } - private: + void trip() + { + state_ = State::Open; + opened_at_ = clock_(); + } - static Clock default_clock() - { - return [] { return std::chrono::steady_clock::now(); }; - } + std::size_t failure_threshold_; + Duration cooldown_; + std::size_t success_threshold_; + Clock clock_; - void trip() - { - state_ = State::Open; - opened_at_ = clock_(); - } + State state_ = State::Closed; + std::size_t failures_ = 0; + std::size_t successes_ = 0; + TimePoint opened_at_{}; + std::mutex mu_; +}; - std::size_t failure_threshold_; - Duration cooldown_; - std::size_t success_threshold_; - Clock clock_; +// ── P2 Generation-bound Breaker & RAII BreakerPermit ───────────────────────── - State state_ = State::Closed; - std::size_t failures_ = 0; - std::size_t successes_ = 0; - TimePoint opened_at_{}; - std::mutex mu_; - }; +enum class BreakerState : std::uint8_t { + closed = 0, + open, + half_open +}; + +using BreakerStateCallback = std::function; + +class Breaker; + +namespace Detail +{ + +struct BreakerSharedState { + BreakerConfig config{}; + const Void::Time::MonotonicClock* clock{nullptr}; + Observability::HookSlot* hooks{nullptr}; + + std::mutex mu{}; + BreakerState state{BreakerState::closed}; + std::uint64_t generation{1}; + std::size_t failures{0}; + std::size_t half_open_in_flight{0}; + std::size_t half_open_successes{0}; + std::uint64_t observer_errors{0}; + Void::Time::MonotonicClock::time_point opened_at{}; + BreakerStateCallback on_state_change{}; + + BreakerSharedState(BreakerConfig cfg, + const Void::Time::MonotonicClock* clk, + Observability::HookSlot* h) + : config(std::move(cfg)) + , clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance()) + , hooks(h) + { + } + + void emit_transition(const BreakerStateCallback& cb, + BreakerState old_st, + BreakerState new_st, + std::uint64_t gen) noexcept + { + if (cb) { + try { + cb(old_st, new_st, gen); + } catch (...) { + std::lock_guard lock{mu}; + ++observer_errors; + } + } + if (hooks != nullptr && !config.metric_name.empty()) { + const char* label = + new_st == BreakerState::closed ? "closed" + : new_st == BreakerState::half_open ? "half_open" + : "open"; + const Observability::AttributeView attrs[] = {{"state", label}}; + hooks->invoke_metric(Observability::MetricPoint{ + .name = config.metric_name, + .kind = Observability::MetricKind::counter, + .integer_delta = 1, + .attributes = attrs}); + } + } + + void complete(std::uint64_t permit_gen, bool is_probe, Outcome outcome) noexcept + { + BreakerStateCallback cb; + bool transitioned = false; + BreakerState old_st = BreakerState::closed; + BreakerState new_st = BreakerState::closed; + std::uint64_t new_gen = 0; + + { + std::lock_guard lock{mu}; + if (is_probe && permit_gen == generation && half_open_in_flight > 0) { + --half_open_in_flight; + } + if (permit_gen != generation) { + return; + } + if (outcome == Outcome::neutral) { + return; + } + + if (state == BreakerState::half_open) { + if (outcome == Outcome::success) { + if (++half_open_successes >= config.success_threshold) { + old_st = BreakerState::half_open; + new_st = BreakerState::closed; + state = BreakerState::closed; + failures = 0; + half_open_successes = 0; + half_open_in_flight = 0; + new_gen = ++generation; + transitioned = true; + cb = on_state_change; + } + } else { + old_st = BreakerState::half_open; + new_st = BreakerState::open; + state = BreakerState::open; + opened_at = clock->now(); + half_open_successes = 0; + half_open_in_flight = 0; + new_gen = ++generation; + transitioned = true; + cb = on_state_change; + } + } else if (state == BreakerState::closed) { + if (outcome == Outcome::success) { + failures = 0; + } else if (++failures >= config.failure_threshold) { + old_st = BreakerState::closed; + new_st = BreakerState::open; + state = BreakerState::open; + opened_at = clock->now(); + new_gen = ++generation; + transitioned = true; + cb = on_state_change; + } + } + } + + if (transitioned) { + emit_transition(cb, old_st, new_st, new_gen); + } + } +}; + +} // namespace Detail + +class BreakerPermit +{ +public: + BreakerPermit() noexcept = default; + + ~BreakerPermit() noexcept + { + if (state_ && !finished_) { + finish(Outcome::neutral); + } + } + + BreakerPermit(BreakerPermit&& other) noexcept + : state_(std::move(other.state_)) + , generation_(other.generation_) + , is_probe_(other.is_probe_) + , finished_(std::exchange(other.finished_, true)) + { + } + + BreakerPermit& operator=(BreakerPermit&& other) noexcept + { + if (this != &other) { + if (state_ && !finished_) { + finish(Outcome::neutral); + } + state_ = std::move(other.state_); + generation_ = other.generation_; + is_probe_ = other.is_probe_; + finished_ = std::exchange(other.finished_, true); + } + return *this; + } + + BreakerPermit(const BreakerPermit&) = delete; + BreakerPermit& operator=(const BreakerPermit&) = delete; + + void finish(Outcome outcome) noexcept + { + if (!state_ || finished_) { + return; + } + finished_ = true; + auto st = std::move(state_); + st->complete(generation_, is_probe_, outcome); + } + + [[nodiscard]] std::uint64_t generation() const noexcept + { + return generation_; + } + + [[nodiscard]] bool is_probe() const noexcept { return is_probe_; } + + [[nodiscard]] bool active() const noexcept + { + return state_ != nullptr && !finished_; + } + +private: + friend class Breaker; + + BreakerPermit(std::shared_ptr state, + std::uint64_t generation, + bool is_probe) noexcept + : state_(std::move(state)) + , generation_(generation) + , is_probe_(is_probe) + , finished_(false) + { + } + + std::shared_ptr state_{}; + std::uint64_t generation_{0}; + bool is_probe_{false}; + bool finished_{true}; +}; + +class Breaker +{ +public: + [[nodiscard]] static Void::Result::Result create( + BreakerConfig config = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + Observability::HookSlot* hooks = nullptr) + { + if (auto v = config.validate(); !v) { + return Void::Result::fail(std::move(v).error()); + } + auto st = std::make_shared( + std::move(config), &clock, hooks); + return Breaker{std::move(st)}; + } + + [[nodiscard]] Void::Result::Result acquire() + { + BreakerStateCallback cb; + bool transitioned = false; + std::uint64_t new_gen = 0; + std::uint64_t permit_gen = 0; + bool is_probe = false; + bool admitted = false; + + { + std::lock_guard lock{state_->mu}; + const auto now = state_->clock->now(); + if (state_->state == BreakerState::open) { + if (now >= state_->opened_at && + now - state_->opened_at >= state_->config.cooldown) { + state_->state = BreakerState::half_open; + state_->half_open_in_flight = 0; + state_->half_open_successes = 0; + new_gen = ++state_->generation; + transitioned = true; + cb = state_->on_state_change; + } + } + + if (state_->state == BreakerState::half_open) { + if (state_->half_open_in_flight < + state_->config.half_open_max_probes) { + ++state_->half_open_in_flight; + permit_gen = state_->generation; + is_probe = true; + admitted = true; + } + } else if (state_->state == BreakerState::closed) { + permit_gen = state_->generation; + is_probe = false; + admitted = true; + } + } + + if (transitioned) { + state_->emit_transition( + cb, BreakerState::open, BreakerState::half_open, new_gen); + } + + if (!admitted) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::circuit_open, + "Circuit breaker rejected acquisition")); + } + return BreakerPermit{state_, permit_gen, is_probe}; + } + + void on_state_change(BreakerStateCallback callback) + { + std::lock_guard lock{state_->mu}; + state_->on_state_change = std::move(callback); + } + + [[nodiscard]] BreakerState state() const + { + std::lock_guard lock{state_->mu}; + return state_->state; + } + + [[nodiscard]] std::uint64_t generation() const + { + std::lock_guard lock{state_->mu}; + return state_->generation; + } + + [[nodiscard]] std::size_t half_open_in_flight() const + { + std::lock_guard lock{state_->mu}; + return state_->half_open_in_flight; + } + + [[nodiscard]] std::uint64_t observer_errors() const + { + std::lock_guard lock{state_->mu}; + return state_->observer_errors; + } + +private: + explicit Breaker(std::shared_ptr state) noexcept + : state_(std::move(state)) + { + } + + std::shared_ptr state_; +}; } // namespace Void::Resilience diff --git a/include/Void/Resilience/KeyedRateLimiter.hpp b/include/Void/Resilience/KeyedRateLimiter.hpp index b336728..a698225 100644 --- a/include/Void/Resilience/KeyedRateLimiter.hpp +++ b/include/Void/Resilience/KeyedRateLimiter.hpp @@ -1,166 +1,408 @@ #pragma once +#include #include +#include #include +#include +#include #include +#include #include #include #include #include +#include +#include #include #include +#include namespace Void::Resilience { - // ── KeyedRateLimiter ─────────────────────────────────────────────── - // A rate limiter that maintains an independent TokenBucket per distinct - // Key. Every key shares the same capacity + refill rate; buckets are - // created lazily on first use and can be reclaimed with cleanup(). Thread- - // safe. Generic over the key type (e.g. a client id, IP, or user name). +// ── KeyedRateLimiter ──────────────────────────────────────────────────── +// Preserved compatibility rate limiter maintaining an independent TokenBucket +// per key. Use BoundedKeyedRateLimiter for new policy code requiring validated +// limits, bounded incremental cursor cleanup, and encoded key size bounds. - template > - class KeyedRateLimiter - { - public: +template > +class KeyedRateLimiter +{ +public: + using Clock = TokenBucket::Clock; + using TimePoint = TokenBucket::TimePoint; - using Clock = TokenBucket::Clock; - using TimePoint = TokenBucket::TimePoint; + explicit KeyedRateLimiter(double capacity, + double refill_per_sec, + Clock clock = default_clock(), + std::size_t max_keys = 0) + : capacity_{capacity} + , rate_{refill_per_sec} + , clock_{std::move(clock)} + , max_keys_{max_keys} + { + if (max_keys_ > 0) { + map_.reserve(max_keys_); + } + } - // `capacity` is the burst size; `refill_per_sec` the sustained - // rate. `max_keys == 0` keeps the historic unbounded behaviour. - // Otherwise new keys are rejected at capacity until cleanup/reset - // frees space. The clock is shared with every bucket so tests stay - // deterministic. - explicit KeyedRateLimiter(double capacity, double refill_per_sec, - Clock clock = default_clock(), - std::size_t max_keys = 0) - : capacity_{capacity}, rate_{refill_per_sec}, - clock_{std::move(clock)}, max_keys_{max_keys} - { - if (max_keys_ > 0) { - map_.reserve(max_keys_); - } - } + [[nodiscard]] bool allow(const Key& key, double tokens = 1.0) + { + return allow_at(key, clock_(), tokens); + } - // Consume `tokens` for `key`. Returns false (without consuming) - // when the key's bucket is exhausted. - [[nodiscard]] bool allow(const Key& key, double tokens = 1.0) - { - return allow_at(key, clock_(), tokens); - } + [[nodiscard]] bool allow_at(const Key& key, TimePoint now, double tokens = 1.0) + { + if (!std::isfinite(tokens) || tokens < 0.0 || tokens > capacity_) { + return false; + } + std::lock_guard lock{mu_}; + Entry* value = entry(key, now); + return value != nullptr && value->bucket->try_acquire_at(now, tokens); + } - [[nodiscard]] bool allow_at(const Key& key, TimePoint now, - double tokens = 1.0) - { - std::lock_guard lock{mu_}; - Entry* value = entry(key, now); - return value != nullptr && - value->bucket->try_acquire_at(now, tokens); - } + [[nodiscard]] double remaining(const Key& key) + { + return remaining_at(key, clock_()).value_or(0.0); + } - // Tokens currently available to `key` (creates the bucket if new). - [[nodiscard]] double remaining(const Key& key) - { - return remaining_at(key, clock_()).value_or(0.0); - } + [[nodiscard]] std::optional remaining_at(const Key& key, TimePoint now) + { + std::lock_guard lock{mu_}; + Entry* value = entry(key, now); + if (value == nullptr) { + return std::nullopt; + } + return value->bucket->available_at(now); + } - // A missing optional means the key could not be created because the - // configured key cap is full. - [[nodiscard]] std::optional remaining_at(const Key& key, - TimePoint now) - { - std::lock_guard lock{mu_}; - Entry* value = entry(key, now); - if (value == nullptr) { - return std::nullopt; - } - return value->bucket->available_at(now); - } + void reset(const Key& key) + { + std::lock_guard lock{mu_}; + map_.erase(key); + } - // Forget a key's bucket (its next use starts full). - void reset(const Key& key) - { - std::lock_guard lock{mu_}; - map_.erase(key); - } + void reset() + { + std::lock_guard lock{mu_}; + map_.clear(); + } - void reset() - { - std::lock_guard lock{mu_}; - map_.clear(); - } + std::size_t cleanup(std::chrono::steady_clock::duration max_age) + { + return cleanup_at(clock_(), max_age); + } - // Drop buckets not touched within `max_age`. Returns how many were - // removed. Call periodically to bound memory for churny key spaces. - std::size_t cleanup(std::chrono::steady_clock::duration max_age) - { - return cleanup_at(clock_(), max_age); - } + std::size_t cleanup_at(TimePoint now, + std::chrono::steady_clock::duration max_age) + { + std::lock_guard lock{mu_}; + std::size_t removed = 0; + for (auto it = map_.begin(); it != map_.end();) { + if (now >= it->second.last_seen && + now - it->second.last_seen >= max_age) { + it = map_.erase(it); + ++removed; + } else { + ++it; + } + } + return removed; + } - std::size_t cleanup_at(TimePoint now, - std::chrono::steady_clock::duration max_age) - { - std::lock_guard lock{mu_}; - std::size_t removed = 0; - for (auto it = map_.begin(); it != map_.end();) { - if (now >= it->second.last_seen && - now - it->second.last_seen >= max_age) { - it = map_.erase(it); - ++removed; - } else { - ++it; - } - } - return removed; - } + [[nodiscard]] std::size_t tracked() const + { + std::lock_guard lock{mu_}; + return map_.size(); + } - // Number of keys currently tracked. - [[nodiscard]] std::size_t tracked() const - { - std::lock_guard lock{mu_}; - return map_.size(); - } +private: + static Clock default_clock() + { + return [] { return std::chrono::steady_clock::now(); }; + } - private: + struct Entry { + std::unique_ptr bucket; + std::chrono::steady_clock::time_point last_seen; + }; - static Clock default_clock() - { - return [] { return std::chrono::steady_clock::now(); }; - } + Entry* entry(const Key& key, TimePoint now) + { + auto it = map_.find(key); + if (it == map_.end()) { + if (max_keys_ > 0 && map_.size() >= max_keys_) { + return nullptr; + } + it = map_.emplace(key, + Entry{std::make_unique( + capacity_, rate_, clock_), + now}) + .first; + } else { + if (now > it->second.last_seen) { + it->second.last_seen = now; + } + } + return &it->second; + } - struct Entry { - // TokenBucket owns a std::mutex (non-movable), so hold it - // by pointer to keep Entry movable for the hash map. - std::unique_ptr bucket; - std::chrono::steady_clock::time_point last_seen; - }; + double capacity_; + double rate_; + Clock clock_; + std::size_t max_keys_; + mutable std::mutex mu_; + std::unordered_map map_; +}; - Entry* entry(const Key& key, TimePoint now) - { - auto it = map_.find(key); - if (it == map_.end()) { - if (max_keys_ > 0 && map_.size() >= max_keys_) { - return nullptr; - } - it = map_.emplace(key, - Entry{std::make_unique( - capacity_, rate_, clock_), - now}) - .first; - } else { - it->second.last_seen = now; - } - return &it->second; - } +namespace Detail +{ - double capacity_; - double rate_; - Clock clock_; - std::size_t max_keys_; - mutable std::mutex mu_; - std::unordered_map map_; - }; +template +[[nodiscard]] inline std::size_t encoded_key_size(const Key& key) noexcept +{ + if constexpr (std::convertible_to) { + return std::string_view{key}.size(); + } else { + return sizeof(Key); + } +} + +} // namespace Detail + +/// Bounded per-key rate limiter with key length caps, zero live-key eviction on +/// cap pressure, non-regressing token refill, and O(batch_limit) cursor cleanup. +template > +class BoundedKeyedRateLimiter +{ +public: + using TimePoint = std::chrono::steady_clock::time_point; + + [[nodiscard]] static Void::Result::Result create( + KeyedBucketConfig config = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + Observability::HookSlot* hooks = nullptr) + { + if (auto v = config.validate(); !v) { + return Void::Result::fail(std::move(v).error()); + } + auto state = std::make_shared(config, &clock, hooks); + return BoundedKeyedRateLimiter{std::move(state)}; + } + + [[nodiscard]] Void::Result::Result + admit(const Key& key, double cost = 1.0) + { + return admit_at(key, state_->clock->now(), cost); + } + + [[nodiscard]] Void::Result::Result + admit_at(const Key& key, TimePoint now, double cost = 1.0) + { + if (Detail::encoded_key_size(key) > state_->config.max_key_bytes) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::key_too_large, + "Rate-limiter key exceeds max_key_bytes")); + } + if (!std::isfinite(cost) || cost <= 0.0 || cost > state_->config.capacity) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "Cost must be finite, positive, and <= capacity")); + } + + Admission adm{}; + bool cap_rejected = false; + { + std::lock_guard lock{state_->mu}; + auto it = state_->entries.find(key); + if (it == state_->entries.end()) { + if (state_->entries.size() >= state_->config.max_keys) { + ++state_->rejected_new_keys; + cap_rejected = true; + } else { + Entry created{}; + created.tokens = state_->config.capacity; + created.last_refill = now; + created.last_seen = now; + it = state_->entries.emplace(key, created).first; + state_->cursor_keys.push_back(key); + } + } else { + if (now > it->second.last_seen) { + it->second.last_seen = now; + } + } + + if (!cap_rejected) { + auto& entry = it->second; + if (now > entry.last_refill) { + const std::chrono::duration elapsed = + now - entry.last_refill; + entry.last_refill = now; + entry.tokens = std::min( + state_->config.capacity, + entry.tokens + + elapsed.count() * state_->config.refill_per_second); + } + if (entry.tokens >= cost) { + entry.tokens -= cost; + adm = Admission{true, std::chrono::nanoseconds{0}}; + } else { + adm = Admission{ + false, + compute_retry_after(cost - entry.tokens)}; + } + } else { + adm = Admission{false, std::chrono::nanoseconds{0}}; + } + } + + // Never emit raw user keys as metric labels. + emit_metric(cap_rejected ? "cap_rejected" + : (adm.allowed ? "allowed" : "rejected")); + return adm; + } + + std::size_t cleanup_step() + { + return cleanup_step_at(state_->clock->now()); + } + + std::size_t cleanup_step_at(TimePoint now) + { + std::lock_guard lock{state_->mu}; + if (state_->cursor_keys.empty()) { + state_->cursor_idx = 0; + return 0; + } + const std::size_t scan_budget = std::min( + state_->config.cleanup_batch_limit, state_->cursor_keys.size()); + std::size_t scanned = 0; + std::size_t removed = 0; + while (scanned < scan_budget && !state_->cursor_keys.empty()) { + if (state_->cursor_idx >= state_->cursor_keys.size()) { + state_->cursor_idx = 0; + } + ++scanned; + const Key& k = state_->cursor_keys[state_->cursor_idx]; + auto it = state_->entries.find(k); + if (it == state_->entries.end()) { + swap_remove_cursor(state_->cursor_idx); + continue; + } + if (now >= it->second.last_seen && + now - it->second.last_seen >= state_->config.idle_retention) { + state_->entries.erase(it); + swap_remove_cursor(state_->cursor_idx); + ++removed; + } else { + ++state_->cursor_idx; + } + } + return removed; + } + + [[nodiscard]] std::size_t tracked() const + { + std::lock_guard lock{state_->mu}; + return state_->entries.size(); + } + + [[nodiscard]] std::uint64_t rejected_new_keys() const + { + std::lock_guard lock{state_->mu}; + return state_->rejected_new_keys; + } + + void reset(const Key& key) + { + std::lock_guard lock{state_->mu}; + state_->entries.erase(key); + } + + void reset() + { + std::lock_guard lock{state_->mu}; + state_->entries.clear(); + state_->cursor_keys.clear(); + state_->cursor_idx = 0; + } + +private: + struct Entry { + double tokens{0.0}; + TimePoint last_refill{}; + TimePoint last_seen{}; + }; + + struct State { + KeyedBucketConfig config; + const Void::Time::MonotonicClock* clock; + Observability::HookSlot* hooks; + std::mutex mu; + std::unordered_map entries; + std::vector cursor_keys; + std::size_t cursor_idx{0}; + std::uint64_t rejected_new_keys{0}; + + State(KeyedBucketConfig cfg, + const Void::Time::MonotonicClock* clk, + Observability::HookSlot* h) + : config(std::move(cfg)) + , clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance()) + , hooks(h) + { + entries.reserve(std::min(config.max_keys, 1024)); + } + }; + + explicit BoundedKeyedRateLimiter(std::shared_ptr st) noexcept + : state_(std::move(st)) + { + } + + [[nodiscard]] std::chrono::nanoseconds + compute_retry_after(double deficit) const noexcept + { + if (deficit <= 0.0) { + return std::chrono::nanoseconds{0}; + } + if (state_->config.refill_per_second <= 0.0) { + return std::chrono::nanoseconds::max(); + } + const double sec = deficit / state_->config.refill_per_second; + if (!std::isfinite(sec) || sec * 1e9 >= 9.0e18) { + return std::chrono::nanoseconds::max(); + } + const auto ns = static_cast(std::ceil(sec * 1e9)); + return std::chrono::nanoseconds{std::max(1, ns)}; + } + + void swap_remove_cursor(std::size_t idx) + { + if (idx + 1 < state_->cursor_keys.size()) { + state_->cursor_keys[idx] = std::move(state_->cursor_keys.back()); + } + state_->cursor_keys.pop_back(); + } + + void emit_metric(std::string_view outcome) noexcept + { + if (state_->hooks == nullptr || state_->config.metric_name.empty()) { + return; + } + const Observability::AttributeView attrs[] = {{"outcome", outcome}}; + state_->hooks->invoke_metric(Observability::MetricPoint{ + .name = state_->config.metric_name, + .kind = Observability::MetricKind::counter, + .integer_delta = 1, + .attributes = attrs}); + } + + std::shared_ptr state_; +}; } // namespace Void::Resilience diff --git a/include/Void/Resilience/RateLimiter.hpp b/include/Void/Resilience/RateLimiter.hpp index 82706ab..bf97397 100644 --- a/include/Void/Resilience/RateLimiter.hpp +++ b/include/Void/Resilience/RateLimiter.hpp @@ -1,108 +1,341 @@ #pragma once +#include +#include + #include #include +#include +#include #include +#include +#include #include +#include +#include #include +#include namespace Void::Resilience { - // ── TokenBucket - // ─────────────────────────────────────────────────────────────── A - // token-bucket rate limiter. The bucket holds up to `capacity` tokens and - // refills continuously at `refill_per_sec` tokens per second. - // try_acquire(n) consumes n tokens when available. Thread-safe; the clock - // is injectable so the refill behaviour is deterministic in tests. +// ── TokenBucket ────────────────────────────────────────────────────────────── +// A token-bucket rate limiter holding up to `capacity` tokens and refilling +// continuously at `refill_per_sec` tokens per second. +// Thread-safe; backed by stationary shared state so checked Admission queries, +// atomic multi-bucket acquisition, and legacy constructors share one model. - class TokenBucket - { - public: +class TokenBucket +{ +public: + using Clock = std::function; + using TimePoint = std::chrono::steady_clock::time_point; - using Clock = - std::function; - using TimePoint = std::chrono::steady_clock::time_point; + TokenBucket(double capacity, + double refill_per_sec, + Clock clock = default_clock()) + : state_(std::make_shared( + std::isfinite(capacity) && capacity > 0.0 ? capacity : 0.0, + std::isfinite(refill_per_sec) && refill_per_sec >= 0.0 + ? refill_per_sec + : 0.0, + std::move(clock), + nullptr, + nullptr, + std::string{})) + { + } - TokenBucket(double capacity, double refill_per_sec, - Clock clock = default_clock()) - : capacity_{capacity}, rate_{refill_per_sec}, tokens_{capacity}, - clock_{std::move(clock)}, last_{clock_()} - { - } + [[nodiscard]] static Void::Result::Result create( + BucketConfig config, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + Observability::HookSlot* hooks = nullptr) + { + if (auto v = config.validate(); !v) { + return Void::Result::fail(std::move(v).error()); + } + auto state = std::make_shared( + config.capacity, + config.refill_per_second, + Clock{}, + &clock, + hooks, + std::move(config.metric_name)); + return TokenBucket{std::move(state)}; + } - // Consume `tokens` if the bucket (after refilling for elapsed time) - // holds at least that many. Returns false without consuming - // anything otherwise. - [[nodiscard]] bool try_acquire(double tokens = 1.0) - { - std::lock_guard lock{mu_}; - refill(clock_()); - return try_acquire_locked(tokens); - } + // Legacy consume `tokens` if available; returns false without consuming on + // shortfall or invalid cost. + [[nodiscard]] bool try_acquire(double tokens = 1.0) + { + return try_acquire_at(state_->now(), tokens); + } - // Explicit-time variant for callers that need a single - // deterministic clock value across several coordinated buckets. - [[nodiscard]] bool try_acquire_at(TimePoint now, - double tokens = 1.0) - { - std::lock_guard lock{mu_}; - refill(now); - return try_acquire_locked(tokens); - } + [[nodiscard]] bool try_acquire_at(TimePoint now, double tokens = 1.0) + { + if (!std::isfinite(tokens) || tokens < 0.0 || + tokens > state_->capacity || state_->capacity <= 0.0) { + return false; + } + std::lock_guard lock{state_->mu}; + state_->refill_locked(now); + if (state_->tokens >= tokens) { + state_->tokens -= tokens; + return true; + } + return false; + } - // Current token count after refilling for elapsed time. - [[nodiscard]] double available() { return available_at(clock_()); } + // Validated P2 admission returning retry_after on shortfall and rejecting + // invalid (NaN/Inf/non-positive/oversize) costs cleanly. + [[nodiscard]] Void::Result::Result + try_acquire_checked(double cost = 1.0) + { + return try_acquire_at_checked(state_->now(), cost); + } - [[nodiscard]] double available_at(TimePoint now) - { - std::lock_guard lock{mu_}; - refill(now); - return tokens_; - } + [[nodiscard]] Void::Result::Result + try_acquire_at_checked(TimePoint now, double cost = 1.0) + { + if (!std::isfinite(cost) || cost <= 0.0 || cost > state_->capacity) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "Token cost must be finite, positive, and <= bucket capacity")); + } - void reset() { reset_at(clock_()); } + Admission adm{}; + { + std::lock_guard lock{state_->mu}; + state_->refill_locked(now); + adm = state_->try_acquire_locked(cost); + } + emit_metric(adm.allowed); + return adm; + } - void reset_at(TimePoint now) - { - std::lock_guard lock{mu_}; - tokens_ = capacity_; - last_ = now; - } + [[nodiscard]] double available() + { + return available_at(state_->now()); + } - [[nodiscard]] double capacity() const noexcept { return capacity_; } + [[nodiscard]] double available_at(TimePoint now) + { + std::lock_guard lock{state_->mu}; + state_->refill_locked(now); + return state_->tokens; + } - private: + void reset() { reset_at(state_->now()); } - [[nodiscard]] bool try_acquire_locked(double tokens) - { - if (tokens_ >= tokens) { - tokens_ -= tokens; - return true; - } - return false; - } + void reset_at(TimePoint now) + { + std::lock_guard lock{state_->mu}; + state_->tokens = state_->capacity; + if (now > state_->last) { + state_->last = now; + } + } - static Clock default_clock() - { - return [] { return std::chrono::steady_clock::now(); }; - } + [[nodiscard]] double capacity() const noexcept + { + return state_->capacity; + } - void refill(TimePoint now) - { - const std::chrono::duration elapsed = - now > last_ ? now - last_ : TimePoint::duration::zero(); - last_ = now; - tokens_ = - std::min(capacity_, tokens_ + elapsed.count() * rate_); - } + [[nodiscard]] double refill_per_second() const noexcept + { + return state_->rate; + } - double capacity_; - double rate_; - double tokens_; - Clock clock_; - TimePoint last_; - std::mutex mu_; - }; + // Atomically reserves tokens across all specified buckets or leaves every + // bucket untouched on first denial or invalid cost. + [[nodiscard]] static Void::Result::Result try_acquire_all_at( + TimePoint now, + std::span> requests) + { + for (const auto& [bucket, cost] : requests) { + if (bucket == nullptr || !std::isfinite(cost) || cost <= 0.0 || + cost > bucket->state_->capacity) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "Invalid bucket or cost in try_acquire_all_at")); + } + } + if (requests.empty()) { + return Admission{true, std::chrono::nanoseconds{0}}; + } + + std::vector lock_order; + lock_order.reserve(requests.size()); + for (const auto& [bucket, cost] : requests) { + (void)cost; + lock_order.push_back(bucket->state_.get()); + } + std::sort(lock_order.begin(), lock_order.end()); + lock_order.erase(std::unique(lock_order.begin(), lock_order.end()), + lock_order.end()); + + std::vector> locks; + locks.reserve(lock_order.size()); + for (auto* st : lock_order) { + locks.emplace_back(st->mu); + st->refill_locked(now); + } + + std::vector needed; + needed.assign(lock_order.size(), 0.0); + for (const auto& [bucket, cost] : requests) { + const auto pos = static_cast(std::distance( + lock_order.begin(), + std::lower_bound(lock_order.begin(), lock_order.end(), + bucket->state_.get()))); + needed[pos] += cost; + if (needed[pos] > lock_order[pos]->capacity) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "Combined cost exceeds bucket capacity")); + } + } + + std::chrono::nanoseconds max_wait{0}; + bool all_ok = true; + for (std::size_t i = 0; i < lock_order.size(); ++i) { + auto* st = lock_order[i]; + if (st->tokens < needed[i]) { + all_ok = false; + const auto wait = st->compute_retry_after_locked(needed[i] - st->tokens); + if (wait > max_wait) { + max_wait = wait; + } + } + } + + if (all_ok) { + for (std::size_t i = 0; i < lock_order.size(); ++i) { + lock_order[i]->tokens -= needed[i]; + } + } + locks.clear(); + + for (const auto& [bucket, cost] : requests) { + (void)cost; + bucket->emit_metric(all_ok); + } + return Admission{all_ok, all_ok ? std::chrono::nanoseconds{0} : max_wait}; + } + + [[nodiscard]] static Void::Result::Result try_acquire_all( + std::span> requests, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) + { + return try_acquire_all_at(clock.now(), requests); + } + +private: + struct State { + double capacity{0.0}; + double rate{0.0}; + double tokens{0.0}; + Clock clock_fn{}; + const Void::Time::MonotonicClock* clock_ptr{nullptr}; + Observability::HookSlot* hooks{nullptr}; + std::string metric_name{}; + TimePoint last{}; + std::mutex mu{}; + + State(double cap, + double r, + Clock clk_fn, + const Void::Time::MonotonicClock* clk_ptr, + Observability::HookSlot* h, + std::string mname) + : capacity(cap) + , rate(r) + , tokens(cap) + , clock_fn(std::move(clk_fn)) + , clock_ptr(clk_ptr) + , hooks(h) + , metric_name(std::move(mname)) + , last(now()) + { + } + + [[nodiscard]] TimePoint now() const + { + if (clock_ptr != nullptr) { + return clock_ptr->now(); + } + if (clock_fn) { + return clock_fn(); + } + return std::chrono::steady_clock::now(); + } + + void refill_locked(TimePoint now_tp) + { + // Clock moving backwards must never reset `last` backward or grant + // extra credits on recovery. + if (now_tp <= last) { + return; + } + const std::chrono::duration elapsed = now_tp - last; + last = now_tp; + tokens = std::min(capacity, tokens + elapsed.count() * rate); + } + + [[nodiscard]] std::chrono::nanoseconds + compute_retry_after_locked(double deficit) const noexcept + { + if (deficit <= 0.0) { + return std::chrono::nanoseconds{0}; + } + if (rate <= 0.0) { + return std::chrono::nanoseconds::max(); + } + const double sec = deficit / rate; + if (!std::isfinite(sec) || sec * 1e9 >= 9.0e18) { + return std::chrono::nanoseconds::max(); + } + const auto ns = static_cast(std::ceil(sec * 1e9)); + return std::chrono::nanoseconds{std::max(1, ns)}; + } + + [[nodiscard]] Admission try_acquire_locked(double cost) noexcept + { + if (tokens >= cost) { + tokens -= cost; + return Admission{true, std::chrono::nanoseconds{0}}; + } + return Admission{false, compute_retry_after_locked(cost - tokens)}; + } + }; + + explicit TokenBucket(std::shared_ptr st) noexcept + : state_(std::move(st)) + { + } + + static Clock default_clock() + { + return [] { return std::chrono::steady_clock::now(); }; + } + + void emit_metric(bool allowed) noexcept + { + if (state_->hooks == nullptr || state_->metric_name.empty()) { + return; + } + const Observability::AttributeView attrs[] = { + {"outcome", allowed ? "allowed" : "rejected"}}; + state_->hooks->invoke_metric(Observability::MetricPoint{ + .name = state_->metric_name, + .kind = Observability::MetricKind::counter, + .integer_delta = 1, + .attributes = attrs}); + } + + std::shared_ptr state_; +}; } // namespace Void::Resilience diff --git a/include/Void/Resilience/Resilience.hpp b/include/Void/Resilience/Resilience.hpp index f31ba9b..53936a5 100644 --- a/include/Void/Resilience/Resilience.hpp +++ b/include/Void/Resilience/Resilience.hpp @@ -1,10 +1,12 @@ #pragma once -// Umbrella header for the Resilience module: rate limiting, circuit breaking, -// and resource monitoring. These complement Functional/Retry.hpp (retry with -// backoff) rather than replacing it. +// Umbrella header for synchronous Resilience primitives: validated configs, +// rate limiting, circuit breaking, and resource monitoring. For optional Async +// bulkhead + retry composition, link Void::ResilienceAsync and include +// . #include #include #include #include +#include diff --git a/include/Void/Resilience/ResourceMonitor.hpp b/include/Void/Resilience/ResourceMonitor.hpp index 02d3e2e..8f87b28 100644 --- a/include/Void/Resilience/ResourceMonitor.hpp +++ b/include/Void/Resilience/ResourceMonitor.hpp @@ -1,117 +1,301 @@ #pragma once +#include + +#include +#include #include #include +#include #include #include namespace Void::Resilience { - // ── ResourceMonitor - // ─────────────────────────────────────────────────────────── Tracks usage - // of a bounded resource (memory budget, in-flight requests, queue depth, - // ...) against a limit, with hysteresis watermark callbacks. - // - // try_acquire() refuses to exceed the limit. Crossing the high watermark - // upward fires on_high_watermark once; dropping back to the low watermark - // fires on_low_watermark once (the gap prevents callback flapping). - // Callbacks run outside the internal lock. +class ResourceMonitor; - class ResourceMonitor - { - public: +namespace Detail +{ - using Callback = std::function; +struct MonitorState { + using Callback = std::function; - // high/low are fractions of `limit` in [0, 1]; high should exceed - // low. - explicit ResourceMonitor(std::uint64_t limit, double high = 0.9, - double low = 0.7) - : limit_{limit}, high_{static_cast( - static_cast(limit) * high)}, - low_{static_cast(static_cast(limit) * - low)} - { - } + std::uint64_t limit{0}; + std::uint64_t high{0}; + std::uint64_t low{0}; + std::uint64_t usage{0}; + bool alarmed{false}; + std::uint64_t observer_errors{0}; + Callback on_high{}; + Callback on_low{}; + mutable std::mutex mu{}; - void on_high_watermark(Callback cb) { on_high_ = std::move(cb); } - void on_low_watermark(Callback cb) { on_low_ = std::move(cb); } + MonitorState(std::uint64_t lim, std::uint64_t hi, std::uint64_t lo) noexcept + : limit(lim), high(hi), low(lo) + { + } - // Reserve `amount`. Returns false (reserving nothing) if it would - // exceed the limit. May fire the high-watermark callback when - // crossing upward. - [[nodiscard]] bool try_acquire(std::uint64_t amount = 1) - { - Callback fire; - std::uint64_t at = 0; - { - std::lock_guard lock{mu_}; - if (usage_ + amount > limit_) { - return false; - } - usage_ += amount; - if (!alarmed_ && usage_ >= high_) { - alarmed_ = true; - fire = on_high_; - at = usage_; - } - } - if (fire) { - fire(at); - } - return true; - } + void invoke_callback(const Callback& cb, std::uint64_t at) noexcept + { + if (!cb) { + return; + } + try { + cb(at); + } catch (...) { + std::lock_guard lock{mu}; + ++observer_errors; + } + } - // Release `amount` (clamped at zero). May fire the low-watermark - // callback when dropping back through the low threshold. - void release(std::uint64_t amount = 1) - { - Callback fire; - std::uint64_t at = 0; - { - std::lock_guard lock{mu_}; - usage_ = (amount >= usage_) ? 0 : usage_ - amount; - if (alarmed_ && usage_ <= low_) { - alarmed_ = false; - fire = on_low_; - at = usage_; - } - } - if (fire) { - fire(at); - } - } + void release_amount(std::uint64_t amount, bool clamp) noexcept + { + Callback fire; + std::uint64_t at = 0; + { + std::lock_guard lock{mu}; + if (amount >= usage) { + usage = clamp ? 0 : (usage - std::min(usage, amount)); + } else { + usage -= amount; + } + if (alarmed && usage <= low) { + alarmed = false; + fire = on_low; + at = usage; + } + } + invoke_callback(fire, at); + } +}; - [[nodiscard]] std::uint64_t usage() const - { - std::lock_guard lock{mu_}; - return usage_; - } +} // namespace Detail - [[nodiscard]] std::uint64_t limit() const noexcept - { - return limit_; - } +class ResourcePermit +{ +public: + ResourcePermit() noexcept = default; - [[nodiscard]] double utilization() const - { - std::lock_guard lock{mu_}; - return limit_ == 0 ? 0.0 - : static_cast(usage_) / - static_cast(limit_); - } + ~ResourcePermit() noexcept { release(); } - private: + ResourcePermit(ResourcePermit&& other) noexcept + : state_(std::move(other.state_)) + , amount_(std::exchange(other.amount_, 0)) + { + } - std::uint64_t limit_; - std::uint64_t high_; - std::uint64_t low_; - std::uint64_t usage_ = 0; - bool alarmed_ = false; - Callback on_high_; - Callback on_low_; - mutable std::mutex mu_; - }; + ResourcePermit& operator=(ResourcePermit&& other) noexcept + { + if (this != &other) { + release(); + state_ = std::move(other.state_); + amount_ = std::exchange(other.amount_, 0); + } + return *this; + } + + ResourcePermit(const ResourcePermit&) = delete; + ResourcePermit& operator=(const ResourcePermit&) = delete; + + void release() noexcept + { + if (!state_ || amount_ == 0) { + return; + } + const auto amt = std::exchange(amount_, 0); + auto st = std::move(state_); + st->release_amount(amt, false); + } + + [[nodiscard]] std::uint64_t amount() const noexcept { return amount_; } + [[nodiscard]] bool active() const noexcept + { + return state_ != nullptr && amount_ > 0; + } + +private: + friend class ResourceMonitor; + + ResourcePermit(std::shared_ptr state, + std::uint64_t amount) noexcept + : state_(std::move(state)), amount_(amount) + { + } + + std::shared_ptr state_{}; + std::uint64_t amount_{0}; +}; + +// ── ResourceMonitor ────────────────────────────────────────────────────────── +// Tracks usage of a bounded resource against a limit, with synchronized +// watermark callbacks executed outside the internal mutex. + +class ResourceMonitor +{ +public: + using Callback = std::function; + + explicit ResourceMonitor(std::uint64_t limit, + double high = 0.9, + double low = 0.7) + : state_(std::make_shared( + limit, + clamp_fraction(limit, high, 0.9), + clamp_fraction(limit, low, 0.7))) + { + } + + [[nodiscard]] static Void::Result::Result create( + MonitorConfig config) + { + if (auto v = config.validate(); !v) { + return Void::Result::fail(std::move(v).error()); + } + const auto hi = clamp_fraction(config.limit, config.high_fraction, 0.9); + const auto lo = std::min(hi, clamp_fraction(config.limit, config.low_fraction, 0.7)); + return ResourceMonitor{ + std::make_shared(config.limit, hi, lo)}; + } + + void on_high_watermark(Callback cb) + { + std::lock_guard lock{state_->mu}; + state_->on_high = std::move(cb); + } + + void on_low_watermark(Callback cb) + { + std::lock_guard lock{state_->mu}; + state_->on_low = std::move(cb); + } + + [[nodiscard]] bool try_acquire(std::uint64_t amount = 1) + { + Callback fire; + std::uint64_t at = 0; + { + std::lock_guard lock{state_->mu}; + if (amount > state_->limit - state_->usage) { + return false; + } + state_->usage += amount; + if (!state_->alarmed && state_->usage >= state_->high) { + state_->alarmed = true; + fire = state_->on_high; + at = state_->usage; + } + } + state_->invoke_callback(fire, at); + return true; + } + + [[nodiscard]] Void::Result::Result + try_acquire_checked(std::uint64_t amount = 1) + { + if (amount == 0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "ResourceMonitor::try_acquire_checked requires amount > 0")); + } + Callback fire; + std::uint64_t at = 0; + { + std::lock_guard lock{state_->mu}; + if (amount > state_->limit - state_->usage) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::overflow, + "ResourceMonitor reservation exceeds configured limit")); + } + state_->usage += amount; + if (!state_->alarmed && state_->usage >= state_->high) { + state_->alarmed = true; + fire = state_->on_high; + at = state_->usage; + } + } + state_->invoke_callback(fire, at); + return ResourcePermit{state_, amount}; + } + + void release(std::uint64_t amount = 1) + { + state_->release_amount(amount, true); + } + + [[nodiscard]] Void::Result::Result + release_checked(std::uint64_t amount = 1) + { + if (amount == 0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "ResourceMonitor::release_checked requires amount > 0")); + } + Callback fire; + std::uint64_t at = 0; + { + std::lock_guard lock{state_->mu}; + if (amount > state_->usage) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::over_release, + "ResourceMonitor release amount exceeds active usage")); + } + state_->usage -= amount; + if (state_->alarmed && state_->usage <= state_->low) { + state_->alarmed = false; + fire = state_->on_low; + at = state_->usage; + } + } + state_->invoke_callback(fire, at); + return {}; + } + + [[nodiscard]] std::uint64_t usage() const + { + std::lock_guard lock{state_->mu}; + return state_->usage; + } + + [[nodiscard]] std::uint64_t limit() const noexcept + { + return state_->limit; + } + + [[nodiscard]] double utilization() const + { + std::lock_guard lock{state_->mu}; + return state_->limit == 0 + ? 0.0 + : static_cast(state_->usage) / + static_cast(state_->limit); + } + + [[nodiscard]] std::uint64_t observer_errors() const + { + std::lock_guard lock{state_->mu}; + return state_->observer_errors; + } + +private: + explicit ResourceMonitor(std::shared_ptr state) noexcept + : state_(std::move(state)) + { + } + + [[nodiscard]] static std::uint64_t clamp_fraction(std::uint64_t limit, + double frac, + double fallback) noexcept + { + const double chosen = + (std::isfinite(frac) && frac >= 0.0 && frac <= 1.0) ? frac : fallback; + return static_cast( + std::clamp(static_cast(limit) * chosen, + 0.0, + static_cast(limit))); + } + + std::shared_ptr state_; +}; } // namespace Void::Resilience diff --git a/include/Void/Resilience/Types.hpp b/include/Void/Resilience/Types.hpp new file mode 100644 index 0000000..b7efd39 --- /dev/null +++ b/include/Void/Resilience/Types.hpp @@ -0,0 +1,176 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Resilience +{ + +enum class ResilienceErrorCode : std::int32_t { + invalid_argument = 1, + rate_limited = 2, + circuit_open = 3, + bulkhead_full = 4, + capacity_exceeded = 5, + overflow = 6, + over_release = 7, + closed = 8, + cancelled = 9, + timeout = 10, + key_too_large = 11 +}; + +[[nodiscard]] inline Void::Result::Error + make_resilience_error(ResilienceErrorCode code, std::string message = {}) +{ + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case ResilienceErrorCode::invalid_argument: + case ResilienceErrorCode::key_too_large: + kind = ErrorKind::invalid_argument; + break; + case ResilienceErrorCode::rate_limited: + case ResilienceErrorCode::circuit_open: + case ResilienceErrorCode::bulkhead_full: + kind = ErrorKind::overloaded; + break; + case ResilienceErrorCode::capacity_exceeded: + case ResilienceErrorCode::overflow: + kind = ErrorKind::exhausted; + break; + case ResilienceErrorCode::over_release: + kind = ErrorKind::conflict; + break; + case ResilienceErrorCode::closed: + case ResilienceErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case ResilienceErrorCode::timeout: + kind = ErrorKind::timeout; + break; + } + + return Error{ + kind, + std::move(message), + ErrorCode{Void::Result::kResilienceErrorDomain, + static_cast(code)}}; +} + +enum class Outcome : std::uint8_t { + success = 0, + dependency_failure, + neutral +}; + +struct Admission { + bool allowed{false}; + std::chrono::nanoseconds retry_after{0}; +}; + +struct BucketConfig { + double capacity{100.0}; + double refill_per_second{100.0}; + std::string metric_name{}; + + [[nodiscard]] Void::Result::Result validate() const + { + if (!std::isfinite(capacity) || capacity <= 0.0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "BucketConfig::capacity must be finite and positive")); + } + if (!std::isfinite(refill_per_second) || refill_per_second < 0.0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "BucketConfig::refill_per_second must be finite and non-negative")); + } + return {}; + } +}; + +struct KeyedBucketConfig { + double capacity{100.0}; + double refill_per_second{100.0}; + std::size_t max_keys{10'000}; + std::size_t max_key_bytes{256}; + std::chrono::nanoseconds idle_retention{std::chrono::minutes{5}}; + std::size_t cleanup_batch_limit{256}; + std::string metric_name{}; + + [[nodiscard]] Void::Result::Result validate() const + { + if (!std::isfinite(capacity) || capacity <= 0.0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "KeyedBucketConfig::capacity must be finite and positive")); + } + if (!std::isfinite(refill_per_second) || refill_per_second < 0.0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "KeyedBucketConfig::refill_per_second must be finite and non-negative")); + } + if (max_keys == 0 || max_key_bytes == 0 || cleanup_batch_limit == 0 || + idle_retention.count() < 0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "KeyedBucketConfig limits must be positive")); + } + return {}; + } +}; + +struct BreakerConfig { + std::size_t failure_threshold{5}; + std::chrono::nanoseconds cooldown{std::chrono::seconds{5}}; + std::size_t half_open_max_probes{1}; + std::size_t success_threshold{2}; + std::string metric_name{}; + + [[nodiscard]] Void::Result::Result validate() const + { + if (failure_threshold == 0 || half_open_max_probes == 0 || + success_threshold == 0 || cooldown.count() < 0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "BreakerConfig thresholds/probes must be positive and cooldown non-negative")); + } + return {}; + } +}; + +struct MonitorConfig { + std::uint64_t limit{0}; + double high_fraction{0.9}; + double low_fraction{0.7}; + + [[nodiscard]] Void::Result::Result validate() const + { + if (limit == 0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "MonitorConfig::limit must be non-zero")); + } + if (!std::isfinite(high_fraction) || !std::isfinite(low_fraction) || + low_fraction < 0.0 || low_fraction > high_fraction || + high_fraction > 1.0) { + return Void::Result::fail(make_resilience_error( + ResilienceErrorCode::invalid_argument, + "MonitorConfig watermarks must satisfy 0.0 <= low <= high <= 1.0")); + } + return {}; + } +}; + +} // namespace Void::Resilience diff --git a/src/Resilience/module.cmake b/src/Resilience/module.cmake index a106c65..165e3ba 100644 --- a/src/Resilience/module.cmake +++ b/src/Resilience/module.cmake @@ -1 +1,4 @@ -void_add_module(Resilience) +void_add_module(Resilience + INTERNAL_DEPS Functional Time ObservabilityHooks + EXCLUDE_HEADERS Void/Resilience/AsyncPolicy.hpp +) diff --git a/src/ResilienceAsync/module.cmake b/src/ResilienceAsync/module.cmake new file mode 100644 index 0000000..6a2ee6b --- /dev/null +++ b/src/ResilienceAsync/module.cmake @@ -0,0 +1,4 @@ +void_add_module(ResilienceAsync + INTERNAL_DEPS Resilience Async Functional Time ObservabilityHooks + EXTRA_HEADERS Void/Resilience/AsyncPolicy.hpp +) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 8ee7f8c..a33ed33 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -126,6 +126,11 @@ if(_has_obs) run_consumer(ObservabilityOnly "${install_prefix}" "ObservabilityOnly" ${_no_external_deps}) endif() +has_modules(_has_resilience Resilience ObservabilityHooks Time Functional Core) +if(_has_resilience) + run_consumer(ResilienceOnly "${install_prefix}" "ResilienceOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/ResilienceOnly/CMakeLists.txt b/tests/package/ResilienceOnly/CMakeLists.txt new file mode 100644 index 0000000..a956708 --- /dev/null +++ b/tests/package/ResilienceOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidResilienceOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Resilience) + +add_executable(void_resilience_only_consumer main.cpp) +target_link_libraries(void_resilience_only_consumer PRIVATE Void::Resilience) + +enable_testing() +add_test(NAME VoidResilienceOnlyConsumer COMMAND void_resilience_only_consumer) diff --git a/tests/package/ResilienceOnly/main.cpp b/tests/package/ResilienceOnly/main.cpp new file mode 100644 index 0000000..8b59930 --- /dev/null +++ b/tests/package/ResilienceOnly/main.cpp @@ -0,0 +1,22 @@ +#include + +int main() +{ + auto b = Void::Resilience::TokenBucket::create( + Void::Resilience::BucketConfig{4.0, 1.0}); + auto br = Void::Resilience::Breaker::create(Void::Resilience::BreakerConfig{}); + auto mon = Void::Resilience::ResourceMonitor::create( + Void::Resilience::MonitorConfig{16, 0.9, 0.7}); + if (!b || !br || !mon) { + return 1; + } + auto bp = br->acquire(); + auto rp = mon->try_acquire_checked(4); + auto adm = b->try_acquire_checked(1.0); + if (!bp || !rp || !adm || !adm->allowed) { + return 2; + } + bp->finish(Void::Resilience::Outcome::success); + rp->release(); + return 0; +} diff --git a/tests/standalone/Resilience/ResilienceHardening.cpp b/tests/standalone/Resilience/ResilienceHardening.cpp new file mode 100644 index 0000000..f423cac --- /dev/null +++ b/tests/standalone/Resilience/ResilienceHardening.cpp @@ -0,0 +1,272 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using namespace Void::Resilience; +using namespace std::chrono_literals; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +} // namespace + +Void::Testing::Test resilience_bucket_config_regression_and_multi_rollback() +{ + expect(!BucketConfig{0.0, 1.0}.validate().has_value()); + expect(!BucketConfig{-1.0, 1.0}.validate().has_value()); + expect(!BucketConfig{std::numeric_limits::quiet_NaN(), 1.0}.validate().has_value()); + expect(!BucketConfig{10.0, -0.5}.validate().has_value()); + expect(!BucketConfig{10.0, std::numeric_limits::infinity()}.validate().has_value()); + // Zero refill is valid (finite non-refilling bucket). + expect(BucketConfig{10.0, 0.0}.validate().has_value()); + + Void::Time::ManualClock clock; + (void)clock.advance(10s); + + auto b1_res = TokenBucket::create(BucketConfig{10.0, 2.0}, clock); + auto b2_res = TokenBucket::create(BucketConfig{4.0, 1.0}, clock); + require(b1_res.has_value() && b2_res.has_value()); + auto b1 = std::move(*b1_res); + auto b2 = std::move(*b2_res); + + // Invalid costs consume nothing. + expect(!b1.try_acquire_checked(-1.0).has_value()); + expect(!b1.try_acquire_checked(0.0).has_value()); + expect(!b1.try_acquire_checked(std::numeric_limits::quiet_NaN()).has_value()); + expect(!b1.try_acquire_checked(11.0).has_value()); + expect_eq(b1.available(), 10.0); + + // Spend 2 from b1, then prove backwards timestamp cannot add double credit. + auto ok1 = b1.try_acquire_checked(2.0); + require(ok1.has_value()); + expect(ok1->allowed); + const auto t_now = clock.now(); + const auto earlier = t_now - 5s; + expect(b1.available_at(earlier) <= 8.0001); + expect(b1.available_at(t_now) <= 8.0001); + + // Multi-bucket atomic acquisition rolls back (leaves both untouched) when b2 fails. + const std::pair pair_fail[] = {{&b1, 5.0}, {&b2, 5.0}}; + expect(!TokenBucket::try_acquire_all(pair_fail, clock).has_value()); + expect_eq(b1.available(), 8.0); + expect_eq(b2.available(), 4.0); + + const std::pair pair_deny[] = {{&b1, 5.0}, {&b2, 4.0}}; + auto adm1 = TokenBucket::try_acquire_all(pair_deny, clock); + require(adm1.has_value()); + expect(adm1->allowed); + expect_eq(b1.available(), 3.0); + expect_eq(b2.available(), 0.0); + + // Now b2 cannot afford 1 -> b1 must NOT be debited! + const std::pair pair_second[] = {{&b1, 2.0}, {&b2, 1.0}}; + auto adm2 = TokenBucket::try_acquire_all(pair_second, clock); + require(adm2.has_value()); + expect(!adm2->allowed); + expect(adm2->retry_after > 0ns); + expect_eq(b1.available(), 3.0); +} + +Void::Testing::Test resilience_resource_monitor_overflow_permits_and_observers() +{ + expect(!MonitorConfig{0, 0.9, 0.7}.validate().has_value()); + expect(!MonitorConfig{100, 0.5, 0.8}.validate().has_value()); + expect(!MonitorConfig{100, 1.5, 0.7}.validate().has_value()); + + // Overflow-safe check near UINT64_MAX. + const auto umax = std::numeric_limits::max(); + ResourceMonitor hugemon{umax}; + expect(hugemon.try_acquire(umax - 10)); + expect(!hugemon.try_acquire(20)); // previously wrapped unsigned arithmetic! + expect_eq(hugemon.usage(), umax - 10); + + auto mon_res = ResourceMonitor::create(MonitorConfig{100, 0.9, 0.7}); + require(mon_res.has_value()); + auto mon = std::move(*mon_res); + + // Observer that throws AND re-enters monitor queries must not corrupt state. + int high_calls = 0; + mon.on_high_watermark([&](std::uint64_t) { + ++high_calls; + (void)mon.usage(); + throw std::runtime_error{"observer failed"}; + }); + + { + auto p = mon.try_acquire_checked(95); + require(p.has_value()); + expect(p->active()); + expect_eq(mon.usage(), std::uint64_t{95}); + expect_eq(high_calls, 1); + expect_eq(mon.observer_errors(), std::uint64_t{1}); + } + // Permit auto-released on destruction. + expect_eq(mon.usage(), std::uint64_t{0}); + + // Strict over-release check rejects instead of silently clamping. + expect(mon.try_acquire(10)); + auto over = mon.release_checked(20); + expect(!over.has_value()); + expect_eq(over.error().code().value, + static_cast(ResilienceErrorCode::over_release)); + expect_eq(mon.usage(), std::uint64_t{10}); +} + +Void::Testing::Test resilience_breaker_single_probe_generation_and_abandon() +{ + expect(!BreakerConfig{0, 5s, 1, 2}.validate().has_value()); + expect(!BreakerConfig{5, 5s, 0, 2}.validate().has_value()); + expect(!BreakerConfig{5, 5s, 1, 0}.validate().has_value()); + + Void::Time::ManualClock clock; + BreakerConfig cfg{}; + cfg.failure_threshold = 2; + cfg.cooldown = 5s; + cfg.half_open_max_probes = 1; + cfg.success_threshold = 2; + + auto br_res = Breaker::create(cfg, clock); + require(br_res.has_value()); + auto br = std::move(*br_res); + + // Grab an in-flight permit at gen 1 BEFORE tripping, then trip Open with another. + auto stale_p = br.acquire(); + require(stale_p.has_value()); + const auto gen1 = stale_p->generation(); + + for (int i = 0; i < 2; ++i) { + auto p = br.acquire(); + require(p.has_value()); + p->finish(Outcome::dependency_failure); + } + expect(br.state() == BreakerState::open); + expect(br.generation() > gen1); + + // Completing stale generation permit must not close or corrupt Open breaker. + stale_p->finish(Outcome::success); + expect(br.state() == BreakerState::open); + expect(!br.acquire().has_value()); + + // Advance cooldown: first acquire gets sole HalfOpen probe; concurrent 2nd fails. + (void)clock.advance(5s); + { + auto probe1 = br.acquire(); + require(probe1.has_value()); + expect(probe1->is_probe()); + expect(br.state() == BreakerState::half_open); + expect_eq(br.half_open_in_flight(), std::size_t{1}); + + auto concurrent = br.acquire(); + expect(!concurrent.has_value()); + expect_eq(concurrent.error().code().value, + static_cast(ResilienceErrorCode::circuit_open)); + // Destroying probe1 without explicit finish treats it neutrally and + // frees the probe slot so HalfOpen does not deadlock. + } + expect_eq(br.half_open_in_flight(), std::size_t{0}); + expect(br.state() == BreakerState::half_open); + + // Two sequential successful probes close the breaker. + for (int i = 0; i < 2; ++i) { + auto probe = br.acquire(); + require(probe.has_value()); + expect(probe->is_probe()); + probe->finish(Outcome::success); + } + expect(br.state() == BreakerState::closed); + + // Multi-thread contention during HalfOpen never exceeds 1 concurrent probe. + for (int i = 0; i < 2; ++i) { + auto p = br.acquire(); + require(p.has_value()); + p->finish(Outcome::dependency_failure); + } + (void)clock.advance(5s); + std::atomic admitted_probes{0}; + std::atomic rejected{0}; + std::vector racers; + std::vector> acquired(16); + std::atomic go{false}; + for (std::size_t i = 0; i < 16; ++i) { + racers.emplace_back([&, i] { + while (!go.load(std::memory_order_acquire)) { + } + auto r = br.acquire(); + if (r.has_value()) { + admitted_probes.fetch_add(1, std::memory_order_relaxed); + acquired[i].emplace(std::move(*r)); + } else { + rejected.fetch_add(1, std::memory_order_relaxed); + } + }); + } + go.store(true, std::memory_order_release); + for (auto& t : racers) { + t.join(); + } + expect_eq(admitted_probes.load(), 1); + expect_eq(rejected.load(), 15); + acquired.clear(); +} + +Void::Testing::Test resilience_bounded_keyed_limiter_churn_and_cursor_cleanup() +{ + Void::Time::ManualClock clock; + KeyedBucketConfig cfg{}; + cfg.capacity = 2.0; + cfg.refill_per_second = 0.0; + cfg.max_keys = 3; + cfg.max_key_bytes = 16; + cfg.idle_retention = 10s; + cfg.cleanup_batch_limit = 2; + + auto kl_res = BoundedKeyedRateLimiter::create(cfg, clock); + require(kl_res.has_value()); + auto kl = std::move(*kl_res); + + // Oversize key fails with key_too_large. + auto too_long = kl.admit(std::string(17, 'x')); + expect(!too_long.has_value()); + expect_eq(too_long.error().code().value, + static_cast(ResilienceErrorCode::key_too_large)); + + expect(kl.admit("k1")->allowed); + expect(kl.admit("k2")->allowed); + expect(kl.admit("k3")->allowed); + expect_eq(kl.tracked(), std::size_t{3}); + + // Churn keys k4..k10 must be rejected cleanly WITHOUT evicting live k1..k3! + for (int i = 4; i <= 10; ++i) { + auto r = kl.admit("k" + std::to_string(i)); + require(r.has_value()); + expect(!r->allowed); + } + expect_eq(kl.rejected_new_keys(), std::uint64_t{7}); + expect(kl.admit("k1")->allowed); // k1's quota was NOT reset (1/2 remaining)! + expect(!kl.admit("k1")->allowed); // k1 is now genuinely empty! + + // Refresh k1 at t=8s; leave k2 and k3 untouched since t=0s. + (void)clock.advance(8s); + (void)kl.admit("k2", 0.5); // consume from k2 to refresh last_seen to 8s + + // Advance to t=11s: k1 (last=0s) & k3 (last=0s) are >=10s idle; k2 (last=8s) is live. + (void)clock.advance(3s); + // cleanup_batch_limit=2 removes in bounded incremental steps across turns. + const std::size_t r1 = kl.cleanup_step(); + const std::size_t r2 = kl.cleanup_step(); + expect_eq(r1 + r2, std::size_t{2}); + expect_eq(kl.tracked(), std::size_t{1}); +} diff --git a/tests/standalone/ResilienceAsync/AsyncPolicy.cpp b/tests/standalone/ResilienceAsync/AsyncPolicy.cpp new file mode 100644 index 0000000..f6d60f3 --- /dev/null +++ b/tests/standalone/ResilienceAsync/AsyncPolicy.cpp @@ -0,0 +1,252 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Async = Void::Async; +using namespace Void::Resilience; +using namespace std::chrono_literals; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +namespace +{ + +Void::Coro::Task> acquire_bulkhead_coro( + Bulkhead& bh, + Async::OperationOptions opts, + Async::Executor* exec) +{ + co_return co_await bh.acquire_async(std::move(opts), exec); +} + +Void::Coro::Task spawn_acquire_to_slot( + Bulkhead* bh, + Async::OperationOptions opts, + Async::Executor* exec, + std::optional>* out, + std::atomic* done_count) +{ + *out = co_await bh->acquire_async(std::move(opts), exec); + done_count->fetch_add(1, std::memory_order_release); +} + +Void::Coro::Task> run_pipeline_coro( + ResiliencePipeline pipeline, + std::function()> fn, + std::function&)> classify, + Async::OperationOptions opts, + Async::Executor* exec) +{ + co_return co_await execute_resilient( + std::move(pipeline), + std::move(fn), + std::move(classify), + std::move(opts), + exec); +} + +} // namespace + +Void::Testing::Test resilience_async_bulkhead_fifo_expiry_stop_and_close() +{ + Void::Time::ManualClock clock; + BulkheadConfig cfg{}; + cfg.max_active = 1; + cfg.max_waiting = 2; + auto bh_res = Bulkhead::create(cfg, clock); + require(bh_res.has_value()); + auto bh = std::move(*bh_res); + + auto active1 = bh.try_acquire(); + require(active1.has_value()); + expect_eq(bh.active_count(), std::size_t{1}); + + Void::Async::ManualExecutor exec; + std::optional> out_exp; + std::optional> out_stop; + std::optional> out_ok; + std::atomic done{0}; + + std::stop_source stop_src; + Async::OperationOptions exp_opts{}; + exp_opts.deadline = clock.now() + 50ms; + Async::OperationOptions stop_opts{}; + stop_opts.stop = stop_src.get_token(); + + // Enqueue 2 waiters (limit=2): waiter1 has deadline, waiter2 has stop token. + Void::Async::spawn( + exec, spawn_acquire_to_slot(&bh, exp_opts, &exec, &out_exp, &done)); + Void::Async::spawn( + exec, spawn_acquire_to_slot(&bh, stop_opts, &exec, &out_stop, &done)); + (void)exec.drain(); + expect_eq(bh.waiting_count(), std::size_t{2}); + + // Advance past waiter1's deadline AND request waiter2 stop before next admission. + (void)clock.advance(100ms); + stop_src.request_stop(); + (void)exec.drain(); + + // Release active1 -> evicts expired waiter1 and cancelled waiter2, freeing slot! + active1->release(); + (void)exec.drain(); + expect_eq(done.load(std::memory_order_acquire), 2); + require(out_exp.has_value() && !out_exp->has_value()); + require(out_stop.has_value() && !out_stop->has_value()); + expect_eq(bh.waiting_count(), std::size_t{0}); + expect_eq(bh.active_count(), std::size_t{0}); + + // Now test FIFO wait grant + close(). + auto active2 = bh.try_acquire(); + require(active2.has_value()); + + done.store(0); + std::optional> out_closed; + Void::Async::spawn( + exec, spawn_acquire_to_slot(&bh, {}, &exec, &out_ok, &done)); + Void::Async::spawn( + exec, spawn_acquire_to_slot(&bh, {}, &exec, &out_closed, &done)); + (void)exec.drain(); + expect_eq(bh.waiting_count(), std::size_t{2}); + + // 3rd waiter overflows max_waiting=2 immediately. + auto full_t = acquire_bulkhead_coro(bh, {}, &exec); + auto full_r = full_t.run(); + expect(!full_r.has_value()); + expect_eq(full_r.error().code().value, + static_cast(ResilienceErrorCode::bulkhead_full)); + + // Releasing active2 grants first FIFO waiter (out_ok). + active2->release(); + (void)exec.drain(); + require(out_ok.has_value() && out_ok->has_value()); + + // close() rejects remaining waiter (out_closed) with closed error. + bh.close(); + (void)exec.drain(); + require(out_closed.has_value() && !out_closed->has_value()); + expect_eq(out_closed->error().code().value, + static_cast(ResilienceErrorCode::closed)); + out_ok->value().release(); +} + +Void::Testing::Test resilience_async_execute_order_replay_deadline_and_breaker() +{ + Void::Time::ManualClock clock; + auto rl = TokenBucket::create(BucketConfig{10.0, 1.0}, clock); + auto bh = Bulkhead::create(BulkheadConfig{2, 4}, clock); + auto br = Breaker::create(BreakerConfig{2, 5s, 1, 1}, clock); + require(rl.has_value() && bh.has_value() && br.has_value()); + + // 1. Non-replay-safe write never retries even when classifier marks retryable. + int calls = 0; + std::vector delays; + ResiliencePipeline write_pipe{}; + write_pipe.rate_limiter = &*rl; + write_pipe.bulkhead = &*bh; + write_pipe.breaker = &*br; + write_pipe.clock = &clock; + write_pipe.retry = ResilientRetryConfig{ + .max_attempts = 3, + .base_delay = 100ms, + .max_delay = 2000ms, + .replay_safe = false, + .deterministic_seed = 42}; + write_pipe.wait_fn = [&](std::chrono::nanoseconds d, const Async::OperationOptions&) { + delays.push_back(d); + (void)clock.advance(d); + return true; + }; + + auto res1 = run_pipeline_coro( + write_pipe, + [&]() -> Void::Result::Result { + ++calls; + return Void::Result::fail("write uncertain"); + }, + [](const Void::Result::Result&) { + return AttemptClassification{Outcome::dependency_failure, true}; + }, + {}, + nullptr) + .run(); + expect(!res1.has_value()); + expect_eq(calls, 1); + expect_eq(bh->active_count(), std::size_t{0}); + + // Reset breaker (or let 2nd failure trip it on replay-safe call!). + // 2. Replay-safe read retries through limits until breaker trips open! + calls = 0; + ResiliencePipeline read_pipe = write_pipe; + read_pipe.retry.replay_safe = true; + read_pipe.retry.max_attempts = 5; + auto res2 = run_pipeline_coro( + read_pipe, + [&]() -> Void::Result::Result { + ++calls; + return Void::Result::fail("transient downstream"); + }, + [](const Void::Result::Result&) { + return AttemptClassification{Outcome::dependency_failure, true}; + }, + {}, + nullptr) + .run(); + // 1st attempt failed before this test -> breaker already had 1 failure, so + // this attempt trips breaker Open on attempt #1, then attempt #2 fails with circuit_open! + expect(!res2.has_value()); + expect_eq(calls, 1); + expect_eq(res2.error().code().value, + static_cast(ResilienceErrorCode::circuit_open)); + expect_eq(bh->active_count(), std::size_t{0}); + + // 3. Replay-safe succeeds on attempt #3 within shared total deadline. + (void)clock.advance(5s); // cooldown elapsed -> HalfOpen probe closes breaker on 1st success! + auto br2 = Breaker::create(BreakerConfig{10, 5s, 1, 1}, clock); + require(br2.has_value()); + calls = 0; + delays.clear(); + ResiliencePipeline ok_pipe = read_pipe; + ok_pipe.breaker = &*br2; + ok_pipe.retry.max_attempts = 3; + ok_pipe.wait_fn = [&](std::chrono::nanoseconds d, const Async::OperationOptions&) { + delays.push_back(d); + (void)clock.advance(d); + return true; + }; + + Async::OperationOptions bounded_opts{}; + bounded_opts.deadline = clock.now() + 5000ms; + auto res3 = run_pipeline_coro( + ok_pipe, + [&]() -> Void::Result::Result { + ++calls; + if (calls < 3) { + return Void::Result::fail("retryable"); + } + return 99; + }, + [](const Void::Result::Result& r) { + return r.has_value() + ? AttemptClassification{Outcome::success, false} + : AttemptClassification{Outcome::dependency_failure, true}; + }, + bounded_opts, + nullptr) + .run(); + require(res3.has_value()); + expect_eq(*res3, 99); + expect_eq(calls, 3); + expect_eq(delays.size(), std::size_t{2}); + expect(delays[0] <= 100ms); + expect(delays[1] <= 200ms); +}