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:
1 parent
43b5a81504
commit
80293ee56f
93 files changed
+8500
-3312
No files matched your search
+193
-58
@@ -1,8 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <any>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -10,72 +15,202 @@
|
||||
namespace Void::EventBus
|
||||
{
|
||||
|
||||
// ── EventBus ──────────────────────────────────────────────────────────────────
|
||||
// Synchronous publish/subscribe bus keyed by event type.
|
||||
// Handlers are invoked on the caller's thread inside publish().
|
||||
// Not thread-safe; use external locking if shared across threads.
|
||||
// ── EventBus
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Publish/subscribe bus keyed by event type.
|
||||
//
|
||||
// Mode::Sync (default) handlers run inline on the publisher's thread
|
||||
// inside
|
||||
// publish() — the original zero-overhead behavior.
|
||||
// Mode::Async publish() snapshots the handlers and a copy of
|
||||
// the
|
||||
// event onto an owned worker thread, so slow
|
||||
// handlers (network / DB I/O) never block the
|
||||
// publisher. flush() waits for everything submitted
|
||||
// before the call.
|
||||
//
|
||||
// In Sync mode the bus is not thread-safe (use external locking if shared).
|
||||
// In Async mode publish/subscribe/flush are safe to call from any thread.
|
||||
|
||||
class EventBus
|
||||
{
|
||||
public:
|
||||
using HandlerId = std::size_t;
|
||||
enum class Mode { Sync, Async };
|
||||
|
||||
// Subscribe to events of type Event. Returns a HandlerId for unsubscription.
|
||||
template <typename Event>
|
||||
HandlerId subscribe(std::function<void(const Event&)> handler)
|
||||
{
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
const HandlerId id = next_id_++;
|
||||
handlers_[key].push_back(Entry{id, [h = std::move(handler)](const std::any& ev) {
|
||||
h(std::any_cast<const Event&>(ev));
|
||||
}});
|
||||
return id;
|
||||
}
|
||||
class EventBus
|
||||
{
|
||||
public:
|
||||
|
||||
// Publish an event to all subscribers of its type.
|
||||
template <typename Event>
|
||||
void publish(const Event& event)
|
||||
{
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) return;
|
||||
for (const auto& e : it->second) e.fn(event);
|
||||
}
|
||||
using HandlerId = std::size_t;
|
||||
|
||||
// Unsubscribe by id. O(n) per event type — acceptable for small handler counts.
|
||||
void unsubscribe(HandlerId id)
|
||||
{
|
||||
for (auto& [key, list] : handlers_) {
|
||||
const auto before = list.size();
|
||||
std::erase_if(list, [id](const Entry& e) { return e.id == id; });
|
||||
if (list.size() != before) return;
|
||||
}
|
||||
}
|
||||
explicit EventBus(Mode mode = Mode::Sync) : mode_(mode)
|
||||
{
|
||||
if (mode_ == Mode::Async) {
|
||||
worker_ = std::thread([this] { run(); });
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all handlers for a given event type.
|
||||
template <typename Event>
|
||||
void clear()
|
||||
{
|
||||
handlers_.erase(std::type_index{typeid(Event)});
|
||||
}
|
||||
~EventBus()
|
||||
{
|
||||
if (mode_ == Mode::Async) {
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
stop_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
worker_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void clear_all() { handlers_.clear(); }
|
||||
EventBus(const EventBus&) = delete;
|
||||
EventBus& operator=(const EventBus&) = delete;
|
||||
EventBus(EventBus&&) = delete;
|
||||
EventBus& operator=(EventBus&&) = delete;
|
||||
|
||||
template <typename Event>
|
||||
[[nodiscard]] std::size_t subscriber_count() const
|
||||
{
|
||||
const auto it = handlers_.find(std::type_index{typeid(Event)});
|
||||
return it == handlers_.end() ? 0 : it->second.size();
|
||||
}
|
||||
// Subscribe to events of type Event. Returns a HandlerId for
|
||||
// unsubscription.
|
||||
template <typename Event>
|
||||
HandlerId subscribe(std::function<void(const Event&)> handler)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
const HandlerId id = next_id_++;
|
||||
handlers_[key].push_back(
|
||||
Entry{id, [h = std::move(handler)](const std::any& ev) {
|
||||
h(std::any_cast<const Event&>(ev));
|
||||
}});
|
||||
return id;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
HandlerId id;
|
||||
std::function<void(const std::any&)> fn;
|
||||
};
|
||||
// Publish an event to all subscribers of its type.
|
||||
template <typename Event> void publish(const Event& event)
|
||||
{
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
if (mode_ == Mode::Sync) {
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) {
|
||||
return;
|
||||
}
|
||||
for (const auto& e : it->second) {
|
||||
e.fn(event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
|
||||
HandlerId next_id_{1};
|
||||
};
|
||||
// Async: snapshot the current handlers and queue a dispatch
|
||||
// carrying a copy of the event, so later unsubscribe()s don't
|
||||
// affect this publish.
|
||||
std::unique_lock lock{mu_};
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::function<void(const std::any&)>> snapshot;
|
||||
snapshot.reserve(it->second.size());
|
||||
for (const auto& e : it->second) {
|
||||
snapshot.push_back(e.fn);
|
||||
}
|
||||
tasks_.push([snap = std::move(snapshot), ev = std::any{event}] {
|
||||
for (const auto& fn : snap) {
|
||||
fn(ev);
|
||||
}
|
||||
});
|
||||
++enqueued_;
|
||||
lock.unlock();
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
// Async only: block until every event published before this call
|
||||
// has been dispatched. A no-op in Sync mode (delivery already
|
||||
// happened in publish()).
|
||||
void flush()
|
||||
{
|
||||
if (mode_ != Mode::Async) {
|
||||
return;
|
||||
}
|
||||
std::unique_lock lock{mu_};
|
||||
const auto target = enqueued_;
|
||||
done_cv_.wait(lock, [&] { return processed_ >= target; });
|
||||
}
|
||||
|
||||
// Unsubscribe by id. O(n) per event type — acceptable for small
|
||||
// handler counts.
|
||||
void unsubscribe(HandlerId id)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
for (auto& [key, list] : handlers_) {
|
||||
const auto before = list.size();
|
||||
std::erase_if(list,
|
||||
[id](const Entry& e) { return e.id == id; });
|
||||
if (list.size() != before) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all handlers for a given event type.
|
||||
template <typename Event> void clear()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
handlers_.erase(std::type_index{typeid(Event)});
|
||||
}
|
||||
|
||||
void clear_all()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
handlers_.clear();
|
||||
}
|
||||
|
||||
template <typename Event>
|
||||
[[nodiscard]] std::size_t subscriber_count() const
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
const auto it = handlers_.find(std::type_index{typeid(Event)});
|
||||
return it == handlers_.end() ? 0 : it->second.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] Mode mode() const noexcept { return mode_; }
|
||||
|
||||
private:
|
||||
|
||||
struct Entry {
|
||||
HandlerId id;
|
||||
std::function<void(const std::any&)> fn;
|
||||
};
|
||||
|
||||
void run()
|
||||
{
|
||||
for (;;) {
|
||||
std::function<void()> task;
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
cv_.wait(lock,
|
||||
[this] { return stop_ || !tasks_.empty(); });
|
||||
if (stop_ && tasks_.empty()) {
|
||||
return;
|
||||
}
|
||||
task = std::move(tasks_.front());
|
||||
tasks_.pop();
|
||||
}
|
||||
task();
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
++processed_;
|
||||
}
|
||||
done_cv_.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
Mode mode_;
|
||||
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
|
||||
HandlerId next_id_{1};
|
||||
|
||||
mutable std::mutex mu_;
|
||||
// Async machinery (unused in Sync mode).
|
||||
std::thread worker_;
|
||||
std::queue<std::function<void()>> tasks_;
|
||||
std::condition_variable cv_;
|
||||
std::condition_variable done_cv_;
|
||||
std::uint64_t enqueued_{0};
|
||||
std::uint64_t processed_{0};
|
||||
bool stop_{false};
|
||||
};
|
||||
|
||||
} // namespace Void::EventBus
|
||||
Reference in new issue
Block a user