Files
Library/include/Void/Containers/Cache.hpp
T
faumarayandClaude Opus 4.8 80293ee56f 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>
2026-06-22 15:45:16 +03:00

269 lines
6.7 KiB
C++

#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