Files
EchoionApi/include/echoion/api/Cache.hpp
T
2026-02-01 23:05:41 +03:00

390 lines
11 KiB
C++

#pragma once
#include "Types.hpp"
#include "NetworkTypes.hpp"
#include "TrackTypes.hpp"
#include <string>
#include <unordered_map>
#include <mutex>
#include <shared_mutex>
#include <chrono>
#include <optional>
#include <functional>
#include <list>
#include <memory>
namespace Echoion::Api {
// Cache entry with metadata
template<typename T>
struct CacheEntry {
T value;
std::chrono::system_clock::time_point created;
std::chrono::system_clock::time_point lastAccessed;
std::chrono::milliseconds ttl;
uint64_t accessCount = 0;
size_t size = 0; // Approximate memory size
[[nodiscard]] bool isExpired() const {
auto now = std::chrono::system_clock::now();
return (now - created) > ttl;
}
};
// Cache statistics
struct CacheStats {
size_t hits = 0;
size_t misses = 0;
size_t evictions = 0;
size_t inserts = 0;
size_t currentSize = 0;
size_t maxSize = 0;
size_t memoryUsage = 0;
double hitRate() const {
auto total = hits + misses;
return total > 0 ? static_cast<double>(hits) / total : 0.0;
}
};
// Eviction policy
enum class EvictionPolicy {
LRU, // Least Recently Used
LFU, // Least Frequently Used
FIFO, // First In First Out
TTL // Time To Live only
};
// LRU Cache implementation
template<typename Key, typename Value>
class LruCache {
public:
using Entry = CacheEntry<Value>;
using Loader = std::function<std::optional<Value>(const Key&)>;
explicit LruCache(size_t maxSize = 1000,
std::chrono::milliseconds defaultTtl = std::chrono::minutes(5),
EvictionPolicy policy = EvictionPolicy::LRU)
: maxSize_(maxSize)
, defaultTtl_(defaultTtl)
, policy_(policy) {}
// Get value from cache (with optional loader for cache-aside pattern)
[[nodiscard]] std::optional<Value> get(const Key& key, Loader loader = nullptr) {
std::unique_lock<std::shared_mutex> lock(mutex_);
auto it = cache_.find(key);
if (it != cache_.end()) {
// Check if expired
if (it->second.entry.isExpired()) {
// Remove expired entry
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
cache_.erase(it);
stats_.evictions++;
lock.unlock();
stats_.misses++;
// Try to load if loader provided
if (loader) {
auto value = loader(key);
if (value) {
put(key, *value);
return value;
}
}
return std::nullopt;
}
// Update access info
it->second.entry.lastAccessed = std::chrono::system_clock::now();
it->second.entry.accessCount++;
// Move to front (MRU) for LRU policy
if (policy_ == EvictionPolicy::LRU) {
order_.splice(order_.begin(), order_, it->second.orderIt);
}
stats_.hits++;
return it->second.entry.value;
}
lock.unlock();
stats_.misses++;
// Try to load if loader provided
if (loader) {
auto value = loader(key);
if (value) {
put(key, *value);
return value;
}
}
return std::nullopt;
}
// Put value into cache
void put(const Key& key, const Value& value,
std::optional<std::chrono::milliseconds> ttl = std::nullopt,
size_t estimatedSize = 0) {
std::unique_lock<std::shared_mutex> lock(mutex_);
// Check if key already exists
auto it = cache_.find(key);
if (it != cache_.end()) {
// Update existing entry
memoryUsage_ -= it->second.entry.size;
it->second.entry.value = value;
it->second.entry.created = std::chrono::system_clock::now();
it->second.entry.lastAccessed = it->second.entry.created;
it->second.entry.ttl = ttl.value_or(defaultTtl_);
it->second.entry.size = estimatedSize;
memoryUsage_ += estimatedSize;
// Move to front for LRU
if (policy_ == EvictionPolicy::LRU) {
order_.splice(order_.begin(), order_, it->second.orderIt);
}
return;
}
// Evict entries if necessary
while (cache_.size() >= maxSize_ ||
(maxMemory_ > 0 && memoryUsage_ + estimatedSize > maxMemory_)) {
if (!evictOne()) {
break;
}
}
// Insert new entry
order_.push_front(key);
Entry entry{
.value = value,
.created = std::chrono::system_clock::now(),
.lastAccessed = entry.created,
.ttl = ttl.value_or(defaultTtl_),
.accessCount = 1,
.size = estimatedSize
};
cache_[key] = {
.entry = std::move(entry),
.orderIt = order_.begin()
};
memoryUsage_ += estimatedSize;
stats_.inserts++;
stats_.currentSize = cache_.size();
}
// Remove specific key
bool remove(const Key& key) {
std::unique_lock<std::shared_mutex> lock(mutex_);
auto it = cache_.find(key);
if (it == cache_.end()) {
return false;
}
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
cache_.erase(it);
stats_.currentSize = cache_.size();
return true;
}
// Clear all entries
void clear() {
std::unique_lock<std::shared_mutex> lock(mutex_);
cache_.clear();
order_.clear();
memoryUsage_ = 0;
stats_.currentSize = 0;
}
// Check if key exists (without updating access)
[[nodiscard]] bool contains(const Key& key) const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return cache_.find(key) != cache_.end();
}
// Get cache statistics
[[nodiscard]] CacheStats getStats() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
CacheStats stats = stats_;
stats.currentSize = cache_.size();
stats.maxSize = maxSize_;
stats.memoryUsage = memoryUsage_;
return stats;
}
// Reset statistics
void resetStats() {
std::unique_lock<std::shared_mutex> lock(mutex_);
stats_ = CacheStats{};
}
// Set max size
void setMaxSize(size_t maxSize) {
std::unique_lock<std::shared_mutex> lock(mutex_);
maxSize_ = maxSize;
// Evict if necessary
while (cache_.size() > maxSize_) {
if (!evictOne()) {
break;
}
}
}
// Set max memory (0 = unlimited)
void setMaxMemory(size_t maxMemory) {
std::unique_lock<std::shared_mutex> lock(mutex_);
maxMemory_ = maxMemory;
// Evict if necessary
if (maxMemory_ > 0) {
while (memoryUsage_ > maxMemory_) {
if (!evictOne()) {
break;
}
}
}
}
// Remove expired entries
size_t purgeExpired() {
std::unique_lock<std::shared_mutex> lock(mutex_);
size_t count = 0;
auto now = std::chrono::system_clock::now();
for (auto it = cache_.begin(); it != cache_.end();) {
if ((now - it->second.entry.created) > it->second.entry.ttl) {
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
it = cache_.erase(it);
count++;
} else {
++it;
}
}
stats_.evictions += count;
stats_.currentSize = cache_.size();
return count;
}
private:
struct Node {
Entry entry;
typename std::list<Key>::iterator orderIt;
};
bool evictOne() {
if (order_.empty()) {
return false;
}
Key keyToEvict;
switch (policy_) {
case EvictionPolicy::LRU:
case EvictionPolicy::FIFO:
// Evict from back (oldest/least recently used)
keyToEvict = order_.back();
break;
case EvictionPolicy::LFU: {
// Find least frequently used
auto minAccess = std::numeric_limits<uint64_t>::max();
for (const auto& [key, node] : cache_) {
if (node.entry.accessCount < minAccess) {
minAccess = node.entry.accessCount;
keyToEvict = key;
}
}
break;
}
case EvictionPolicy::TTL: {
// Find soonest to expire
auto now = std::chrono::system_clock::now();
auto minRemaining = std::chrono::milliseconds::max();
for (const auto& [key, node] : cache_) {
auto remaining = node.entry.ttl - (now - node.entry.created);
if (remaining < minRemaining) {
minRemaining = remaining;
keyToEvict = key;
}
}
break;
}
}
auto it = cache_.find(keyToEvict);
if (it != cache_.end()) {
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
cache_.erase(it);
stats_.evictions++;
return true;
}
return false;
}
void removeFromOrder(typename std::list<Key>::iterator it) {
order_.erase(it);
}
mutable std::shared_mutex mutex_;
std::unordered_map<Key, Node> cache_;
std::list<Key> order_; // For LRU/FIFO ordering
size_t maxSize_;
size_t maxMemory_ = 0;
size_t memoryUsage_ = 0;
std::chrono::milliseconds defaultTtl_;
EvictionPolicy policy_;
mutable CacheStats stats_;
};
// Type aliases for common cache types
using StringCache = LruCache<std::string, std::string>;
using HttpCache = LruCache<std::string, HttpResponse>;
using TrackCache = LruCache<std::string, TrackInfo>;
// Cache manager for multiple cache types
class CacheManager {
public:
static CacheManager& instance();
void initialize();
void shutdown();
// Get specific caches
[[nodiscard]] HttpCache& httpCache() { return httpCache_; }
[[nodiscard]] TrackCache& trackCache() { return trackCache_; }
[[nodiscard]] StringCache& metadataCache() { return metadataCache_; }
// Purge all expired entries
void purgeAllExpired();
// Clear all caches
void clearAll();
// Get combined stats
[[nodiscard]] std::unordered_map<std::string, CacheStats> getAllStats() const;
private:
CacheManager() = default;
HttpCache httpCache_{100, std::chrono::minutes(5)};
TrackCache trackCache_{500, std::chrono::hours(1)};
StringCache metadataCache_{1000, std::chrono::minutes(30)};
};
} // namespace Echoion::Api