feat(async): add EventBus injected/joined lifecycle and Observable reentrancy queue (M-ASYNC-05)
This commit is contained in:
1 parent
1e752da590
commit
ef85ce07b7
4 files changed
+2156
-288
No files matched your search
+1099
-236
File diff suppressed because it is too large.
Load diff
@@ -1,45 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Observable
|
||||
{
|
||||
|
||||
// ── Handle — opaque subscription identifier ───────────────────────────────────
|
||||
inline constexpr std::size_t kMaxPendingNotifications = 1024;
|
||||
|
||||
struct Handle
|
||||
{
|
||||
struct Handle {
|
||||
std::uint64_t id{0};
|
||||
[[nodiscard]] bool valid() const noexcept { return id != 0; }
|
||||
[[nodiscard]] bool operator==(const Handle&) const noexcept = default;
|
||||
};
|
||||
|
||||
// ── Observable<T> ─────────────────────────────────────────────────────────────
|
||||
// A value that observers can subscribe to via on_change().
|
||||
// Observers receive (old_value, new_value) on every set() call that changes
|
||||
// the stored value.
|
||||
namespace detail
|
||||
{
|
||||
struct EmptyQueue {};
|
||||
} // namespace detail
|
||||
|
||||
/// Observable value container holding a T and notifying listeners on change.
|
||||
/// Single-threaded (not thread-safe across threads), reentrancy-safe:
|
||||
/// - Copyable T: nested set() updates the value immediately and queues (old, new)
|
||||
/// notifications FIFO after the active pass (bounded at kMaxPendingNotifications).
|
||||
/// - Move-only T: 1.x immediate recursive notification over a listener snapshot.
|
||||
template <typename T>
|
||||
class Observable
|
||||
{
|
||||
public:
|
||||
using Listener = std::function<void(const T& old_val, const T& new_val)>;
|
||||
|
||||
explicit Observable(T initial = {}) : value_{std::move(initial)} {}
|
||||
explicit Observable(T initial = {})
|
||||
: value_{std::move(initial)}
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] const T& get() const noexcept { return value_; }
|
||||
[[nodiscard]] operator const T&() const noexcept { return value_; }
|
||||
|
||||
void set(T new_val)
|
||||
{
|
||||
if (new_val == value_) return;
|
||||
if (new_val == value_) {
|
||||
return;
|
||||
}
|
||||
T old = std::move(value_);
|
||||
value_ = std::move(new_val);
|
||||
notify(old, value_);
|
||||
if constexpr (std::copy_constructible<T>) {
|
||||
if (dispatch_depth_ > 0) {
|
||||
if (pending_.size() < kMaxPendingNotifications) {
|
||||
pending_.emplace_back(std::move(old), value_);
|
||||
} else {
|
||||
++dropped_notifications_;
|
||||
}
|
||||
return;
|
||||
}
|
||||
dispatch_fifo(std::move(old), value_);
|
||||
} else {
|
||||
notify_snapshot(old, value_);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded reentrant update for copyable T: returns overloaded without
|
||||
/// modifying value_ if the nested notification queue is full.
|
||||
[[nodiscard]] Void::Result::Result<void> try_set(T new_val)
|
||||
requires std::copy_constructible<T>
|
||||
{
|
||||
if (new_val == value_) {
|
||||
return {};
|
||||
}
|
||||
if (dispatch_depth_ > 0 &&
|
||||
pending_.size() >= kMaxPendingNotifications) {
|
||||
return std::unexpected{Void::Async::make_async_error(
|
||||
Void::Async::AsyncErrorCode::overloaded,
|
||||
"Observable pending notification queue full")};
|
||||
}
|
||||
set(std::move(new_val));
|
||||
return {};
|
||||
}
|
||||
|
||||
Observable& operator=(T new_val)
|
||||
@@ -48,21 +95,26 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
Handle on_change(Listener listener)
|
||||
Handle on_change(Listener fn)
|
||||
{
|
||||
const Handle h{++next_id_};
|
||||
listeners_.push_back({h, std::move(listener)});
|
||||
const Handle h{next_id_++};
|
||||
auto entry = std::make_shared<Entry>(Entry{h, true, std::move(fn)});
|
||||
listeners_.push_back(std::move(entry));
|
||||
return h;
|
||||
}
|
||||
|
||||
bool unsubscribe(Handle h)
|
||||
{
|
||||
const auto it =
|
||||
std::ranges::find_if(listeners_,
|
||||
[&](const auto& e) { return e.h == h; });
|
||||
if (it == listeners_.end()) return false;
|
||||
listeners_.erase(it);
|
||||
return true;
|
||||
for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
|
||||
if ((*it)->handle == h) {
|
||||
(*it)->active = false;
|
||||
auto dropped = std::move((*it)->fn);
|
||||
listeners_.erase(it);
|
||||
dropped = {};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t listener_count() const noexcept
|
||||
@@ -70,52 +122,141 @@ public:
|
||||
return listeners_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
void notify(const T& old_val, const T& new_val)
|
||||
[[nodiscard]] std::size_t dropped_notifications() const noexcept
|
||||
{
|
||||
for (auto& [h, fn] : listeners_) fn(old_val, new_val);
|
||||
return dropped_notifications_;
|
||||
}
|
||||
|
||||
T value_;
|
||||
std::uint64_t next_id_{0};
|
||||
|
||||
struct Entry
|
||||
{
|
||||
Handle h;
|
||||
Listener fn;
|
||||
private:
|
||||
struct Entry {
|
||||
Handle handle{0};
|
||||
bool active{true};
|
||||
Listener fn{};
|
||||
};
|
||||
std::vector<Entry> listeners_;
|
||||
|
||||
void notify_snapshot(const T& old_val, const T& new_val) const
|
||||
{
|
||||
auto snapshot = listeners_;
|
||||
for (const auto& entry : snapshot) {
|
||||
if (!entry->active || !entry->fn) {
|
||||
continue;
|
||||
}
|
||||
auto fn = entry->fn;
|
||||
fn(old_val, new_val);
|
||||
fn = {};
|
||||
}
|
||||
}
|
||||
|
||||
void dispatch_fifo(T first_old, T first_new)
|
||||
requires std::copy_constructible<T>
|
||||
{
|
||||
dispatch_depth_ = 1;
|
||||
try {
|
||||
notify_snapshot(first_old, first_new);
|
||||
while (!pending_.empty()) {
|
||||
auto next = std::move(pending_.front());
|
||||
pending_.pop_front();
|
||||
notify_snapshot(next.first, next.second);
|
||||
}
|
||||
} catch (...) {
|
||||
dropped_notifications_ += pending_.size();
|
||||
pending_.clear();
|
||||
dispatch_depth_ = 0;
|
||||
throw;
|
||||
}
|
||||
dispatch_depth_ = 0;
|
||||
}
|
||||
|
||||
using QueueType = std::conditional_t<
|
||||
std::copy_constructible<T>,
|
||||
std::deque<std::pair<T, T>>,
|
||||
detail::EmptyQueue>;
|
||||
|
||||
T value_;
|
||||
std::vector<std::shared_ptr<Entry>> listeners_{};
|
||||
QueueType pending_{};
|
||||
std::size_t dispatch_depth_{0};
|
||||
std::size_t dropped_notifications_{0};
|
||||
std::uint64_t next_id_{1};
|
||||
};
|
||||
|
||||
// ── Signal<Args...> ───────────────────────────────────────────────────────────
|
||||
// An event signal that observers connect to. emit() calls all connected slots.
|
||||
|
||||
/// Typed multi-slot signal.
|
||||
/// Single-threaded (not thread-safe across threads), reentrancy-safe:
|
||||
/// snapshots connected slots and queues nested emit() calls FIFO when all
|
||||
/// decayed Args are copy-constructible (bounded at kMaxPendingNotifications).
|
||||
template <typename... Args>
|
||||
class Signal
|
||||
{
|
||||
public:
|
||||
using Slot = std::function<void(const Args&...)>;
|
||||
|
||||
Handle connect(Slot slot)
|
||||
Handle connect(Slot fn)
|
||||
{
|
||||
const Handle h{++next_id_};
|
||||
slots_.push_back({h, std::move(slot)});
|
||||
const Handle h{next_id_++};
|
||||
auto entry = std::make_shared<Entry>(Entry{h, true, std::move(fn)});
|
||||
slots_.push_back(std::move(entry));
|
||||
return h;
|
||||
}
|
||||
|
||||
bool disconnect(Handle h)
|
||||
{
|
||||
const auto it =
|
||||
std::ranges::find_if(slots_,
|
||||
[&](const auto& e) { return e.h == h; });
|
||||
if (it == slots_.end()) return false;
|
||||
slots_.erase(it);
|
||||
return true;
|
||||
for (auto it = slots_.begin(); it != slots_.end(); ++it) {
|
||||
if ((*it)->handle == h) {
|
||||
(*it)->active = false;
|
||||
auto dropped = std::move((*it)->fn);
|
||||
slots_.erase(it);
|
||||
dropped = {};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void clear() noexcept
|
||||
{
|
||||
auto all = std::move(slots_);
|
||||
slots_.clear();
|
||||
for (auto& e : all) {
|
||||
e->active = false;
|
||||
e->fn = {};
|
||||
}
|
||||
}
|
||||
|
||||
void emit(const Args&... args) const
|
||||
{
|
||||
for (const auto& [h, fn] : slots_) fn(args...);
|
||||
constexpr bool kAllCopyable =
|
||||
(std::copy_constructible<std::decay_t<Args>> && ...);
|
||||
if constexpr (kAllCopyable) {
|
||||
if (dispatch_depth_ > 0) {
|
||||
if (pending_.size() < kMaxPendingNotifications) {
|
||||
pending_.emplace_back(args...);
|
||||
} else {
|
||||
++dropped_notifications_;
|
||||
}
|
||||
return;
|
||||
}
|
||||
dispatch_depth_ = 1;
|
||||
try {
|
||||
emit_snapshot(args...);
|
||||
while (!pending_.empty()) {
|
||||
auto next = std::move(pending_.front());
|
||||
pending_.pop_front();
|
||||
std::apply(
|
||||
[this](const auto&... packed) {
|
||||
emit_snapshot(packed...);
|
||||
},
|
||||
next);
|
||||
}
|
||||
} catch (...) {
|
||||
dropped_notifications_ += pending_.size();
|
||||
pending_.clear();
|
||||
dispatch_depth_ = 0;
|
||||
throw;
|
||||
}
|
||||
dispatch_depth_ = 0;
|
||||
} else {
|
||||
emit_snapshot(args...);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t slot_count() const noexcept
|
||||
@@ -123,17 +264,45 @@ public:
|
||||
return slots_.size();
|
||||
}
|
||||
|
||||
void clear() noexcept { slots_.clear(); }
|
||||
[[nodiscard]] std::size_t dropped_notifications() const noexcept
|
||||
{
|
||||
return dropped_notifications_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::uint64_t next_id_{0};
|
||||
|
||||
struct Entry
|
||||
{
|
||||
Handle h;
|
||||
Slot fn;
|
||||
struct Entry {
|
||||
Handle handle{0};
|
||||
bool active{true};
|
||||
Slot fn{};
|
||||
};
|
||||
std::vector<Entry> slots_;
|
||||
|
||||
void emit_snapshot(const Args&... args) const
|
||||
{
|
||||
auto snapshot = slots_;
|
||||
for (const auto& entry : snapshot) {
|
||||
if (!entry->active || !entry->fn) {
|
||||
continue;
|
||||
}
|
||||
auto fn = entry->fn;
|
||||
fn(args...);
|
||||
fn = {};
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr bool kCopyableArgs =
|
||||
(std::copy_constructible<std::decay_t<Args>> && ...);
|
||||
|
||||
using TupleType = std::tuple<std::decay_t<Args>...>;
|
||||
using QueueType = std::conditional_t<
|
||||
kCopyableArgs,
|
||||
std::deque<TupleType>,
|
||||
detail::EmptyQueue>;
|
||||
|
||||
std::vector<std::shared_ptr<Entry>> slots_{};
|
||||
mutable QueueType pending_{};
|
||||
mutable std::size_t dispatch_depth_{0};
|
||||
mutable std::size_t dropped_notifications_{0};
|
||||
std::uint64_t next_id_{1};
|
||||
};
|
||||
|
||||
} // namespace Void::Observable
|
||||
Reference in new issue
Block a user