Add Async lock-free infrastructure and reflection JSON serializer

Async (Void::Async):
- MpscQueue<T>: unbounded Vyukov multi-producer/single-consumer queue.
  Wait-free push (XCHG + store, no CAS loop); consumer-owned reclamation so
  no hazard pointers and no ABA. The transient mid-link empty window is
  documented; try_pop/empty are re-poll hints.
- Executor/ManualExecutor: minimal scheduling bridge for Coro::Task with
  lock-free post() from any thread and single-thread run_one()/drain();
  schedule_on() awaitable and spawn() for detached task launch with a
  self-destroying wrapper frame.

Data (Void::Json):
- Reflect.hpp: P2996 to_json/from_json for aggregate structs (field-name
  keys; arithmetic/bool/string/enum-by-name/vector/optional/string-map/
  nested aggregates), tolerant deserialization (unknown fields ignored,
  missing fields keep defaults, mismatches report dotted field paths).
- Versioned envelopes {"__version", "data"} with StateTraits<T> and
  MigrationChain for stepwise schema upgrades - groundwork for plugin
  hot-reload state transfer.
- Member to_json/from_json customization wins over reflection and is the
  only path on compilers without <meta> (Reflectable is false there).

Verified with GCC 16.1 (-freflection): 25 new tests including an
8-producer x 100k MPSC stress with per-producer FIFO assertion, coroutine
frame lifetime checks, and a 3-step v1->v3 migration; suite green under
ASan+UBSan.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-12 18:57:15 +03:00
1 parent 28b94883fd
commit 8a6065539a
6 files changed
+1150

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
#pragma once
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <coroutine>
#include <cstddef>
#include <exception>
namespace Void::Async
{
// ── Executor ──────────────────────────────────────────────────────────────────
// Minimal scheduling interface bridging Coro::Task to a driving thread.
// post() must be safe to call from any thread.
class Executor
{
public:
virtual ~Executor() = default;
// Schedule a coroutine for resumption on this executor. Thread-safe.
virtual void post(std::coroutine_handle<> handle) = 0;
};
// ── ManualExecutor ────────────────────────────────────────────────────────────
// An executor whose queue is drained explicitly by its owning thread.
// post() is lock-free from any thread; run_one()/drain() must only be
// called from a single consumer thread (typically the owner's loop).
class ManualExecutor final : public Executor
{
public:
void post(std::coroutine_handle<> handle) override
{
queue_.push(handle);
}
// Resume one pending coroutine. Returns false if none was pending.
bool run_one()
{
auto h = queue_.try_pop();
if (!h) {
return false;
}
h->resume();
return true;
}
// Resume pending coroutines until the queue drains. Returns how many
// coroutines were resumed (including ones posted while draining).
std::size_t drain()
{
std::size_t count = 0;
while (run_one()) {
++count;
}
return count;
}
[[nodiscard]] bool empty() const noexcept { return queue_.empty(); }
private:
MpscQueue<std::coroutine_handle<>> queue_;
};
// ── schedule_on ───────────────────────────────────────────────────────────────
// Awaitable that re-schedules the awaiting coroutine onto an executor:
//
// co_await schedule_on(executor); // resumes on the executor's thread
struct ScheduleAwaiter {
Executor& executor;
[[nodiscard]] bool await_ready() const noexcept { return false; }
void await_suspend(std::coroutine_handle<> h) const { executor.post(h); }
void await_resume() const noexcept {}
};
[[nodiscard]] inline ScheduleAwaiter schedule_on(Executor& executor)
{
return ScheduleAwaiter{executor};
}
// ── spawn ─────────────────────────────────────────────────────────────────────
// Launch a Task<void> detached, driven on the given executor. The wrapper
// coroutine owns the task; its frame self-destroys on completion. An
// exception escaping the task terminates (there is no awaiter to receive
// it) — handle errors inside the task.
namespace Detail
{
struct DetachedTask {
struct promise_type {
DetachedTask get_return_object() noexcept { return {}; }
std::suspend_never initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() noexcept {}
void unhandled_exception() noexcept { std::terminate(); }
};
};
inline DetachedTask spawn_impl(Executor& executor, Coro::Task<void> task)
{
co_await schedule_on(executor);
co_await std::move(task);
}
} // namespace Detail
inline void spawn(Executor& executor, Coro::Task<void> task)
{
Detail::spawn_impl(executor, std::move(task));
}
} // namespace Void::Async
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#include <atomic>
#include <optional>
#include <utility>
namespace Void::Async
{
// ── MpscQueue<T> ──────────────────────────────────────────────────────────────
// Unbounded multi-producer / single-consumer queue (Vyukov scheme).
//
// push() — any thread; wait-free (one exchange + one store, no CAS loop).
// try_pop() — exactly ONE consumer thread; lock-free.
//
// Memory reclamation is trivial by construction: only the consumer ever
// dereferences and frees popped nodes, so there are no hazard pointers, no
// epochs, and no ABA window (no compare-and-swap on shared nodes at all).
//
// Known Vyukov subtlety: a producer can be preempted between swapping the
// tail and linking the previous node's `next`. During that window the chain
// is transiently broken and try_pop() reports the queue as empty even though
// later-pushed items exist. Callers must treat empty() / nullopt as a hint
// and re-poll; items are never lost.
//
// The queue carries no blocking facility by design — consumers that need to
// sleep when idle pair it with a std::binary_semaphore (see ManualExecutor
// and the Fsm worker for the pattern).
template <typename T>
class MpscQueue
{
public:
MpscQueue() : head_{new Node{}}, tail_{head_} {}
MpscQueue(const MpscQueue&) = delete;
MpscQueue& operator=(const MpscQueue&) = delete;
MpscQueue(MpscQueue&&) = delete;
MpscQueue& operator=(MpscQueue&&) = delete;
~MpscQueue()
{
// No concurrent access is permitted during destruction.
Node* n = head_;
while (n) {
Node* next = n->next.load(std::memory_order_relaxed);
delete n;
n = next;
}
}
// Enqueue from any thread. Wait-free.
void push(T value)
{
Node* node = new Node{std::move(value)};
Node* prev = tail_.exchange(node, std::memory_order_acq_rel);
// A consumer scanning right now sees prev->next == nullptr and
// treats the queue as empty until this store lands (see above).
prev->next.store(node, std::memory_order_release);
}
// Dequeue. Must only ever be called from one consumer thread.
// Returns nullopt when the queue is empty *or* a producer is mid-link.
[[nodiscard]] std::optional<T> try_pop()
{
Node* head = head_;
Node* next = head->next.load(std::memory_order_acquire);
if (!next) {
return std::nullopt;
}
std::optional<T> result{std::move(*next->value)};
next->value.reset();
head_ = next;
delete head;
return result;
}
// Consumer-side emptiness hint; racy when observed from other threads.
[[nodiscard]] bool empty() const noexcept
{
return head_->next.load(std::memory_order_acquire) == nullptr;
}
private:
struct Node {
Node() = default;
explicit Node(T v) : value{std::move(v)} {}
std::atomic<Node*> next{nullptr};
std::optional<T> value{}; // disengaged only in the stub node
};
Node* head_; // consumer-owned; always the consumed stub
std::atomic<Node*> tail_; // producers swap themselves in here
};
} // namespace Void::Async
+423
View File
@@ -0,0 +1,423 @@
#pragma once
#include <Void/Data/Json.hpp>
#include <Void/Detail/Enum.hpp>
#include <concepts>
#include <cstdint>
#include <expected>
#include <functional>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
#if __has_include(<meta>)
#include <meta>
#define VOID_HAS_JSON_REFLECTION 1
#endif
// ── Reflection → JSON ─────────────────────────────────────────────────────────
// Serialize/deserialize aggregate structs to Json::Value using C++26 P2996
// reflection (GCC 16+, -freflection). Field names become object keys.
//
// Customization: a type providing
// Json::Value to_json() const;
// static std::expected<T, ReflectError> from_json(const Json::Value&);
// always wins over reflection — and is the only path on compilers without
// <meta>, where the Reflectable concept is false.
//
// Deserialization tolerance (the backward/forward-compat contract):
// * unknown JSON fields are ignored
// * missing fields keep the default-initialized member value
// * a present field with the wrong JSON type is an error
//
// Versioned envelopes for hot-reload state migration:
// to_versioned_json(s) -> {"__version": N, "data": {...}}
// from_versioned_json<T> -> runs a MigrationChain when the stored
// version is older than StateTraits<T>::version.
namespace Void::Json
{
struct ReflectError {
std::string field; // dotted path of the offending field ("" if global)
std::string message;
};
// ── customization point ───────────────────────────────────────────────────────
template <typename T>
concept HasMemberToJson = requires(const T& t) {
{ t.to_json() } -> std::same_as<Value>;
};
template <typename T>
concept HasMemberFromJson = requires(const Value& v) {
{ T::from_json(v) } -> std::same_as<std::expected<T, ReflectError>>;
};
// ── supported leaf / container shapes ─────────────────────────────────────────
namespace ReflectDetail
{
template <typename T>
struct IsOptional : std::false_type {};
template <typename U>
struct IsOptional<std::optional<U>> : std::true_type {};
template <typename T>
struct IsVector : std::false_type {};
template <typename U>
struct IsVector<std::vector<U>> : std::true_type {};
template <typename T>
struct IsStringMap : std::false_type {};
template <typename U>
struct IsStringMap<std::map<std::string, U>> : std::true_type {};
} // namespace ReflectDetail
#ifdef VOID_HAS_JSON_REFLECTION
template <typename T>
concept ReflectableAggregate =
std::is_aggregate_v<T> && !std::is_array_v<T> &&
std::is_default_constructible_v<T>;
#else
template <typename T>
concept ReflectableAggregate = false;
#endif
template <typename T>
concept JsonConvertible =
HasMemberToJson<T> || std::same_as<T, bool> || std::is_arithmetic_v<T> ||
std::is_enum_v<T> || std::same_as<T, std::string> ||
ReflectDetail::IsOptional<T>::value || ReflectDetail::IsVector<T>::value ||
ReflectDetail::IsStringMap<T>::value || ReflectableAggregate<T>;
// Anything serializable through this header (customized or reflected).
template <typename T>
concept Reflectable = JsonConvertible<T>;
// ── to_json ───────────────────────────────────────────────────────────────────
template <Reflectable T>
[[nodiscard]] Value to_json(const T& v);
namespace ReflectDetail
{
template <typename T>
Value leaf_to_json(const T& v)
{
if constexpr (HasMemberToJson<T>) {
return v.to_json();
}
else if constexpr (std::same_as<T, bool>) {
return Value{v};
}
else if constexpr (std::is_enum_v<T>) {
#ifdef VOID_HAS_ENUM_REFLECTION
// Enum values serialize by name — stable across binary versions.
return Value{Void::Detail::enum_name(v)};
#else
return Value{static_cast<double>(
static_cast<std::underlying_type_t<T>>(v))};
#endif
}
else if constexpr (std::is_arithmetic_v<T>) {
return Value{static_cast<double>(v)};
}
else if constexpr (std::same_as<T, std::string>) {
return Value{v};
}
else if constexpr (IsOptional<T>::value) {
return v ? Json::to_json(*v) : Value{nullptr};
}
else if constexpr (IsVector<T>::value) {
auto arr = Json::array();
arr.as_array().reserve(v.size());
for (const auto& e : v) {
arr.as_array().push_back(Json::to_json(e));
}
return arr;
}
else if constexpr (IsStringMap<T>::value) {
auto obj = Json::object();
for (const auto& [k, e] : v) {
obj.as_object().emplace_back(k, Json::to_json(e));
}
return obj;
}
else {
static_assert(ReflectableAggregate<T>,
"type is not serializable via Json reflection");
#ifdef VOID_HAS_JSON_REFLECTION
auto obj = Json::object();
static constexpr auto members = std::define_static_array(
std::meta::nonstatic_data_members_of(
^^T, std::meta::access_context::current()));
template for (constexpr auto m : members) {
obj.as_object().emplace_back(
std::string{std::meta::identifier_of(m)},
Json::to_json(v.[:m:]));
}
return obj;
#endif
}
}
} // namespace ReflectDetail
template <Reflectable T>
[[nodiscard]] Value to_json(const T& v)
{
return ReflectDetail::leaf_to_json(v);
}
// ── from_json ─────────────────────────────────────────────────────────────────
template <Reflectable T>
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j);
namespace ReflectDetail
{
[[nodiscard]] inline ReflectError nest(std::string_view field,
ReflectError inner)
{
if (inner.field.empty()) {
inner.field = std::string{field};
}
else {
inner.field = std::string{field} + "." + inner.field;
}
return inner;
}
template <typename T>
std::expected<T, ReflectError> leaf_from_json(const Value& j)
{
if constexpr (HasMemberFromJson<T>) {
return T::from_json(j);
}
else if constexpr (std::same_as<T, bool>) {
if (!j.is_bool()) {
return std::unexpected{ReflectError{"", "expected bool"}};
}
return j.as_bool();
}
else if constexpr (std::is_enum_v<T>) {
#ifdef VOID_HAS_ENUM_REFLECTION
if (!j.is_string()) {
return std::unexpected{
ReflectError{"", "expected enum name string"}};
}
auto parsed = Void::Detail::enum_parse<T>(j.as_string());
if (!parsed) {
return std::unexpected{ReflectError{
"", "unknown enumerator '" + j.as_string() + "'"}};
}
return *parsed;
#else
if (!j.is_number()) {
return std::unexpected{
ReflectError{"", "expected enum number"}};
}
return static_cast<T>(
static_cast<std::underlying_type_t<T>>(j.as_number()));
#endif
}
else if constexpr (std::is_arithmetic_v<T>) {
if (!j.is_number()) {
return std::unexpected{ReflectError{"", "expected number"}};
}
return static_cast<T>(j.as_number());
}
else if constexpr (std::same_as<T, std::string>) {
if (!j.is_string()) {
return std::unexpected{ReflectError{"", "expected string"}};
}
return j.as_string();
}
else if constexpr (IsOptional<T>::value) {
using U = typename T::value_type;
if (j.is_null()) {
return T{std::nullopt};
}
auto inner = Json::from_json<U>(j);
if (!inner) {
return std::unexpected{std::move(inner).error()};
}
return T{std::move(*inner)};
}
else if constexpr (IsVector<T>::value) {
using U = typename T::value_type;
if (!j.is_array()) {
return std::unexpected{ReflectError{"", "expected array"}};
}
T out;
out.reserve(j.as_array().size());
std::size_t index = 0;
for (const auto& e : j.as_array()) {
auto inner = Json::from_json<U>(e);
if (!inner) {
return std::unexpected{nest(
"[" + std::to_string(index) + "]",
std::move(inner).error())};
}
out.push_back(std::move(*inner));
++index;
}
return out;
}
else if constexpr (IsStringMap<T>::value) {
using U = typename T::mapped_type;
if (!j.is_object()) {
return std::unexpected{ReflectError{"", "expected object"}};
}
T out;
for (const auto& [k, e] : j.as_object()) {
auto inner = Json::from_json<U>(e);
if (!inner) {
return std::unexpected{nest(k, std::move(inner).error())};
}
out.emplace(k, std::move(*inner));
}
return out;
}
else {
static_assert(ReflectableAggregate<T>,
"type is not deserializable via Json reflection");
#ifdef VOID_HAS_JSON_REFLECTION
if (!j.is_object()) {
return std::unexpected{ReflectError{"", "expected object"}};
}
T out{};
static constexpr auto members = std::define_static_array(
std::meta::nonstatic_data_members_of(
^^T, std::meta::access_context::current()));
std::optional<ReflectError> failure;
template for (constexpr auto m : members) {
if (!failure) {
constexpr auto name = std::meta::identifier_of(m);
using MT = [:std::meta::type_of(m):];
if (const Value* field = j.find(name)) {
auto inner = Json::from_json<MT>(*field);
if (!inner) {
failure = nest(name, std::move(inner).error());
}
else {
out.[:m:] = std::move(*inner);
}
}
// absent field: keep the default-initialized value
}
}
if (failure) {
return std::unexpected{std::move(*failure)};
}
return out;
#endif
}
}
} // namespace ReflectDetail
template <Reflectable T>
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j)
{
return ReflectDetail::leaf_from_json<T>(j);
}
// ── versioned envelope + migrations ───────────────────────────────────────────
// Specialize to bump a state type's schema version:
// template <> struct Void::Json::StateTraits<MyState> {
// static constexpr std::uint32_t version = 3;
// };
template <typename T>
struct StateTraits {
static constexpr std::uint32_t version = 1;
};
// Ordered chain of per-version JSON transforms. Each step upgrades the bare
// "data" payload from `from_version` to `from_version + 1`.
class MigrationChain
{
public:
using Step = std::function<Value(Value)>;
MigrationChain& add(std::uint32_t from_version, Step step)
{
steps_.emplace(from_version, std::move(step));
return *this;
}
[[nodiscard]] std::expected<Value, ReflectError>
migrate(Value data, std::uint32_t from, std::uint32_t to) const
{
while (from < to) {
auto it = steps_.find(from);
if (it == steps_.end()) {
return std::unexpected{ReflectError{
"__version", "no migration step from version " +
std::to_string(from)}};
}
data = it->second(std::move(data));
++from;
}
return data;
}
[[nodiscard]] bool empty() const noexcept { return steps_.empty(); }
private:
std::map<std::uint32_t, Step> steps_;
};
template <Reflectable T>
[[nodiscard]] Value to_versioned_json(const T& v)
{
auto envelope = object();
envelope.as_object().emplace_back(
"__version", Value{static_cast<double>(StateTraits<T>::version)});
envelope.as_object().emplace_back("data", to_json(v));
return envelope;
}
template <Reflectable T>
[[nodiscard]] std::expected<T, ReflectError>
from_versioned_json(const Value& envelope,
const MigrationChain& migrations = {})
{
if (!envelope.is_object()) {
return std::unexpected{ReflectError{"", "expected envelope object"}};
}
const Value* version = envelope.find("__version");
const Value* data = envelope.find("data");
if (!version || !version->is_number() || !data) {
return std::unexpected{
ReflectError{"__version", "malformed versioned envelope"}};
}
const auto from = static_cast<std::uint32_t>(version->as_number());
constexpr auto to = StateTraits<T>::version;
if (from > to) {
return std::unexpected{ReflectError{
"__version", "stored version " + std::to_string(from) +
" is newer than supported version " +
std::to_string(to)}};
}
if (from == to) {
return from_json<T>(*data);
}
auto migrated = migrations.migrate(*data, from, to);
if (!migrated) {
return std::unexpected{std::move(migrated).error()};
}
return from_json<T>(*migrated);
}
} // namespace Void::Json