feat(async): add EventBus injected/joined lifecycle and Observable reentrancy queue (M-ASYNC-05)

This commit is contained in:
faumaray committed 2026-12-01 10:27:50 +03:00
1 parent 1e752da590
commit ef85ce07b7
4 files changed
+2156 -288

No files matched your search

File diff suppressed because it is too large. Load diff
+221 -52
View File
@@ -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
+600
View File
@@ -0,0 +1,600 @@
#include <Void/Async/EventBus.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <coroutine>
#include <cstdint>
#include <filesystem>
#include <future>
#include <latch>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace
{
struct Ping {
int value{0};
};
[[nodiscard]] std::size_t current_thread_count()
{
std::size_t count = 0;
std::error_code ec;
for (const auto& _ :
std::filesystem::directory_iterator("/proc/self/task", ec)) {
(void)_;
++count;
}
return count;
}
[[nodiscard]] std::int32_t async_code(const Void::Result::Error& err) noexcept
{
return err.code().value;
}
} // namespace
Void::Testing::Test bus_injected_no_private_thread_manual_pumping()
{
using namespace Void::EventBus;
const std::size_t threads_before = current_thread_count();
Void::Async::ManualExecutor manual;
EventBus bus{manual};
const std::size_t threads_after = current_thread_count();
Void::Testing::expect_eq(threads_after, threads_before);
Void::Testing::expect(bus.mode() == Mode::Injected);
int sum = 0;
std::thread::id caller_id = std::this_thread::get_id();
std::thread::id seen_id{};
auto sub = bus.try_subscribe<Ping>([&](const Ping& p) {
seen_id = std::this_thread::get_id();
sum += p.value;
});
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{10}).has_value());
Void::Testing::require(bus.try_publish(Ping{25}).has_value());
Void::Testing::expect_eq(sum, 0);
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(sum, 35);
Void::Testing::expect(seen_id == caller_id);
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_injected_subscription_limit_overloaded()
{
using namespace Void::EventBus;
Void::Async::ManualExecutor manual;
EventBus bus{manual, BusOptions{.max_subscriptions = 2}};
auto s1 = bus.try_subscribe<Ping>([](const Ping&) {});
auto s2 = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::require(s1.has_value());
Void::Testing::require(s2.has_value());
auto s3 = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::require(!s3.has_value());
Void::Testing::expect_eq(
async_code(s3.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::overloaded));
s1->reset();
auto s4 = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::expect(s4.has_value());
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_injected_dispatch_limit_overloaded()
{
using namespace Void::EventBus;
Void::Async::ManualExecutor manual;
EventBus bus{manual, BusOptions{.max_admitted_dispatches = 2}};
int hits = 0;
auto sub = bus.try_subscribe<Ping>([&](const Ping& p) { hits += p.value; });
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
Void::Testing::require(bus.try_publish(Ping{2}).has_value());
auto third = bus.try_publish(Ping{3});
Void::Testing::require(!third.has_value());
Void::Testing::expect_eq(
async_code(third.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::overloaded));
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(hits, 3);
Void::Testing::require(bus.try_publish(Ping{4}).has_value());
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(hits, 7);
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_close_and_join_waits_inflight_releases_capture_tsan()
{
using namespace Void::EventBus;
auto exec_res = Void::Async::ThreadExecutor::create(
Void::Async::ThreadExecutorOptions{.workers = 2, .max_admitted = 32});
Void::Testing::require(exec_res.has_value());
auto exec = std::move(*exec_res);
Void::Testing::require(exec->start().has_value());
{
EventBus bus{*exec};
auto sentinel = std::make_shared<int>(99);
std::latch started{1};
std::promise<void> release_promise;
auto release_future = release_promise.get_future().share();
std::atomic<bool> finished{false};
auto sub = bus.try_subscribe<Ping>(
[&, sentinel](const Ping&) {
started.count_down();
release_future.wait();
finished.store(true, std::memory_order_release);
});
Void::Testing::require(sub.has_value());
Void::Testing::expect(sentinel.use_count() >= 2);
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
started.wait();
std::atomic<bool> join_done{false};
Void::Result::Result<void> join_res;
std::thread joiner([&]() {
join_res = sub->close_and_join();
join_done.store(true, std::memory_order_release);
});
std::this_thread::sleep_for(std::chrono::milliseconds{15});
Void::Testing::expect(!join_done.load(std::memory_order_acquire));
release_promise.set_value();
joiner.join();
Void::Testing::expect(join_res.has_value());
Void::Testing::expect(finished.load(std::memory_order_acquire));
Void::Testing::expect_eq(sentinel.use_count(), 1L);
Void::Testing::require(bus.close_and_join().has_value());
}
exec->close();
Void::Testing::require(exec->join().has_value());
}
Void::Testing::Test bus_unsubscribe_during_dispatch_prevents_later_admission()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
int first_hits = 0;
int second_hits = 0;
HandlerId id2 = 0;
bus.subscribe<Ping>([&](const Ping&) {
++first_hits;
bus.unsubscribe(id2);
});
id2 = bus.subscribe<Ping>([&](const Ping&) { ++second_hits; });
bus.publish(Ping{1});
Void::Testing::expect_eq(first_hits, 1);
Void::Testing::expect_eq(second_hits, 0);
bus.publish(Ping{2});
Void::Testing::expect_eq(first_hits, 2);
Void::Testing::expect_eq(second_hits, 0);
}
Void::Testing::Test bus_self_unsubscribe_ok_self_join_rejected()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
EventBus::Subscription sub;
Void::Result::Result<void> join_res;
int calls = 0;
auto sub_res = bus.try_subscribe<Ping>([&](const Ping&) {
++calls;
join_res = sub.close_and_join();
sub.reset();
});
Void::Testing::require(sub_res.has_value());
sub = std::move(*sub_res);
bus.publish(Ping{1});
bus.publish(Ping{2});
Void::Testing::expect_eq(calls, 1);
Void::Testing::require(!join_res.has_value());
Void::Testing::expect_eq(
async_code(join_res.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
Void::Testing::expect(!static_cast<bool>(sub));
}
Void::Testing::Test bus_callback_throw_to_error_sink_others_run()
{
using namespace Void::EventBus;
Void::Async::ManualExecutor manual;
std::vector<std::string> errors;
EventBus bus{
manual,
BusOptions{.error_sink = [&](std::exception_ptr ex) {
try {
if (ex) {
std::rethrow_exception(ex);
}
} catch (const std::exception& e) {
errors.emplace_back(e.what());
}
}}};
int second_hits = 0;
auto s1 = bus.try_subscribe<Ping>([](const Ping&) {
throw std::runtime_error("boom_injected");
});
auto s2 = bus.try_subscribe<Ping>([&](const Ping& p) { second_hits += p.value; });
Void::Testing::require(s1.has_value() && s2.has_value());
Void::Testing::require(bus.try_publish(Ping{9}).has_value());
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(second_hits, 9);
Void::Testing::expect_eq(bus.callback_failures(), std::uint64_t{1});
Void::Testing::require(errors.size() == 1);
Void::Testing::expect_eq(errors[0], std::string{"boom_injected"});
// Legacy Sync publish retains exception propagation.
EventBus sync_bus{Mode::Sync};
sync_bus.subscribe<Ping>([](const Ping&) { throw std::runtime_error("sync_boom"); });
bool caught = false;
try {
sync_bus.publish(Ping{1});
} catch (const std::runtime_error&) {
caught = true;
}
Void::Testing::expect(caught);
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_error_sink_throw_caught_and_counted()
{
using namespace Void::EventBus;
EventBus bus{
Mode::Async,
BusOptions{.error_sink = [](std::exception_ptr) {
throw std::runtime_error("sink_boom");
}}};
std::atomic<int> second_hits{0};
bus.subscribe<Ping>([](const Ping&) {
throw std::runtime_error("cb_boom");
});
bus.subscribe<Ping>([&](const Ping& p) {
second_hits.fetch_add(p.value, std::memory_order_relaxed);
});
Void::Testing::require(bus.try_publish(Ping{7}).has_value());
Void::Testing::require(bus.flush_blocking().has_value());
Void::Testing::expect_eq(second_hits.load(), 7);
// 1 for handler throw + 1 for throwing error_sink
Void::Testing::expect_eq(bus.callback_failures(), std::uint64_t{2});
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_legacy_async_unsubscribe_keeps_queued_copy()
{
using namespace Void::EventBus;
struct Unblock {};
EventBus bus{Mode::Async};
std::latch blocker_entered{1};
std::promise<void> release_blocker;
auto release_future = release_blocker.get_future().share();
bus.subscribe<Unblock>([&](const Unblock&) {
blocker_entered.count_down();
release_future.wait();
});
std::atomic<int> target_hits{0};
const HandlerId target_id = bus.subscribe<Ping>([&](const Ping& p) {
target_hits.fetch_add(p.value, std::memory_order_relaxed);
});
bus.publish(Unblock{});
blocker_entered.wait();
bus.publish(Ping{13});
bus.unsubscribe(target_id);
bus.publish(Ping{100});
release_blocker.set_value();
bus.flush();
Void::Testing::expect_eq(target_hits.load(), 13);
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_sync_reentrant_subscribe_unsubscribe_asan()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
int late_hits = 0;
int primary_hits = 0;
HandlerId removable_id = 0;
bus.subscribe<Ping>([&](const Ping& p) {
++primary_hits;
if (p.value == 1) {
bus.subscribe<Ping>([&](const Ping&) { ++late_hits; });
bus.unsubscribe(removable_id);
}
});
int removed_hits = 0;
removable_id = bus.subscribe<Ping>([&](const Ping&) { ++removed_hits; });
bus.publish(Ping{1});
Void::Testing::expect_eq(primary_hits, 1);
Void::Testing::expect_eq(removed_hits, 0);
Void::Testing::expect_eq(late_hits, 0);
bus.publish(Ping{2});
Void::Testing::expect_eq(primary_hits, 2);
Void::Testing::expect_eq(removed_hits, 0);
Void::Testing::expect_eq(late_hits, 1);
}
Void::Testing::Test bus_publish_after_close_closed()
{
using namespace Void::EventBus;
EventBus bus{Mode::Async};
Void::Testing::require(bus.close_and_join().has_value());
auto sub_res = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::require(!sub_res.has_value());
Void::Testing::expect_eq(
async_code(sub_res.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::closed));
auto pub_res = bus.try_publish(Ping{42});
Void::Testing::require(!pub_res.has_value());
Void::Testing::expect_eq(
async_code(pub_res.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::closed));
}
Void::Testing::Test bus_sync_unsubscribe_releases_captured_state()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
auto s1 = std::make_shared<int>(1);
const HandlerId id = bus.subscribe<Ping>([s1](const Ping&) { (void)s1; });
Void::Testing::expect_eq(s1.use_count(), 2L);
bus.unsubscribe(id);
Void::Testing::expect_eq(s1.use_count(), 1L);
auto s2 = std::make_shared<int>(2);
auto scoped = bus.try_subscribe<Ping>([s2](const Ping&) { (void)s2; });
Void::Testing::require(scoped.has_value());
Void::Testing::expect_eq(s2.use_count(), 2L);
scoped->reset();
Void::Testing::expect_eq(s2.use_count(), 1L);
}
Void::Testing::Test bus_legacy_async_unsubscribe_then_flush_releases_captured_state()
{
using namespace Void::EventBus;
struct Hold {};
EventBus bus{Mode::Async};
std::latch entered{1};
std::promise<void> rel;
auto rel_fut = rel.get_future().share();
bus.subscribe<Hold>([&](const Hold&) {
entered.count_down();
rel_fut.wait();
});
auto sentinel = std::make_shared<int>(77);
const HandlerId id = bus.subscribe<Ping>([sentinel](const Ping&) { (void)sentinel; });
bus.publish(Hold{});
entered.wait();
bus.publish(Ping{1});
bus.unsubscribe(id);
Void::Testing::expect(sentinel.use_count() >= 2L);
rel.set_value();
bus.flush();
Void::Testing::expect_eq(sentinel.use_count(), 1L);
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_legacy_async_close_and_join_releases_capture_with_queued_copies()
{
using namespace Void::EventBus;
struct Hold {};
EventBus bus{Mode::Async};
std::latch entered{1};
std::promise<void> rel;
auto rel_fut = rel.get_future().share();
bus.subscribe<Hold>([&](const Hold&) {
entered.count_down();
rel_fut.wait();
});
auto sentinel = std::make_shared<int>(88);
auto sub = bus.try_subscribe<Ping>([sentinel](const Ping&) { (void)sentinel; });
Void::Testing::require(sub.has_value());
bus.publish(Hold{});
entered.wait();
// Queue copies on the worker queue while Hold keeps worker busy.
bus.publish(Ping{1});
bus.publish(Ping{2});
Void::Testing::expect(sentinel.use_count() >= 3L);
// Must purge queued copies for sub and release captured state immediately
// without blocking on Hold or executing queued Ping callbacks.
Void::Testing::require(sub->close_and_join().has_value());
Void::Testing::expect_eq(sentinel.use_count(), 1L);
rel.set_value();
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_destructor_gates_admitted_deliveries()
{
using namespace Void::EventBus;
// 1. Queued ManualExecutor deliveries are gated when ~EventBus destroys.
{
Void::Async::ManualExecutor manual;
int delivered = 0;
{
EventBus bus{manual};
auto sub = bus.try_subscribe<Ping>([&](const Ping&) { ++delivered; });
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
Void::Testing::require(bus.try_publish(Ping{2}).has_value());
}
manual.drain();
Void::Testing::expect_eq(delivered, 0);
}
// 2. Destruction on a thread waits for OTHER thread's in-flight callback,
// gates queued unstarted work, and self-destruction in callback doesn't deadlock.
{
auto exec_res = Void::Async::ThreadExecutor::create(
Void::Async::ThreadExecutorOptions{.workers = 1, .max_admitted = 32});
Void::Testing::require(exec_res.has_value());
auto exec = std::move(*exec_res);
Void::Testing::require(exec->start().has_value());
std::atomic<int> started_count{0};
std::atomic<int> gated_count{0};
std::latch first_in_flight{1};
std::promise<void> allow_first_finish;
auto finish_fut = allow_first_finish.get_future().share();
{
std::optional<EventBus> bus{std::in_place, *exec};
auto s1 = bus->try_subscribe<Ping>([&](const Ping& p) {
if (p.value == 1) {
started_count.fetch_add(1, std::memory_order_relaxed);
first_in_flight.count_down();
finish_fut.wait();
} else {
gated_count.fetch_add(1, std::memory_order_relaxed);
}
});
Void::Testing::require(s1.has_value());
Void::Testing::require(bus->try_publish(Ping{1}).has_value());
first_in_flight.wait();
Void::Testing::require(bus->try_publish(Ping{2}).has_value());
std::atomic<bool> destroyed{false};
std::thread destroyer([&]() {
bus.reset();
destroyed.store(true, std::memory_order_release);
});
std::this_thread::sleep_for(std::chrono::milliseconds{15});
Void::Testing::expect(!destroyed.load(std::memory_order_acquire));
allow_first_finish.set_value();
destroyer.join();
}
exec->close();
Void::Testing::require(exec->join().has_value());
Void::Testing::expect_eq(started_count.load(), 1);
Void::Testing::expect_eq(gated_count.load(), 0);
}
// 3. Destroying EventBus from inside its own Sync callback doesn't deadlock.
{
std::optional<EventBus> bus{std::in_place, Mode::Sync};
int ran = 0;
bus->subscribe<Ping>([&](const Ping&) {
++ran;
bus.reset();
});
bus->publish(Ping{1});
Void::Testing::expect_eq(ran, 1);
Void::Testing::expect(!bus.has_value());
}
}
Void::Testing::Test bus_flush_blocking_self_join_and_manual_invalid()
{
using namespace Void::EventBus;
// ManualExecutor rejects flush_blocking and close_and_join with invalid_argument.
{
Void::Async::ManualExecutor manual;
EventBus bus{manual};
auto fb = bus.flush_blocking();
Void::Testing::require(!fb.has_value());
Void::Testing::expect_eq(
async_code(fb.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::invalid_argument));
auto cj = bus.close_and_join();
Void::Testing::require(!cj.has_value());
Void::Testing::expect_eq(
async_code(cj.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::invalid_argument));
}
// Executor worker thread calling flush_blocking or close_and_join gets self_join.
{
auto exec_res = Void::Async::ThreadExecutor::create(
Void::Async::ThreadExecutorOptions{.workers = 1, .max_admitted = 16});
Void::Testing::require(exec_res.has_value());
auto exec = std::move(*exec_res);
Void::Testing::require(exec->start().has_value());
EventBus bus{*exec};
std::optional<Void::Result::Result<void>> fb_res;
std::optional<Void::Result::Result<void>> cj_res;
auto sub = bus.try_subscribe<Ping>([&](const Ping&) {
fb_res = bus.flush_blocking();
cj_res = bus.close_and_join();
});
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
Void::Testing::require(bus.flush_blocking().has_value());
Void::Testing::require(fb_res.has_value() && !fb_res->has_value());
Void::Testing::expect_eq(
async_code(fb_res->error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
Void::Testing::require(cj_res.has_value() && !cj_res->has_value());
Void::Testing::expect_eq(
async_code(cj_res->error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
// Wrong executor passed to flush_pumping returns invalid_argument.
Void::Async::ManualExecutor other_manual;
auto fp = bus.flush_pumping(other_manual);
Void::Testing::require(!fp.has_value());
Void::Testing::expect_eq(
async_code(fp.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::invalid_argument));
Void::Testing::require(bus.close_and_join().has_value());
exec->close();
Void::Testing::require(exec->join().has_value());
}
}
@@ -0,0 +1,236 @@
#include <Void/Async/Observable.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <utility>
#include <vector>
namespace
{
struct MoveOnlyVal {
int id{0};
MoveOnlyVal() = default;
explicit MoveOnlyVal(int v) noexcept : id{v} {}
MoveOnlyVal(const MoveOnlyVal&) = delete;
MoveOnlyVal& operator=(const MoveOnlyVal&) = delete;
MoveOnlyVal(MoveOnlyVal&&) noexcept = default;
MoveOnlyVal& operator=(MoveOnlyVal&&) noexcept = default;
[[nodiscard]] bool operator==(const MoveOnlyVal& other) const noexcept
{
return id == other.id;
}
};
} // namespace
Void::Testing::Test observable_nested_set_fifo()
{
using namespace Void::Observable;
Observable<int> obs{0};
std::vector<std::pair<int, int>> seen;
obs.on_change([&](const int& old_v, const int& new_v) {
seen.emplace_back(old_v, new_v);
if (new_v == 1) {
obs.set(2);
Void::Testing::expect_eq(obs.get(), 2);
obs.set(3);
Void::Testing::expect_eq(obs.get(), 3);
}
});
obs.set(1);
Void::Testing::expect_eq(obs.get(), 3);
Void::Testing::require(seen.size() == 3);
Void::Testing::expect_eq(seen[0].first, 0);
Void::Testing::expect_eq(seen[0].second, 1);
Void::Testing::expect_eq(seen[1].first, 1);
Void::Testing::expect_eq(seen[1].second, 2);
Void::Testing::expect_eq(seen[2].first, 2);
Void::Testing::expect_eq(seen[2].second, 3);
}
Void::Testing::Test observable_unsubscribe_in_listener_skips_rest()
{
using namespace Void::Observable;
Observable<int> obs{0};
int second_hits = 0;
Handle second_h{};
obs.on_change([&](const int&, const int&) { obs.unsubscribe(second_h); });
second_h = obs.on_change([&](const int&, const int&) { ++second_hits; });
obs.set(1);
Void::Testing::expect_eq(second_hits, 0);
obs.set(2);
Void::Testing::expect_eq(second_hits, 0);
}
Void::Testing::Test observable_subscribe_in_listener_not_current_pass()
{
using namespace Void::Observable;
Observable<int> obs{0};
int late_hits = 0;
bool added = false;
obs.on_change([&](const int&, const int&) {
if (!added) {
added = true;
obs.on_change([&](const int&, const int&) { ++late_hits; });
}
});
obs.set(1);
Void::Testing::expect_eq(late_hits, 0);
obs.set(2);
Void::Testing::expect_eq(late_hits, 1);
}
Void::Testing::Test observable_try_set_overloaded_when_pending_full()
{
using namespace Void::Observable;
Observable<int> obs{0};
Void::Result::Result<void> overflow_res{};
bool overflow_checked = false;
obs.on_change([&](const int&, const int& new_v) {
if (new_v == 1) {
for (std::size_t i = 0; i < kMaxPendingNotifications; ++i) {
auto r = obs.try_set(static_cast<int>(i + 2));
if (!r.has_value()) {
overflow_checked = false;
return;
}
}
const int val_before_overload = obs.get();
overflow_res = obs.try_set(999999);
Void::Testing::expect_eq(obs.get(), val_before_overload);
// Overflow via set() updates value and increments dropped_notifications.
obs.set(888888);
Void::Testing::expect_eq(obs.get(), 888888);
overflow_checked = true;
}
});
obs.set(1);
Void::Testing::expect(overflow_checked);
Void::Testing::require(!overflow_res.has_value());
Void::Testing::expect_eq(
overflow_res.error().code().value,
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::overloaded));
Void::Testing::expect_eq(obs.get(), 888888);
Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{1});
}
Void::Testing::Test observable_listener_throw_restores_state()
{
using namespace Void::Observable;
Observable<int> obs{0};
int normal_hits = 0;
obs.on_change([&](const int&, const int& new_v) {
if (new_v == 1) {
obs.set(2);
obs.set(3);
throw std::runtime_error("listener_boom");
}
++normal_hits;
});
bool caught = false;
try {
obs.set(1);
} catch (const std::runtime_error&) {
caught = true;
}
Void::Testing::expect(caught);
Void::Testing::expect_eq(obs.get(), 3);
Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{2});
// Subsequent set operates cleanly with depth restored to 0.
obs.set(4);
Void::Testing::expect_eq(obs.get(), 4);
Void::Testing::expect_eq(normal_hits, 1);
}
Void::Testing::Test observable_self_unsubscribe_releases_capture()
{
using namespace Void::Observable;
Observable<int> obs{0};
auto sentinel = std::make_shared<int>(55);
Handle h{};
h = obs.on_change([&, sentinel](const int&, const int&) {
(void)sentinel;
Void::Testing::expect(obs.unsubscribe(h));
});
Void::Testing::expect_eq(sentinel.use_count(), 2L);
obs.set(1);
Void::Testing::expect_eq(sentinel.use_count(), 1L);
Void::Testing::expect_eq(obs.listener_count(), std::size_t{0});
}
Void::Testing::Test observable_move_only_immediate_notification_compat()
{
using namespace Void::Observable;
Observable<MoveOnlyVal> obs{MoveOnlyVal{0}};
std::vector<std::pair<int, int>> trace;
obs.on_change([&](const MoveOnlyVal& ov, const MoveOnlyVal& nv) {
trace.emplace_back(ov.id, nv.id);
if (nv.id == 1) {
obs.set(MoveOnlyVal{2});
}
});
obs.on_change([&](const MoveOnlyVal& ov, const MoveOnlyVal& nv) {
trace.emplace_back(ov.id * 10, nv.id * 10);
});
obs.set(MoveOnlyVal{1});
// Immediate recursive delivery matches 1.x notify(old, value_) aliasing.
Void::Testing::require(trace.size() == 4);
Void::Testing::expect_eq(trace[0].first, 0);
Void::Testing::expect_eq(trace[0].second, 1);
Void::Testing::expect_eq(trace[1].first, 1);
Void::Testing::expect_eq(trace[1].second, 2);
Void::Testing::expect_eq(trace[2].first, 10);
Void::Testing::expect_eq(trace[2].second, 20);
Void::Testing::expect_eq(trace[3].first, 0);
Void::Testing::expect_eq(trace[3].second, 20);
Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{0});
}
Void::Testing::Test signal_reentrant_connect_disconnect_during_emit()
{
using namespace Void::Observable;
Signal<int> sig;
std::vector<int> log;
Handle second_h{};
Handle third_h{};
sig.connect([&](const int& v) {
log.push_back(v);
if (v == 1) {
Void::Testing::expect(sig.disconnect(second_h));
third_h = sig.connect([&](const int& x) { log.push_back(x * 100); });
sig.emit(2);
}
});
second_h = sig.connect([&](const int& v) { log.push_back(v * 10); });
sig.emit(1);
// First emit skips disconnected second_h and skips newly added third_h;
// queued emit(2) runs first slot and third_h FIFO.
Void::Testing::require(log.size() == 3);
Void::Testing::expect_eq(log[0], 1);
Void::Testing::expect_eq(log[1], 2);
Void::Testing::expect_eq(log[2], 200);
Void::Testing::expect(third_h.id != 0);
}