Add async/resilience/reflection primitives + FSM v2 rewrite

A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 15:45:16 +03:00
1 parent 43b5a81504
commit 80293ee56f
93 files changed
+8500 -3312

No files matched your search

+203
View File
@@ -0,0 +1,203 @@
#pragma once
#include <bit>
#include <cstddef>
#include <cstdint>
#include <span>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::BufferPool
{
// ── BufferPool<T>
// ───────────────────────────────────────────────────────────── A pool of
// reusable, variable-length buffers of T — e.g. audio sample blocks (int16
// / float). Distinct from Containers/Pool.hpp's ObjectPool, which pools
// fixed-size *objects*: this pools backing storage sized by request.
//
// acquire(n) hands back a Buffer of logical length n backed by capacity
// rounded up to the next power-of-two size class; on drop the storage
// returns to the pool's bucket for that size class, so a later acquire of
// the same class reuses it with no reallocation.
//
// Not thread-safe — guard externally if shared.
template <typename T> class BufferPool
{
public:
BufferPool() = default;
BufferPool(const BufferPool&) = delete;
BufferPool& operator=(const BufferPool&) = delete;
BufferPool(BufferPool&&) = default;
BufferPool& operator=(BufferPool&&) = default;
struct Stats {
std::uint64_t allocations = 0; // fresh storage allocated
std::uint64_t reuses = 0; // requests served from a bucket
std::size_t pooled = 0; // buffers currently idle in buckets
};
// An owning view returned by acquire(); recycles its storage on
// drop.
class Buffer
{
public:
Buffer() = default;
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
Buffer(Buffer&& other) noexcept
: pool_{other.pool_},
storage_{std::move(other.storage_)},
size_{other.size_}
{
other.pool_ = nullptr;
other.size_ = 0;
}
Buffer& operator=(Buffer&& other) noexcept
{
if (this != &other) {
recycle();
pool_ = other.pool_;
storage_ = std::move(other.storage_);
size_ = other.size_;
other.pool_ = nullptr;
other.size_ = 0;
}
return *this;
}
~Buffer() { recycle(); }
[[nodiscard]] T* data() noexcept { return storage_.data(); }
[[nodiscard]] const T* data() const noexcept
{
return storage_.data();
}
[[nodiscard]] std::size_t size() const noexcept
{
return size_;
}
[[nodiscard]] bool empty() const noexcept
{
return size_ == 0;
}
// Backing capacity (the size class) — always >= size().
[[nodiscard]] std::size_t capacity() const noexcept
{
return storage_.size();
}
[[nodiscard]] T& operator[](std::size_t i) noexcept
{
return storage_[i];
}
[[nodiscard]] const T&
operator[](std::size_t i) const noexcept
{
return storage_[i];
}
[[nodiscard]] T* begin() noexcept { return data(); }
[[nodiscard]] T* end() noexcept { return data() + size_; }
[[nodiscard]] const T* begin() const noexcept
{
return data();
}
[[nodiscard]] const T* end() const noexcept
{
return data() + size_;
}
[[nodiscard]] std::span<T> span() noexcept
{
return {data(), size_};
}
[[nodiscard]] std::span<const T> span() const noexcept
{
return {data(), size_};
}
private:
friend class BufferPool;
Buffer(BufferPool* pool, std::vector<T> storage,
std::size_t n) noexcept
: pool_{pool}, storage_{std::move(storage)}, size_{n}
{
}
void recycle() noexcept
{
if (pool_) {
pool_->recycle(std::move(storage_));
pool_ = nullptr;
}
}
BufferPool* pool_ = nullptr;
std::vector<T> storage_;
std::size_t size_ = 0;
};
// Hand out a buffer of logical length n (capacity rounded up to a
// power of two), reusing pooled storage of that size class when
// available.
[[nodiscard]] Buffer acquire(std::size_t n)
{
const std::size_t cls = size_class(n);
std::vector<T> storage;
auto bucket = free_.find(cls);
if (bucket != free_.end() && !bucket->second.empty()) {
storage = std::move(bucket->second.back());
bucket->second.pop_back();
++reuses_;
} else {
storage.resize(cls);
++allocations_;
}
return Buffer{this, std::move(storage), n};
}
[[nodiscard]] Stats stats() const
{
std::size_t pooled = 0;
for (const auto& [cls, bucket] : free_) {
pooled += bucket.size();
}
return Stats{allocations_, reuses_, pooled};
}
// Drop all pooled (idle) storage. Outstanding Buffers are
// unaffected.
void shrink() noexcept { free_.clear(); }
private:
static std::size_t size_class(std::size_t n) noexcept
{
return n == 0 ? 0 : std::bit_ceil(n);
}
void recycle(std::vector<T> storage)
{
if (storage.empty()) {
return;
}
free_[storage.size()].push_back(std::move(storage));
}
std::unordered_map<std::size_t, std::vector<std::vector<T>>> free_;
std::uint64_t allocations_ = 0;
std::uint64_t reuses_ = 0;
};
} // namespace Void::BufferPool
+268
View File
@@ -0,0 +1,268 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <list>
#include <optional>
#include <stdexcept>
#include <unordered_map>
#include <utility>
namespace Void::Cache
{
// ── Cache<K, V>
// ─────────────────────────────────────────────────────────────── A
// fixed-capacity cache with per-entry TTL, a selectable eviction policy,
// and hit/miss/eviction/expiration counters. Built on the same
// doubly-linked-list + hash-map structure as Containers/LRU.hpp (which
// stays the minimal primitive).
//
// Not thread-safe — guard externally if shared, like LruCache.
//
// Expiry is lazy: an entry past its TTL is treated as a miss and dropped on
// the next access (or in bulk via sweep()). The clock is injectable for
// tests.
enum class Policy {
LRU, // evict the least-recently-used entry (default)
LFU, // evict the least-frequently-used entry
FIFO // evict the oldest inserted entry
};
template <typename K, typename V> class Cache
{
public:
using Clock =
std::function<std::chrono::steady_clock::time_point()>;
using Duration = std::chrono::steady_clock::duration;
using TimePoint = std::chrono::steady_clock::time_point;
struct Stats {
std::uint64_t hits = 0;
std::uint64_t misses = 0;
std::uint64_t evictions =
0; // dropped to make room (capacity)
std::uint64_t expirations =
0; // dropped because the TTL elapsed
std::size_t size = 0;
};
explicit Cache(std::size_t capacity, Policy policy = Policy::LRU,
std::optional<Duration> default_ttl = std::nullopt,
Clock clock = default_clock())
: capacity_{capacity}, policy_{policy},
default_ttl_{default_ttl}, clock_{std::move(clock)}
{
if (capacity == 0) {
throw std::invalid_argument{"capacity must be > 0"};
}
}
[[nodiscard]] std::size_t capacity() const noexcept
{
return capacity_;
}
[[nodiscard]] std::size_t size() const noexcept
{
return map_.size();
}
[[nodiscard]] bool empty() const noexcept { return map_.empty(); }
[[nodiscard]] bool full() const noexcept
{
return map_.size() == capacity_;
}
[[nodiscard]] Policy policy() const noexcept { return policy_; }
// Retrieve a value. nullopt on miss or expiry; updates recency /
// frequency and the hit/miss counters on every call.
[[nodiscard]] std::optional<V> get(const K& key)
{
auto it = map_.find(key);
if (it == map_.end()) {
++misses_;
return std::nullopt;
}
const auto now = clock_();
if (expired(*it->second, now)) {
drop(it);
++expirations_;
++misses_;
return std::nullopt;
}
++hits_;
touch(it->second);
return it->second->value;
}
// Peek without recency promotion and without touching hit/miss
// stats. Still respects expiry (an expired entry is invisible and
// dropped).
[[nodiscard]] const V* peek(const K& key)
{
auto it = map_.find(key);
if (it == map_.end()) {
return nullptr;
}
if (expired(*it->second, clock_())) {
drop(it);
++expirations_;
return nullptr;
}
return &it->second->value;
}
// Insert or update with the cache's default TTL.
void put(const K& key, V value)
{
put(key, std::move(value), default_ttl_);
}
// Insert or update with an explicit TTL (nullopt = never expires).
void put(const K& key, V value, std::optional<Duration> ttl)
{
const auto now = clock_();
if (auto it = map_.find(key); it != map_.end()) {
it->second->value = std::move(value);
set_expiry(*it->second, ttl, now);
touch(it->second);
return;
}
if (map_.size() == capacity_) {
evict_one();
}
list_.push_front(Node{key, std::move(value), 1, {}, false});
set_expiry(list_.front(), ttl, now);
map_[key] = list_.begin();
}
bool erase(const K& key)
{
auto it = map_.find(key);
if (it == map_.end()) {
return false;
}
drop(it);
return true;
}
void clear() noexcept
{
list_.clear();
map_.clear();
}
// Present and not expired. Const: does not drop the expired entry.
[[nodiscard]] bool contains(const K& key) const
{
auto it = map_.find(key);
return it != map_.end() && !expired(*it->second, clock_());
}
// Purge every expired entry; returns how many were removed.
std::size_t sweep()
{
const auto now = clock_();
std::size_t purged = 0;
for (auto it = list_.begin(); it != list_.end();) {
if (expired(*it, now)) {
map_.erase(it->key);
it = list_.erase(it);
++purged;
++expirations_;
} else {
++it;
}
}
return purged;
}
[[nodiscard]] Stats stats() const
{
return Stats{hits_, misses_, evictions_, expirations_,
map_.size()};
}
private:
struct Node {
K key;
V value;
std::uint64_t freq = 0;
TimePoint expiry{};
bool has_expiry = false;
};
using List = std::list<Node>;
using Map = std::unordered_map<K, typename List::iterator>;
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
static bool expired(const Node& n, TimePoint now)
{
return n.has_expiry && now >= n.expiry;
}
void set_expiry(Node& n, std::optional<Duration> ttl, TimePoint now)
{
n.has_expiry = ttl.has_value();
if (ttl) {
n.expiry = now + *ttl;
}
}
// Record a use: bump frequency and (for LRU) promote to
// most-recent.
void touch(typename List::iterator lit)
{
++lit->freq;
if (policy_ == Policy::LRU) {
list_.splice(list_.begin(), list_, lit);
}
}
void drop(typename Map::iterator it)
{
list_.erase(it->second);
map_.erase(it);
}
void evict_one()
{
typename List::iterator victim;
if (policy_ == Policy::LFU) {
victim = list_.begin();
for (auto i = list_.begin(); i != list_.end(); ++i) {
if (i->freq < victim->freq) {
victim = i;
}
}
} else {
// LRU and FIFO both evict from the back: LRU keeps the list
// in recency order via touch(); FIFO never reorders, so the
// back is the oldest insertion.
victim = std::prev(list_.end());
}
map_.erase(victim->key);
list_.erase(victim);
++evictions_;
}
std::size_t capacity_;
Policy policy_;
std::optional<Duration> default_ttl_;
Clock clock_;
List list_;
Map map_;
std::uint64_t hits_ = 0;
std::uint64_t misses_ = 0;
std::uint64_t evictions_ = 0;
std::uint64_t expirations_ = 0;
};
} // namespace Void::Cache
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <Void/Core/Meta.hpp>
#include <ranges>
#include <string>
namespace Void::Containers
{
/// Render any range's elements as "[e0, e1, …]" using the shared
/// reflection renderer Void::Meta::repr (so structs print their fields):
/// Containers::debug_dump(my_ring); // "[Point{x: 1, y: 2}, …]"
template <std::ranges::input_range R>
[[nodiscard]] std::string debug_dump(const R& range)
{
std::string out = "[";
bool first = true;
for (const auto& e : range) {
if (!first) {
out += ", ";
}
out += Void::Meta::repr(e);
first = false;
}
out += ']';
return out;
}
} // namespace Void::Containers