diff --git a/CLAUDE.md b/CLAUDE.md index a34b47b..c97470e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,7 +34,7 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules** | Module | Type | Contents | |---|---|---| -| `Core` | INTERFACE | Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant | +| `Core` | INTERFACE | **Meta** (shared reflection layer), Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant | | `Functional` | INTERFACE | Pipeline (+Curry, +Memo), Either (+Opt), Result, Retry | | `Containers` | INTERFACE | Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval | | `Math` | INTERFACE | Vec/Mat, Matrix, Numeric, Random, Histogram | @@ -53,6 +53,23 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules** `include/Void/Detail/` (e.g. `Enum.hpp` — P2996 enum reflection) is not a module; it is header-only and reachable from every module via the shared include root. +### Reflection layer (`Void::Meta`, `include/Void/Core/Meta.hpp`) + +The single shared C++26 P2996 layer the whole codebase reflects through. Header-only, in `Core`: +- **Shape traits (one source):** `is_optional_v`, `is_vector_v`, `is_string_map_v`, `is_duration_v`, `Leaf`, `Struct` — the trait sets that used to be duplicated in `Data/Reflect.hpp` and `Configuration/Bind.hpp` now live here. +- **Member walk:** `members_v` (the one `nonstatic_data_members_of` + `define_static_array`), `field_count()`, `field_names()`, `for_each_field(obj, fn)`, `type_name()`. +- **Annotations:** `Str` (a *value-based fixed-capacity string* — annotation payloads can't be `std::string_view`/`const char*`, which aren't structural), `has_annotation(member)`, `annotation_of(member)`. **Member annotations work; enumerator annotations do not parse in this GCC** (so enum labels stay identifier-based). +- **Generic algorithms:** `equal`/`compare`/`hash` (member-folded, recursive) and `repr` (formatter → `.format()` → reflected `Type{a: 1, …}`). `Functional/Detail/Repr.hpp` is now a thin alias over `Meta::repr`. +- **Enum utilities (extend `Detail/Enum.hpp`):** `enum_name`/`enum_parse`/`enum_cast` (re-exported) plus `enum_count`, `enum_values()`, `enum_entries()`. + +**Annotation vocabularies** (small structs over `Meta::Str`, used as `[[= ns::Tag{…}]]`): +- `Json::Rename{"k"}` / `Json::Skip` / `Json::Required` / `Json::Flatten` (`Data/Reflect.hpp`). +- `Configuration::Key{"k"}` / `Configuration::Required` (`Bind.hpp`). +- `Argparse::Short{'v'}` / `Help{"…"}` / `Name{"…"}` / `Positional` (`Argparse.hpp`). +- `Fsm::entry` (FSM entry designation). + +**Other reflective consumers:** `Data/Csv.hpp` maps a flat struct to/from a CSV `Row` (`header_row()`, `to_row`, `from_row`); `Logging::FieldScope::from(struct)` reflects a struct's fields into structured log fields; `Core/Flags.hpp` renders/parses a flag set by enumerator name (`Flags::to_string`/`parse` via `enum_entries`); `Containers/Debug.hpp` `debug_dump(range)` renders elements via `repr`; `Service::interface_name()` gives a reflected default service name; the FSM `entry` marker now goes through `Meta::has_annotation`. Non-aggregate structs (e.g. `Math::Vec3`) reflect for read (`repr`/`equal`/`hash`) via `Meta` even though they're excluded from the aggregate-only JSON path; aggregates like `Semver::Version` are JSON-reflectable directly. + ### Module system `cmake/Module.cmake` defines `void_add_module(NAME ...)`. The root `CMakeLists.txt` auto-discovers every subdirectory under `src/` and calls it (or includes the dir's `module.cmake` if present), then calls `void_finalize_modules()`. A module with only headers becomes an `INTERFACE` library; one with `.cpp` sources becomes `SHARED` — except `Testing`, which is special-cased to `STATIC`. @@ -82,29 +99,51 @@ All tests compile into **one binary**, `build/tests/VoidTests` (registered as th #### Writing a test -Tests are free functions (or methods on a `Void::Testing::Fixture` subclass) returning `Void::Testing::Test` or `Void::Testing::DisabledTest` (both aliases for `void`). **Never write the registration code yourself** — `cmake/VoidTestScanner.cmake` parses each `.cpp` at configure time, generates `*.void_tests.cpp` shims with `Void::Testing::Detail::test_registrar` calls, and rewrites the original source to `HEADER_FILE_ONLY`. +The primary model is a **reflection-based suite** (`Void/Testing/Suite.hpp`): +derive a struct from `Void::Testing::Suite` (CRTP). Every public, +0-argument member returning `Void::Testing::Test`/`DisabledTest` (both `void`) — +except `setup`/`teardown` — is auto-registered by reflecting the struct. **No +macros, no CMake scan, no registrar line, no instance**: a `[[gnu::used]]` static +in the base forces registration at program start, even though the suite is never +constructed for its own sake. Metadata is **annotations** (reuse `Meta::Str`): ```cpp #include -#include +#include -Void::Testing::Test addition() { Void::Testing::expect_eq(1 + 1, 2); } - -// @tag integration, database -Void::Testing::Test db_query() { Void::Testing::expect(true); } - -// @skip "Feature #42 not implemented" -Void::Testing::DisabledTest broken() { Void::Testing::fail("not ready"); } +namespace { +struct MathTests : Void::Testing::Suite { + void setup() {} // optional, per-test + Void::Testing::Test addition() { Void::Testing::expect_eq(1 + 1, 2); } + [[= Void::Testing::tag("integration")]] Void::Testing::Test db() { /*…*/ } + [[= Void::Testing::skip("Feature #42")]] Void::Testing::Test wip() { /*…*/ } +}; +} ``` -Fixture-based tests work the same way — declare a class derived from `Void::Testing::Fixture`, override `setup()`/`teardown()`, and write methods returning `Test`/`DisabledTest`. +- Suite label = the struct's name; override with `[[= Testing::name("Math")]]` on the struct. +- `[[= Testing::tag("x")]]` (repeatable) attaches tags; `[[= Testing::skip("reason")]]` disables a test (replaces `DisabledTest` + `@skip`). +- `setup()`/`teardown()` run around each test method (fresh instance per test) — the reflection-discovered replacement for the old `Fixture` base. File/line come from `std::meta::source_location_of`. -Comment metadata (immediately preceding the function): -- `// @tag a, b, c` — attaches tags. -- `// @skip ` — marks the test skipped with a reason; quoted or unquoted strings both work. `DisabledTest` implies `@skip "disabled"` if no explicit reason is given. -- Any non-comment, non-empty line resets the accumulated tags/skip — keep the comment block adjacent to the function. +Global-namespace reflection ICEs this GCC and an `#include` can't be namespace-wrapped, so tests must live in a *named* struct — hence the CRTP `Suite` wrapper rather than bare free functions. -The sweep in `cmake/VoidTesting.cmake` auto-applies the scan to every executable that transitively links `Void::Testing`. To opt a target out, set the `VOID_TESTING_NO_AUTO_SCAN` property; to opt in explicitly (e.g. for a target that doesn't link `Void::Testing` directly), call `void_add_tests()`. +**Scanner (permanent fallback).** Free-function tests +(`Void::Testing::Test name()` with `// @tag`/`// @skip` comments) are still +picked up by `cmake/VoidTestScanner.cmake`, which generates `*.void_tests.cpp` +shims (the original `.cpp` is `HEADER_FILE_ONLY`). This path is **kept as a +fallback** — both for compilers without `` and for tests written in the +old free-function style. The two models coexist with no migration required: a +`Suite`-only file produces an empty shim and self-registers via reflection (the +scanner always emits a valid `#include` of the source), while free-function files +register through the scanner. Use `Suite` for new tests; existing free-function +files keep working as-is. + +**Mock reflection** (`Void/TestingMock/Reflect.hpp`): `method_names()` lists an +interface's virtual methods; `covers()` is a compile-time check that a +hand-written mock implements all of `I`. Full auto-mock (synthesizing the virtual +overrides) is **not possible** here — `` has `define_aggregate` (it can +generate a `MockFunction` member per virtual) but no code injection for the +override bodies, so `MockFunction` members are still wired up by hand. ### Logging @@ -134,7 +173,7 @@ Other key points: ### Configuration module -`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as` / `get_or_as` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind(cfg, prefix)` fills an aggregate via P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`). +`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as` / `get_or_as` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind(cfg, prefix)` fills an aggregate via `Void::Meta` (defaults = schema); members may carry `[[= Configuration::Key{"…"}]]` (key override) / `[[= Configuration::Required{}]]` (error if absent). `Argparse.hpp` also offers reflective `parse(argc, argv)` — define an options struct, annotate fields (`arg::Short`/`Help`/`Name`/`Positional`), parse straight into it (bool→flag, string→option w/ default, optional→option) — alongside the fluent `Parser`. `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`). ### Service module @@ -147,32 +186,31 @@ Other key points: ### Fsm module (inheritance + coroutine workflow) -`Void::Fsm::Machine` (CRTP) — derive it; declare states as nested structs deriving the **single** base `State`. There is no statechart/event-graph; states drive themselves. +`Void::Fsm::Machine` (CRTP) — derive it. Declare the states as a nested struct of forward declarations, `struct States { struct First; struct Second; … };`, each deriving the **single** base `State`; **realise them out-of-line** (typically in a `.cpp`: `struct M::States::First : M::State { Coro::Task> run(){…} };`). The base **auto-registers** them by reflecting `members_of(^^States)` — the first declared state is the initial one unless `using Initial = States::S;`. There is no statechart/event-graph and **no declarative transition table**: states drive themselves and handle events imperatively. Define the constructor out-of-line, after the realisations, so the states are complete when the base registers them. **One `State`, signature-inferred roles.** There is one base class; the engine infers what each state does **purely from member signatures** via P2996 (`Detail/Roles.hpp`) — no `override`, no framework-mandated names: -- **entry** — a member returning `Step`/`Coro::Task` with no params (`Task run()`); a **startup-entry** overload takes the launch data (`Task run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor). -- **reactive** — a member taking `TransitionBuilder&` (`void transitions(TransitionBuilder& on)`); the engine runs its declared table. -- **continuation handlers** — two members distinguished by parameter type, `ok(ChildSuccess auto s)` / `no(ChildFailure auto f)` (`s.value`/`f.value` are the sub's typed Success/Failure); the engine picks by the launched sub's outcome. +- **entry** — a member returning `State`/`Coro::Task>` with no params (`Task run()`); a **startup-entry** overload takes the launch data (`Task run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor). Events are awaited imperatively in the entry (`co_await await_event()`). The nullary `run()` and the startup overload `run(Cfg)` coexist: the overload is chosen when the machine is launched with data (`startMachine<…>(cfg)`), the nullary entry otherwise. When several members match the entry signature, the one annotated `[[= Void::Fsm::entry]]` wins; unannotated, the first-declared match is used. +- **continuation handlers** — two members distinguished by parameter type, `ok(ChildSuccess s)` / `no(ChildFailure f)`; the sub's typed Success/Failure rides type-erased in the result struct and is read with `s.as()`/`f.as()` (`ChildSuccess`/`ChildFailure` are concrete types, no `auto`). The engine picks by the launched sub's outcome. -Mechanics: at `add()` a `Detail::make_driver()` reflection thunk is stored (reactive table vs entry, chosen by whether `S` has a `TransitionBuilder&` member); `drive()` calls the thunk. `startMachine(data…)` (knows `Sub`, `Next`, and the data types) builds a `Launch` step carrying a launcher (runs `Sub`, injecting `data` into its initial state's startup-entry) and a dispatcher (`Detail::dispatch_result`) that builds `ChildSuccessBox<…>`/`ChildFailureBox<…>` and calls `Next`'s matching handler. The reflection selectors must **not** be coroutines (`template for` + member splicing fails inside a coroutine body in this GCC build), so they `return` a `Task` (wrapping plain `Step` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**. +Mechanics: at `add()` a `Detail::make_driver()` reflection thunk (runs the entry) is stored; `drive()` calls the thunk. State-list reflection lives in `Detail/StateList.hpp` (`register_states_from`, `FirstStateOf`/`InitialStateOf`, `states_contains` for the `next()` / `startMachine<,Next>` compile-time target check). `startMachine(data…)` (knows `Sub`, `Next`, and the data types) builds a `Launch` step carrying a launcher (runs `Sub`, injecting `data` into its initial state's startup-entry) and a dispatcher (`Detail::dispatch_result`) that wraps the sub's outcome in a type-erased `ChildSuccess`/`ChildFailure` (value in a `std::any`, read via `.as()`) and calls `Next`'s matching handler. The reflection selectors must **not** be coroutines (`template for` + member splicing fails inside a coroutine body in this GCC build), so they `return` a `Task` (wrapping plain `State` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**. Machine-level entry/exit are overridable virtuals `on_machine_enter()`/`on_machine_exit()`; per-state entry/exit are the state's own `on_enter()`/`on_exit()`. **Typed results.** A machine declares its result types as nested types *reflected by name* — `struct Success {…}` (or `using Success = int;`) and `struct Failure {…}`, each defaulting to `void`. `Outcome = std::expected` (a void failure becomes `std::monostate`); `succeed(Success{…})` / `fail(Failure{…})` carry them (nullary when void). Engine/system faults (no initial state, jump to an unregistered state, a state with no entry) are a **separate `FsmError` channel** — `status()==Faulted`, `system_error()` returns the `FsmError`, never the typed `Failure`. Because `Derived` is incomplete at CRTP base instantiation, the engine stores outcomes type-erased and rebuilds the typed `Outcome` in `wait()`/`run_blocking()` (function templates defaulted on `Derived`); `Detail::SuccessOf`/`FailureOf` resolve the nested types by plain name lookup (`Detail/Result.hpp`). -Header layout (include `` — a thin umbrella): `Machine.hpp` (the `Machine` template + `States<>`, the single nested `State` base, lifecycle, events, nesting, persistence); `Detail/Roles.hpp` (the signature-inference: `ChildSuccess`/`ChildFailure` concepts + boxes, `invoke_entry`/`invoke_startup`/`invoke_handler`/`dispatch_result`/`make_driver`/`has_transitions`); `Detail/Result.hpp` (`SuccessOf`/`FailureOf`/`OutcomeOf`); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable` templates); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase` — only `on_enter`/`on_exit` remain virtual); `Detail/TypeName.hpp` (`type_name()`). +Header layout (include `` — a thin umbrella): `Machine.hpp` (the `Machine` template, the single nested `State` base, lifecycle, events, nesting, persistence); `Detail/StateList.hpp` (state-list reflection over the nested `struct States`: `register_states_from`, `FirstStateOf`/`InitialStateOf`, `states_contains`); `Detail/Roles.hpp` (the signature-inference: `ChildSuccess`/`ChildFailure` result structs, the `entry` annotation marker, `invoke_entry`/`invoke_startup`/`invoke_handler`/`dispatch_result`/`make_driver`); `Detail/Result.hpp` (`SuccessOf`/`FailureOf`/`OutcomeOf`); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Introspect.hpp` (`StateInfo` + node-level `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase` — only `on_enter`/`on_exit` remain virtual); `Detail/TypeName.hpp` (`type_name()`). - **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests). - **Events**: `co_await await_event()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post(e)` is lock-free from any thread. - **Nesting**: `co_await run_child(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected`) — the imperative form, branch on it yourself. -- **Sub-machine continuations (declarative)**: `co_return startMachine(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue` takes a nullary `on_success()`). `Next` must derive `Continue` (a `static_assert` enforces it) and be in `States<>`. A `Continue` handler may itself return another `startMachine` (chaining) or any normal `Step`. Mechanics: a `Step::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's `resume()` (overridden by `Continue`) dispatches — a plain state entered with a pending result just `run()`s. +- **Sub-machine continuations (declarative)**: `co_return startMachine(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue` takes a nullary `on_success()`). `Next` must derive `Continue` (a `static_assert` enforces it) and be in `States<>`. A continuation handler may itself return another `startMachine` (chaining) or any normal `State`. `Next` must be in `States{…}` (compile-time checked). Mechanics: a `State::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's bound dispatcher routes it to the matching `ok`/`no` handler — a plain state entered with no pending result just runs its entry. - **Parallel / orthogonal regions**: `co_await run_parallel()` runs several sub-machines concurrently on the shared executor (interleaved — when one parks on an event, another runs; **multi-waiter mailbox**) and joins **all**, yielding `std::tuple`. `run_parallel_any<…>()` resolves on the **first** to finish → `std::variant<…::Outcome…>`; losers keep running cooperatively (not preemptible), so they're kept alive by the spawned tasks until they finish — a loser parked forever leaks its frame until the machine stops. Children are default-constructed and share events/services. Join uses a small latch coroutine (`Async::spawn` + a completion counter); single-consumer ⇒ no lock. - **Composite sub-states (hierarchy)**: `co_await run_region()` is `run_child` with introspection — the calling state's `on_enter`/`on_exit` wrap the child region, and the parent's `state_path()` reports the parent→child chain (`{Composite, …child leaf}`) while it runs. Map the child's `Outcome` to a sibling transition (`r ? next() : next()`). Parent-level multi-event handling via `co_await await_any()` → `std::variant` (e.g. a region waits for `Tick` or `Cancel` at one level). Coroutines aren't preemptible mid-flight, so child cancellation is **cooperative**: the region awaits a shared `Cancel` event (events route to the deepest awaiter) and returns a failing `Outcome` the parent maps — no frame is abandoned. - **Dynamic**: `add()` / `add_if(cond)`; `next` fails; `has_state()` lets a state branch. - **Direct control**: fluent `send(e1, e2, …)` (variadic `post`); free in-state jumps via `goto_state()` (any registered state, no declared transition); external `jump()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove()` / `set_initial()` / `replace()`. - **Services**: `set_services(registry)`; `state.service()` resolves through the injected context. - **Observation**: `current_state()` is a lock-free atomic-index read of an immutable name table (P2996 `identifier_of`, fallback to indexed names). `state_path()` is the same but appends an active `run_region` child's path — consumer-consistent (read it from within the machine or once settled; deterministic in `pump()` mode). -- **Reactive DSL extras**: `on.defer()` holds event `E` while in the state and re-posts it after the next transition (UML deferred events) instead of dropping it; `on.enter(fn)` / `on.exit(fn)` are entry/exit actions run by the reactive loop; `on.event().internal(fn)` handles `E` (runs `fn`) **without** leaving the state (no exit/enter/transition). -- **Introspection**: `describe()` lists registered states (name, reactive?, initial?) plus the transitions declared by reactive states (event/target names, guard-present); imperative `run()`-chosen edges aren't statically knowable so those states are edgeless nodes. `to_mermaid()` renders a `stateDiagram-v2` string. -- **Error policies / middleware**: state helpers `delay(d)`, `with_retry(times, backoff, attempt)` (retries a `Coro::Task` sub-step), `next_or(step)` (route a failing `Step` to a fallback state). `add_interceptor({before(Transition), after(state_name)})` runs ordered hooks around each transition; `observe(fn)` is the single read-only observer. +- **Event idioms (all imperative)**: timeout — `co_await await_event_for(d)` (→ `optional`, `nullopt` on timeout) or `delay(d)`; multi-event — `co_await await_any()` → `std::variant`; guard — a plain `if` after the await; internal/self transition — a `for(;;)` loop in the entry that handles events without returning (or `next()`); **deferred events are automatic** — the typed mailbox buffers any event a state doesn't await, so a later state consumes it (nothing is dropped, no `defer` declaration needed). +- **Introspection**: `describe()` lists registered states (name, initial?). Transitions are chosen imperatively inside each entry and aren't statically knowable, so the description is **node-level** — `to_mermaid()` renders a `stateDiagram-v2` string with the initial marker plus one node per state (no edges). +- **Error policies / middleware**: state helpers `delay(d)`, `with_retry(times, backoff, attempt)` (retries a `Coro::Task` sub-step), `next_or(step)` (route a failing `State` to a fallback state). `add_interceptor({before(Transition), after(state_name)})` runs ordered hooks around each transition; `observe(fn)` is the single read-only observer. - **Persistence**: `serialize()` → `{state name, on_serialize data}`; `restore()` on an un-started machine resumes at the named state (override `on_serialize`/`on_restore` for derived data, reflection-JSON friendly). - Hot-plug + state-saving are re-expressed via services: plugins provide `IService` impls; `PluginServiceBinding` swaps the registry entry on reload (state migrated by the plugin's v2 ABI), so running FSMs pick up the new impl on the next `service()` call without being patched. diff --git a/cmake/VoidTestScanner.cmake b/cmake/VoidTestScanner.cmake index bc158da..7ea1f9e 100644 --- a/cmake/VoidTestScanner.cmake +++ b/cmake/VoidTestScanner.cmake @@ -4,6 +4,11 @@ endif() file(STRINGS ${INPUT_FILE} lines) +# Forward-slash path for C++ string literals / #include (always set, so files +# whose tests are all reflection-registered Suite<> structs still emit a valid +# include of the original .cpp). +string(REPLACE "\\" "/" INPUT_FILE_FORWARD "${INPUT_FILE}") + set(registrations "") set(in_fixture_class FALSE) set(fixture_class_name "") diff --git a/include/Void/Async/EventBus.hpp b/include/Void/Async/EventBus.hpp index c4daae6..d12edca 100644 --- a/include/Void/Async/EventBus.hpp +++ b/include/Void/Async/EventBus.hpp @@ -1,8 +1,13 @@ #pragma once #include +#include #include +#include #include +#include +#include +#include #include #include #include @@ -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 - HandlerId subscribe(std::function 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(ev)); - }}); - return id; - } + class EventBus + { + public: - // Publish an event to all subscribers of its type. - template - 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 - 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 - [[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 + HandlerId subscribe(std::function 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(ev)); + }}); + return id; + } -private: - struct Entry { - HandlerId id; - std::function fn; - }; + // Publish an event to all subscribers of its type. + template 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> 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> 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 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 + [[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 fn; + }; + + void run() + { + for (;;) { + std::function 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> handlers_; + HandlerId next_id_{1}; + + mutable std::mutex mu_; + // Async machinery (unused in Sync mode). + std::thread worker_; + std::queue> 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 diff --git a/include/Void/Async/ThreadPool.hpp b/include/Void/Async/ThreadPool.hpp index 922f362..0e4ff2c 100644 --- a/include/Void/Async/ThreadPool.hpp +++ b/include/Void/Async/ThreadPool.hpp @@ -1,11 +1,14 @@ #pragma once #include +#include #include +#include #include #include #include #include #include +#include #include #include #include @@ -18,15 +21,30 @@ namespace Void::Concurrency { public: + // A snapshot of throughput / backpressure counters. + struct Stats { + std::uint64_t submitted = + 0; // tasks accepted onto the queue + std::uint64_t completed = 0; // tasks finished running + std::uint64_t rejected = 0; // try_submit refusals (full) + std::size_t pending = 0; // tasks currently queued + }; + + // `max_queue == 0` keeps the queue unbounded (the historical + // behavior). A non-zero bound makes submit() block for space and + // try_submit() reject when the queue is full. explicit ThreadPool( - std::size_t n = std::thread::hardware_concurrency()) + std::size_t n = std::thread::hardware_concurrency(), + std::size_t max_queue = 0) + : max_queue_{max_queue} { const std::size_t count = (n > 0) ? n : 1; workers_.reserve(count); for (std::size_t i = 0; i < count; ++i) { workers_.emplace_back([this] { worker_loop(); }); } - Void::Log::debug("Concurrency", "ThreadPool: started with {} threads", count); + Void::Log::debug("Concurrency", + "ThreadPool: started with {} threads", count); } ~ThreadPool() @@ -37,6 +55,7 @@ namespace Void::Concurrency stop_ = true; } cv_.notify_all(); + not_full_.notify_all(); for (auto& w : workers_) { w.join(); } @@ -47,6 +66,8 @@ namespace Void::Concurrency ThreadPool(ThreadPool&&) = delete; ThreadPool& operator=(ThreadPool&&) = delete; + // Enqueue a task. On a bounded pool this blocks until the queue has + // space (backpressure); on an unbounded pool it never blocks. template auto submit(F&& f) -> std::future> { @@ -56,12 +77,43 @@ namespace Void::Concurrency auto fut = task->get_future(); { std::unique_lock lock{mu_}; + if (max_queue_ > 0) { + not_full_.wait(lock, [this] { + return stop_ || queue_.size() < max_queue_; + }); + } if (stop_) { throw std::runtime_error( "Void::Concurrency::ThreadPool: submit after " "shutdown"); } - queue_.push([task] { (*task)(); }); + push_locked(task); + } + cv_.notify_one(); + return fut; + } + + // Non-blocking enqueue. Returns nullopt when a bounded queue is + // full (recording a rejection) or after shutdown; otherwise the + // future. + template + auto try_submit(F&& f) + -> std::optional>> + { + using R = std::invoke_result_t; + auto task = std::make_shared>( + std::forward(f)); + auto fut = task->get_future(); + { + std::unique_lock lock{mu_}; + if (stop_) { + return std::nullopt; + } + if (max_queue_ > 0 && queue_.size() >= max_queue_) { + rejected_.fetch_add(1, std::memory_order_relaxed); + return std::nullopt; + } + push_locked(task); } cv_.notify_one(); return fut; @@ -78,8 +130,29 @@ namespace Void::Concurrency return queue_.size(); } + [[nodiscard]] Stats stats() const + { + std::unique_lock lock{mu_}; + return Stats{ + submitted_.load(std::memory_order_relaxed), + completed_.load(std::memory_order_relaxed), + rejected_.load(std::memory_order_relaxed), + queue_.size(), + }; + } + private: + template + void push_locked(std::shared_ptr> task) + { + queue_.push([this, task] { + (*task)(); + completed_.fetch_add(1, std::memory_order_relaxed); + }); + submitted_.fetch_add(1, std::memory_order_relaxed); + } + void worker_loop() { for (;;) { @@ -94,14 +167,22 @@ namespace Void::Concurrency task = std::move(queue_.front()); queue_.pop(); } + if (max_queue_ > 0) { + not_full_.notify_one(); + } task(); } } + std::size_t max_queue_; std::vector workers_; std::queue> queue_; mutable std::mutex mu_; std::condition_variable cv_; + std::condition_variable not_full_; + std::atomic submitted_{0}; + std::atomic completed_{0}; + std::atomic rejected_{0}; bool stop_{false}; }; diff --git a/include/Void/Configuration/Argparse.hpp b/include/Void/Configuration/Argparse.hpp index a758ce1..9d817c7 100644 --- a/include/Void/Configuration/Argparse.hpp +++ b/include/Void/Configuration/Argparse.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -9,54 +11,156 @@ namespace Void::Argparse { -// ── Parser ──────────────────────────────────────────────────────────────────── -// Fluent command-line argument parser. -// -// Supports: -// --flag, -f boolean flag (default false, set to true by presence) -// --key=value option with value (= or space separator) -// --key value option with value -// positional args collected in declaration order -// --help / -h auto-generated help text + // ── Parser + // ──────────────────────────────────────────────────────────────────── + // Fluent command-line argument parser. + // + // Supports: + // --flag, -f boolean flag (default false, set to true by + // presence) + // --key=value option with value (= or space separator) + // --key value option with value + // positional args collected in declaration order + // --help / -h auto-generated help text -class Parser -{ -public: - explicit Parser(std::string program, std::string description = {}); + class Parser + { + public: - // Add a boolean flag. - // long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name may be "") - Parser& flag(std::string_view long_name, std::string_view short_name, - std::string_view description, bool& out); + explicit Parser(std::string program, std::string description = {}); - // Add an option that takes a value. If not provided, out stays nullopt. - Parser& option(std::string_view long_name, std::string_view short_name, - std::string_view description, std::optional& out); + // Add a boolean flag. + // long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name + // may be "") + Parser& flag(std::string_view long_name, + std::string_view short_name, + std::string_view description, bool& out); - // Add an option with a default value. out is always set after parse(). - Parser& option_default(std::string_view long_name, std::string_view short_name, - std::string_view description, std::string& out, - std::string_view default_value = ""); + // Add an option that takes a value. If not provided, out stays + // nullopt. + Parser& option(std::string_view long_name, + std::string_view short_name, + std::string_view description, + std::optional& out); - // Add a required positional argument. - Parser& positional(std::string_view name, std::string_view description, std::string& out); + // Add an option with a default value. out is always set after + // parse(). + Parser& option_default(std::string_view long_name, + std::string_view short_name, + std::string_view description, + std::string& out, + std::string_view default_value = ""); - // Parse argc/argv. Returns error message on failure. - [[nodiscard]] std::expected - parse(int argc, const char* const* argv) const; + // Add a required positional argument. + Parser& positional(std::string_view name, + std::string_view description, std::string& out); - // Returns formatted help text. - [[nodiscard]] std::string help() const; + // Parse argc/argv. Returns error message on failure. + [[nodiscard]] std::expected + parse(int argc, const char* const* argv) const; -private: - struct FlagEntry { std::string lng, sht, desc; bool* out; }; - struct OptionEntry{ std::string lng, sht, desc, def; std::optional* out_opt; std::string* out_str; }; - struct PosEntry { std::string name, desc; std::string* out; }; + // Returns formatted help text. + [[nodiscard]] std::string help() const; - std::string program_, description_; - std::vector flags_; - std::vector options_; - std::vector positionals_; -}; + private: + + struct FlagEntry { + std::string lng, sht, desc; + bool* out; + }; + struct OptionEntry { + std::string lng, sht, desc, def; + std::optional* out_opt; + std::string* out_str; + }; + struct PosEntry { + std::string name, desc; + std::string* out; + }; + + std::string program_, description_; + std::vector flags_; + std::vector options_; + std::vector positionals_; + }; + + // ── reflective options struct + // ───────────────────────────────────────────────── Define a struct, + // annotate its fields, and parse straight into it: + // + // struct Opts { + // [[= arg::Short{'v'}]] [[= arg::Help{"verbose output"}]] bool + // verbose = false; + // [[= arg::Help{"output path"}]] std::string + // out = "a.out"; std::optional config; // --config + // + // [[= arg::Positional{}]] std::string input; + // }; + // auto o = Argparse::parse(argc, argv); // std::expected + // + // Field → argument: bool → flag, std::string → option with default (the + // field's initializer), std::optional → optional option, a + // field tagged + // [[= arg::Positional]] → positional. Other field types are ignored. + + struct Short { + char c; + }; + struct Help { + Void::Meta::Str text; + }; + struct Name { + Void::Meta::Str text; + }; // long-name override (without "--") + struct Positional { + }; + +#ifdef VOID_HAS_META_REFLECTION + + template + [[nodiscard]] std::expected + parse(int argc, const char* const* argv, std::string program = "app", + std::string description = {}) + { + Opts out{}; + Parser parser{std::move(program), std::move(description)}; + + template for (constexpr auto m : Void::Meta::members_v) + { + using MT = [:std::meta::type_of(m):]; + constexpr auto nm = Void::Meta::annotation_of(m); + const std::string lng = + std::string{"--"} + + (nm.has_value() ? std::string{nm->text.view()} + : std::string{std::meta::identifier_of(m)}); + constexpr auto sh = Void::Meta::annotation_of(m); + const std::string sht = + sh.has_value() ? (std::string{"-"} + sh->c) : std::string{}; + constexpr auto hp = Void::Meta::annotation_of(m); + const std::string desc = + hp.has_value() ? std::string{hp->text.view()} : std::string{}; + + if constexpr (Void::Meta::has_annotation(m)) { + parser.positional(std::meta::identifier_of(m), desc, out.[:m:]); + } else if constexpr (std::same_as) { + parser.flag(lng, sht, desc, out.[:m:]); + } else if constexpr (Void::Meta::is_optional_v) { + parser.option(lng, sht, desc, out.[:m:]); + } else if constexpr (std::same_as) { + const std::string def = out.[:m:]; + parser.option_default(lng, sht, desc, out.[:m:], def); + } + // other field types: ignored + } + + auto r = parser.parse(argc, argv); + if (!r) { + return std::unexpected{r.error()}; + } + return out; + } + +#endif // VOID_HAS_META_REFLECTION } // namespace Void::Argparse diff --git a/include/Void/Configuration/Bind.hpp b/include/Void/Configuration/Bind.hpp index 415e66d..fcff8c6 100644 --- a/include/Void/Configuration/Bind.hpp +++ b/include/Void/Configuration/Bind.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -39,31 +40,28 @@ namespace Void::Configuration { + // ── field annotations ───────────────────────────────────────────────── + // Annotate aggregate members to control binding: + // struct Settings { + // [[= Configuration::Key{"log_level"}]] std::string level = "info"; + // [[= Configuration::Required{}]] std::string host; + // }; + struct Key { + Void::Meta::Str name; + }; + struct Required { + }; + #ifdef VOID_HAS_CONFIG_REFLECTION namespace BindDetail { - template struct IsOptional : std::false_type { - }; - template - struct IsOptional> : std::true_type { - }; - - template struct IsVector : std::false_type { - }; - template struct IsVector> : std::true_type { - }; - - template struct IsDuration : std::false_type { - }; - template - struct IsDuration> : std::true_type { - }; - + // Leaf / container shape detection comes from Void::Meta (single + // source); Config additionally treats chrono durations as leaves. template concept Leaf = std::is_same_v || std::is_same_v || std::is_arithmetic_v || - std::is_enum_v || IsDuration::value; + std::is_enum_v || Void::Meta::is_duration_v; template concept BindableAggregate = @@ -86,16 +84,20 @@ namespace Void::Configuration T out{}; std::optional failure; - 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) + template for (constexpr auto m : Void::Meta::members_v) { if (!failure) { - constexpr auto name = std::meta::identifier_of(m); using MT = [:std::meta::type_of(m):]; - const auto key = join(prefix, name); + // Key segment: a [[= Configuration::Key("…")]] override, + // else the field identifier. + constexpr auto ko = Void::Meta::annotation_of(m); + const std::string seg = + ko.has_value() + ? std::string{ko->name.view()} + : std::string{std::meta::identifier_of(m)}; + const auto key = join(prefix, seg); + [[maybe_unused]] constexpr bool required = + Void::Meta::has_annotation(m); if constexpr (BindableAggregate && !Leaf) { auto nested = bind_into(cfg, key); @@ -104,7 +106,7 @@ namespace Void::Configuration } else { out.[:m:] = std::move(*nested); } - } else if constexpr (IsOptional::value) { + } else if constexpr (Void::Meta::is_optional_v) { using U = typename MT::value_type; if (cfg.contains(key)) { auto v = cfg.get_as(key); @@ -114,7 +116,7 @@ namespace Void::Configuration out.[:m:] = std::move(*v); } } - } else if constexpr (IsVector::value) { + } else if constexpr (Void::Meta::is_vector_v) { using U = typename MT::value_type; MT items; for (std::size_t i = 0;; ++i) { @@ -142,8 +144,11 @@ namespace Void::Configuration } else { out.[:m:] = std::move(*v); } + } else if constexpr (required) { + failure = Void::Result::Error{ + "missing required config key '" + key + "'"}; } - // absent key: keep the default member value + // absent + not required: keep the default member value } } } diff --git a/include/Void/Configuration/Config.hpp b/include/Void/Configuration/Config.hpp index 7b8621e..4a30a6d 100644 --- a/include/Void/Configuration/Config.hpp +++ b/include/Void/Configuration/Config.hpp @@ -4,15 +4,17 @@ #include #include #include -#include -#include #include #include +#include +#include +#include #include #include #include #include +#include #include #include #include @@ -32,495 +34,514 @@ extern char** environ; // NOLINT namespace Void::Configuration { -/// Layered key-value configuration store with dotted nested keys. -/// -/// Values are plain strings; typed access via get_as(). Layers are -/// applied via overlay(): the last overlay wins on key conflicts. -/// Typical usage: -/// -/// auto cfg = Config::from_env_prefix("MYAPP_"); // MYAPP_LOG__LEVEL → log.level -/// if (auto r = Config::from_ini("app.ini"); r.has_value()) -/// cfg.overlay(*r); // ini overrides env -/// cfg.overlay(Config::from_args(argc, argv)); // --log.level=debug wins -/// auto level = cfg.get_or("log.level", "info"); -/// auto retries = cfg.get_as("net.retries"); // Result -/// -/// Sources: from_env / from_env_prefix (environment), from_file -/// (KEY=VALUE), from_ini (sections become key prefixes), from_json -/// (nested objects flatten into dotted keys), from_args (--key=value). -class Config -{ - public: + /// Layered key-value configuration store with dotted nested keys. + /// + /// Values are plain strings; typed access via get_as(). Layers are + /// applied via overlay(): the last overlay wins on key conflicts. + /// Typical usage: + /// + /// auto cfg = Config::from_env_prefix("MYAPP_"); // MYAPP_LOG__LEVEL → + /// log.level if (auto r = Config::from_ini("app.ini"); r.has_value()) + /// cfg.overlay(*r); // ini overrides env + /// cfg.overlay(Config::from_args(argc, argv)); // --log.level=debug + /// wins auto level = cfg.get_or("log.level", "info"); auto retries = + /// cfg.get_as("net.retries"); // Result + /// + /// Sources: from_env / from_env_prefix (environment), from_file + /// (KEY=VALUE), from_ini (sections become key prefixes), from_json + /// (nested objects flatten into dotted keys), from_args (--key=value). + class Config + { + public: - Config() = default; + Config() = default; - /// Populate from specific named environment variables. - /// Keys absent from the environment are silently skipped. - [[nodiscard]] static Config - from_env(std::initializer_list keys) - { - Config cfg; - for (auto key : keys) { - if (auto r = get_env(key); r.has_value()) { - cfg.values_.emplace(std::string{key}, std::move(*r)); - Void::Log::debug("Configuration", "from_env: loaded '{}'", key); + /// Populate from specific named environment variables. + /// Keys absent from the environment are silently skipped. + [[nodiscard]] static Config + from_env(std::initializer_list keys) + { + Config cfg; + for (auto key : keys) { + if (auto r = get_env(key); r.has_value()) { + cfg.values_.emplace(std::string{key}, std::move(*r)); + Void::Log::debug("Configuration", + "from_env: loaded '{}'", key); + } + } + return cfg; + } + + /// Parse a KEY=VALUE text file (one pair per line, # for comments). + /// Lines without '=' produce a warning log and are skipped. + [[nodiscard]] static Void::Result::Result + from_file(const std::filesystem::path& path) + { + auto text = Void::FileSystem::read_file(path); + if (!text.has_value()) { + return Void::Result::fail( + std::format("Configuration::Config::from_file: {}", + text.error().message())); + } + Config cfg; + std::istringstream ss{*text}; + std::string line; + int lineno = 0; + while (std::getline(ss, line)) { + ++lineno; + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + std::string_view sv{line}; + while (!sv.empty() && sv.front() == ' ') { + sv.remove_prefix(1); + } + if (sv.empty() || sv.front() == '#') { + continue; + } + auto eq = sv.find('='); + if (eq == std::string_view::npos) { + Void::Log::warn("Configuration", + "from_file: '{}' line {}: missing '='", + path.string(), lineno); + continue; + } + auto key = sv.substr(0, eq); + while (!key.empty() && key.back() == ' ') { + key.remove_suffix(1); + } + auto val = sv.substr(eq + 1); + cfg.values_.emplace(std::string{key}, std::string{val}); + } + Void::Log::debug("Configuration", + "from_file: loaded {} keys from '{}'", + cfg.values_.size(), path.string()); + return Void::Result::ok(std::move(cfg)); + } + + /// Layer `other` on top: other's values win on key conflicts. + void overlay(const Config& other) + { + for (const auto& [k, v] : other.values_) { + values_.insert_or_assign(k, v); } } - return cfg; - } - /// Parse a KEY=VALUE text file (one pair per line, # for comments). - /// Lines without '=' produce a warning log and are skipped. - [[nodiscard]] static Void::Result::Result - from_file(const std::filesystem::path& path) - { - auto text = Void::FileSystem::read_file(path); - if (!text.has_value()) { - return Void::Result::fail(std::format( - "Configuration::Config::from_file: {}", text.error().message())); + /// Explicit per-key override (highest priority). + void set(std::string_view key, std::string value) + { + values_.insert_or_assign(std::string{key}, std::move(value)); } - Config cfg; - std::istringstream ss{*text}; - std::string line; - int lineno = 0; - while (std::getline(ss, line)) { - ++lineno; - if (!line.empty() && line.back() == '\r') { - line.pop_back(); + + /// Look up a key. Returns an error if the key is not present. + [[nodiscard]] Void::Result::Result + get(std::string_view key) const + { + auto it = values_.find(std::string{key}); + if (it == values_.end()) { + return Void::Result::fail(std::format( + "Configuration::Config::get: key '{}' not found", key)); } - std::string_view sv{line}; - while (!sv.empty() && sv.front() == ' ') { - sv.remove_prefix(1); - } - if (sv.empty() || sv.front() == '#') { - continue; - } - auto eq = sv.find('='); - if (eq == std::string_view::npos) { - Void::Log::warn("Configuration", "from_file: '{}' line {}: missing '='", - path.string(), lineno); - continue; - } - auto key = sv.substr(0, eq); - while (!key.empty() && key.back() == ' ') { - key.remove_suffix(1); - } - auto val = sv.substr(eq + 1); - cfg.values_.emplace(std::string{key}, std::string{val}); + return Void::Result::ok(std::string_view{it->second}); } - Void::Log::debug("Configuration", "from_file: loaded {} keys from '{}'", - cfg.values_.size(), path.string()); - return Void::Result::ok(std::move(cfg)); - } - /// Layer `other` on top: other's values win on key conflicts. - void overlay(const Config& other) - { - for (const auto& [k, v] : other.values_) { - values_.insert_or_assign(k, v); + /// Look up a key, returning `fallback` when the key is absent. + [[nodiscard]] std::string_view + get_or(std::string_view key, + std::string_view fallback = {}) const + { + auto it = values_.find(std::string{key}); + return it != values_.end() ? std::string_view{it->second} + : fallback; } - } - /// Explicit per-key override (highest priority). - void set(std::string_view key, std::string value) - { - values_.insert_or_assign(std::string{key}, std::move(value)); - } - - /// Look up a key. Returns an error if the key is not present. - [[nodiscard]] Void::Result::Result - get(std::string_view key) const - { - auto it = values_.find(std::string{key}); - if (it == values_.end()) { - return Void::Result::fail(std::format( - "Configuration::Config::get: key '{}' not found", key)); + [[nodiscard]] std::size_t size() const noexcept + { + return values_.size(); + } + [[nodiscard]] bool empty() const noexcept + { + return values_.empty(); } - return Void::Result::ok(std::string_view{it->second}); - } - /// Look up a key, returning `fallback` when the key is absent. - [[nodiscard]] std::string_view - get_or(std::string_view key, std::string_view fallback = {}) const - { - auto it = values_.find(std::string{key}); - return it != values_.end() ? std::string_view{it->second} : fallback; - } + // ═════════════════════════════════════════════════════════════════ + // Additional sources + // ═════════════════════════════════════════════════════════════════ - [[nodiscard]] std::size_t size() const noexcept - { - return values_.size(); - } - [[nodiscard]] bool empty() const noexcept { return values_.empty(); } - - // ═════════════════════════════════════════════════════════════════ - // Additional sources - // ═════════════════════════════════════════════════════════════════ - - /// Scan the whole environment for variables starting with `prefix`. - /// The prefix is stripped, `__` becomes `.`, and the key is - /// lowercased: MYAPP_LOG__LEVEL=debug → log.level=debug. - [[nodiscard]] static Config from_env_prefix(std::string_view prefix) - { - Config cfg; + /// Scan the whole environment for variables starting with `prefix`. + /// The prefix is stripped, `__` becomes `.`, and the key is + /// lowercased: MYAPP_LOG__LEVEL=debug → log.level=debug. + [[nodiscard]] static Config from_env_prefix(std::string_view prefix) + { + Config cfg; #ifdef VOID_CONFIG_HAS_ENVIRON - for (char** env = environ; *env != nullptr; ++env) { - const std::string_view kv{*env}; - const auto eq = kv.find('='); - if (eq == std::string_view::npos || - !kv.starts_with(prefix)) { - continue; + for (char** env = environ; *env != nullptr; ++env) { + const std::string_view kv{*env}; + const auto eq = kv.find('='); + if (eq == std::string_view::npos || + !kv.starts_with(prefix)) { + continue; + } + auto raw_key = kv.substr(prefix.size(), eq - prefix.size()); + std::string key; + key.reserve(raw_key.size()); + for (std::size_t i = 0; i < raw_key.size(); ++i) { + if (raw_key[i] == '_' && i + 1 < raw_key.size() && + raw_key[i + 1] == '_') { + key += '.'; + ++i; + } else { + key += static_cast(std::tolower( + static_cast(raw_key[i]))); + } + } + cfg.values_.emplace(std::move(key), + std::string{kv.substr(eq + 1)}); } - auto raw_key = kv.substr(prefix.size(), eq - prefix.size()); - std::string key; - key.reserve(raw_key.size()); - for (std::size_t i = 0; i < raw_key.size(); ++i) { - if (raw_key[i] == '_' && i + 1 < raw_key.size() && - raw_key[i + 1] == '_') { - key += '.'; + Void::Log::debug("Configuration", + "from_env_prefix('{}'): {} keys", prefix, + cfg.size()); +#else + (void)prefix; +#endif + return cfg; + } + + /// Parse an INI file: `[section]` + `key = value` becomes + /// "section.key"; pairs before any section keep their bare key. + [[nodiscard]] static Void::Result::Result + from_ini(const std::filesystem::path& path) + { + auto text = Void::FileSystem::read_file(path); + if (!text.has_value()) { + return Void::Result::fail( + std::format("Configuration::Config::from_ini: {}", + text.error().message())); + } + return from_ini_text(*text); + } + + [[nodiscard]] static Void::Result::Result + from_ini_text(std::string_view text) + { + Void::Ini::IniFile ini; + if (auto err = Void::Ini::IniFile::parse(ini, text); + err.has_value()) { + return Void::Result::fail(std::format( + "Configuration::Config::from_ini: line {}: {}", + err->line, err->message)); + } + Config cfg; + for (const auto& name : ini.sections()) { + const auto* section = ini.section(name); + if (section == nullptr) { + continue; + } + for (const auto& [key, value] : *section) { + auto full = name.empty() ? key : name + "." + key; + cfg.values_.insert_or_assign(std::move(full), value); + } + } + return Void::Result::ok(std::move(cfg)); + } + + /// Parse a JSON file; nested objects flatten into dotted keys, + /// arrays into numeric segments ("servers.0.host"). Scalars are + /// stored in their canonical string form. + [[nodiscard]] static Void::Result::Result + from_json(const std::filesystem::path& path) + { + auto text = Void::FileSystem::read_file(path); + if (!text.has_value()) { + return Void::Result::fail( + std::format("Configuration::Config::from_json: {}", + text.error().message())); + } + return from_json_text(*text); + } + + [[nodiscard]] static Void::Result::Result + from_json_text(std::string_view text) + { + auto parsed = Void::Json::parse(text); + if (!parsed.has_value()) { + return Void::Result::fail(std::format( + "Configuration::Config::from_json: line {} col {}: {}", + parsed.error().line, parsed.error().col, + parsed.error().message)); + } + Config cfg; + flatten_json(cfg, "", *parsed); + return Void::Result::ok(std::move(cfg)); + } + + /// Collect `--key=value`, `--key value` and bare `--flag` + /// (stored as "true") arguments. Non-option arguments are ignored. + [[nodiscard]] static Config from_args(int argc, + const char* const* argv) + { + Config cfg; + for (int i = 1; i < argc; ++i) { + const std::string_view arg{argv[i]}; + if (!arg.starts_with("--") || arg.size() <= 2) { + continue; + } + const auto body = arg.substr(2); + if (const auto eq = body.find('='); + eq != std::string_view::npos) { + cfg.values_.insert_or_assign( + std::string{body.substr(0, eq)}, + std::string{body.substr(eq + 1)}); + } else if (i + 1 < argc && + std::string_view{argv[i + 1]}.substr(0, 2) != + "--") { + cfg.values_.insert_or_assign(std::string{body}, + std::string{argv[i + 1]}); + ++i; + } else { + cfg.values_.insert_or_assign(std::string{body}, "true"); + } + } + return cfg; + } + + // ═════════════════════════════════════════════════════════════════ + // Typed access + // ═════════════════════════════════════════════════════════════════ + + /// Look up and convert. Supported T: integral and floating types, + /// bool ("true/false/1/0/yes/no/on/off", case-insensitive), enums + /// (by enumerator name, reflection builds), std::string, and + /// std::chrono durations ("250ms", "10s", "5m", "1h", "500us", + /// "30ns" — converted to T, rejecting lossy narrowing). + template + [[nodiscard]] Void::Result::Result + get_as(std::string_view key) const + { + const auto it = values_.find(std::string{key}); + if (it == values_.end()) { + return Void::Result::fail(std::format( + "Configuration::Config::get_as: key '{}' not found", + key)); + } + return convert(key, it->second); + } + + /// Typed lookup with fallback for missing keys. Conversion errors + /// on a *present* key still surface the fallback but are logged. + template + [[nodiscard]] T get_or_as(std::string_view key, T fallback) const + { + auto r = get_as(key); + if (r.has_value()) { + return std::move(*r); + } + return fallback; + } + + // ═════════════════════════════════════════════════════════════════ + // Key enumeration / subtrees + // ═════════════════════════════════════════════════════════════════ + + /// All keys, sorted. + [[nodiscard]] std::vector keys() const + { + std::vector out; + out.reserve(values_.size()); + for (const auto& [k, _] : values_) { + out.push_back(k); + } + std::sort(out.begin(), out.end()); + return out; + } + + /// A new Config holding every key under "prefix." with the prefix + /// stripped: subtree("log") of {log.level, log.file.path} yields + /// {level, file.path}. + [[nodiscard]] Config subtree(std::string_view prefix) const + { + Config out; + const auto full = std::string{prefix} + "."; + for (const auto& [k, v] : values_) { + if (k.starts_with(full)) { + out.values_.emplace(k.substr(full.size()), v); + } + } + return out; + } + + [[nodiscard]] bool contains(std::string_view key) const + { + return values_.contains(std::string{key}); + } + + private: + + static void flatten_json(Config& cfg, const std::string& prefix, + const Void::Json::Value& v) + { + using Void::Json::Value; + if (v.is_object()) { + for (const auto& [k, child] : v.as_object()) { + flatten_json(cfg, prefix.empty() ? k : prefix + "." + k, + child); + } + } else if (v.is_array()) { + std::size_t i = 0; + for (const auto& child : v.as_array()) { + flatten_json(cfg, prefix + "." + std::to_string(i), + child); ++i; } - else { - key += static_cast(std::tolower( - static_cast(raw_key[i]))); + } else if (v.is_string()) { + cfg.values_.insert_or_assign(prefix, v.as_string()); + } else if (v.is_bool()) { + cfg.values_.insert_or_assign(prefix, v.as_bool() ? "true" + : "false"); + } else if (v.is_number()) { + const double d = v.as_number(); + if (d == static_cast(static_cast(d))) { + cfg.values_.insert_or_assign( + prefix, std::to_string(static_cast(d))); + } else { + cfg.values_.insert_or_assign(prefix, + std::format("{}", d)); } } - cfg.values_.emplace(std::move(key), - std::string{kv.substr(eq + 1)}); + // null: key omitted } - Void::Log::debug("Configuration", - "from_env_prefix('{}'): {} keys", prefix, - cfg.size()); -#else - (void)prefix; -#endif - return cfg; - } - /// Parse an INI file: `[section]` + `key = value` becomes - /// "section.key"; pairs before any section keep their bare key. - [[nodiscard]] static Void::Result::Result - from_ini(const std::filesystem::path& path) - { - auto text = Void::FileSystem::read_file(path); - if (!text.has_value()) { - return Void::Result::fail( - std::format("Configuration::Config::from_ini: {}", - text.error().message())); - } - return from_ini_text(*text); - } - - [[nodiscard]] static Void::Result::Result - from_ini_text(std::string_view text) - { - Void::Ini::IniFile ini; - if (auto err = Void::Ini::IniFile::parse(ini, text); - err.has_value()) { - return Void::Result::fail(std::format( - "Configuration::Config::from_ini: line {}: {}", - err->line, err->message)); - } - Config cfg; - for (const auto& name : ini.sections()) { - const auto* section = ini.section(name); - if (section == nullptr) { - continue; - } - for (const auto& [key, value] : *section) { - auto full = - name.empty() ? key : name + "." + key; - cfg.values_.insert_or_assign(std::move(full), value); - } - } - return Void::Result::ok(std::move(cfg)); - } - - /// Parse a JSON file; nested objects flatten into dotted keys, - /// arrays into numeric segments ("servers.0.host"). Scalars are - /// stored in their canonical string form. - [[nodiscard]] static Void::Result::Result - from_json(const std::filesystem::path& path) - { - auto text = Void::FileSystem::read_file(path); - if (!text.has_value()) { - return Void::Result::fail( - std::format("Configuration::Config::from_json: {}", - text.error().message())); - } - return from_json_text(*text); - } - - [[nodiscard]] static Void::Result::Result - from_json_text(std::string_view text) - { - auto parsed = Void::Json::parse(text); - if (!parsed.has_value()) { - return Void::Result::fail(std::format( - "Configuration::Config::from_json: line {} col {}: {}", - parsed.error().line, parsed.error().col, - parsed.error().message)); - } - Config cfg; - flatten_json(cfg, "", *parsed); - return Void::Result::ok(std::move(cfg)); - } - - /// Collect `--key=value`, `--key value` and bare `--flag` - /// (stored as "true") arguments. Non-option arguments are ignored. - [[nodiscard]] static Config from_args(int argc, - const char* const* argv) - { - Config cfg; - for (int i = 1; i < argc; ++i) { - const std::string_view arg{argv[i]}; - if (!arg.starts_with("--") || arg.size() <= 2) { - continue; - } - const auto body = arg.substr(2); - if (const auto eq = body.find('='); - eq != std::string_view::npos) { - cfg.values_.insert_or_assign( - std::string{body.substr(0, eq)}, - std::string{body.substr(eq + 1)}); - } - else if (i + 1 < argc && - std::string_view{argv[i + 1]}.substr(0, 2) != - "--") { - cfg.values_.insert_or_assign(std::string{body}, - std::string{argv[i + 1]}); - ++i; - } - else { - cfg.values_.insert_or_assign(std::string{body}, - "true"); - } - } - return cfg; - } - - // ═════════════════════════════════════════════════════════════════ - // Typed access - // ═════════════════════════════════════════════════════════════════ - - /// Look up and convert. Supported T: integral and floating types, - /// bool ("true/false/1/0/yes/no/on/off", case-insensitive), enums - /// (by enumerator name, reflection builds), std::string, and - /// std::chrono durations ("250ms", "10s", "5m", "1h", "500us", - /// "30ns" — converted to T, rejecting lossy narrowing). - template - [[nodiscard]] Void::Result::Result - get_as(std::string_view key) const - { - const auto it = values_.find(std::string{key}); - if (it == values_.end()) { - return Void::Result::fail(std::format( - "Configuration::Config::get_as: key '{}' not found", - key)); - } - return convert(key, it->second); - } - - /// Typed lookup with fallback for missing keys. Conversion errors - /// on a *present* key still surface the fallback but are logged. - template - [[nodiscard]] T get_or_as(std::string_view key, T fallback) const - { - auto r = get_as(key); - if (r.has_value()) { - return std::move(*r); - } - return fallback; - } - - // ═════════════════════════════════════════════════════════════════ - // Key enumeration / subtrees - // ═════════════════════════════════════════════════════════════════ - - /// All keys, sorted. - [[nodiscard]] std::vector keys() const - { - std::vector out; - out.reserve(values_.size()); - for (const auto& [k, _] : values_) { - out.push_back(k); - } - std::sort(out.begin(), out.end()); - return out; - } - - /// A new Config holding every key under "prefix." with the prefix - /// stripped: subtree("log") of {log.level, log.file.path} yields - /// {level, file.path}. - [[nodiscard]] Config subtree(std::string_view prefix) const - { - Config out; - const auto full = std::string{prefix} + "."; - for (const auto& [k, v] : values_) { - if (k.starts_with(full)) { - out.values_.emplace(k.substr(full.size()), v); - } - } - return out; - } - - [[nodiscard]] bool contains(std::string_view key) const - { - return values_.contains(std::string{key}); - } - - private: - - static void flatten_json(Config& cfg, const std::string& prefix, - const Void::Json::Value& v) - { - using Void::Json::Value; - if (v.is_object()) { - for (const auto& [k, child] : v.as_object()) { - flatten_json( - cfg, prefix.empty() ? k : prefix + "." + k, child); - } - } - else if (v.is_array()) { - std::size_t i = 0; - for (const auto& child : v.as_array()) { - flatten_json(cfg, prefix + "." + std::to_string(i), - child); - ++i; - } - } - else if (v.is_string()) { - cfg.values_.insert_or_assign(prefix, v.as_string()); - } - else if (v.is_bool()) { - cfg.values_.insert_or_assign(prefix, - v.as_bool() ? "true" : "false"); - } - else if (v.is_number()) { - const double d = v.as_number(); - if (d == static_cast(static_cast(d))) { - cfg.values_.insert_or_assign( - prefix, - std::to_string(static_cast(d))); - } - else { - cfg.values_.insert_or_assign(prefix, - std::format("{}", d)); - } - } - // null: key omitted - } - - template - struct IsDuration : std::false_type {}; - template - struct IsDuration> - : std::true_type {}; - - template - static Void::Result::Result - convert(std::string_view key, const std::string& raw) - { - auto fail = [&](std::string_view what) { - return Void::Result::fail(std::format( - "Configuration::Config::get_as: key '{}': {} ('{}')", - key, what, raw)); + template struct IsDuration : std::false_type { + }; + template + struct IsDuration> + : std::true_type { }; - if constexpr (std::is_same_v) { - return Void::Result::ok(raw); - } - else if constexpr (std::is_same_v) { - std::string lower; - lower.reserve(raw.size()); - for (const char c : raw) { - lower += static_cast( - std::tolower(static_cast(c))); - } - if (lower == "true" || lower == "1" || lower == "yes" || - lower == "on") { - return Void::Result::ok(true); - } - if (lower == "false" || lower == "0" || lower == "no" || - lower == "off") { - return Void::Result::ok(false); - } - return fail("not a boolean"); - } - else if constexpr (std::is_enum_v) { + template + static Void::Result::Result + convert(std::string_view key, const std::string& raw) + { + auto fail = [&](std::string_view what) { + return Void::Result::fail(std::format( + "Configuration::Config::get_as: key '{}': {} ('{}')", + key, what, raw)); + }; + + if constexpr (std::is_same_v) { + return Void::Result::ok(raw); + } else if constexpr (std::is_same_v) { + std::string lower; + lower.reserve(raw.size()); + for (const char c : raw) { + lower += static_cast( + std::tolower(static_cast(c))); + } + if (lower == "true" || lower == "1" || lower == "yes" || + lower == "on") { + return Void::Result::ok(true); + } + if (lower == "false" || lower == "0" || lower == "no" || + lower == "off") { + return Void::Result::ok(false); + } + return fail("not a boolean"); + } else if constexpr (std::is_enum_v) { #ifdef VOID_HAS_ENUM_REFLECTION - if (auto e = Void::Detail::enum_parse(raw); - e.has_value()) { - return Void::Result::ok(*e); - } - return fail("no such enumerator"); + if (auto e = Void::Detail::enum_parse(raw); + e.has_value()) { + return Void::Result::ok(*e); + } + return fail("no such enumerator"); #else - return fail("enum parsing requires reflection"); + return fail("enum parsing requires reflection"); #endif - } - else if constexpr (IsDuration::value) { - auto parsed = parse_duration(raw); - if (!parsed.has_value()) { - return fail("not a duration (use e.g. 250ms, 10s, 5m)"); - } - return Void::Result::ok( - std::chrono::duration_cast(*parsed)); - } - else if constexpr (std::is_arithmetic_v) { - T value{}; - const char* begin = raw.data(); - const char* end = raw.data() + raw.size(); - const auto [ptr, ec] = std::from_chars(begin, end, value); - if (ec != std::errc{} || ptr != end) { + } else if constexpr (IsDuration::value) { + auto parsed = parse_duration(raw); + if (!parsed.has_value()) { + return fail("not a duration (use e.g. 250ms, 10s, 5m)"); + } + return Void::Result::ok( + std::chrono::duration_cast(*parsed)); + } else if constexpr (std::is_arithmetic_v) { + T value{}; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, value); + if (ec == std::errc{} && ptr == end) { + return Void::Result::ok(value); + } + // Byte-size units for integral targets: "10MB", "1GiB". + if constexpr (std::is_integral_v) { + if (auto bytes = parse_bytes(raw); bytes.has_value()) { + return Void::Result::ok(static_cast(*bytes)); + } + return fail("not a number or byte size"); + } return fail("not a number"); + } else { + static_assert(std::is_same_v, + "unsupported get_as type"); } - return Void::Result::ok(value); } - else { - static_assert(std::is_same_v, - "unsupported get_as type"); - } - } - static std::optional - parse_duration(const std::string& raw) - { - double number = 0; - const char* begin = raw.data(); - const char* end = raw.data() + raw.size(); - const auto [ptr, ec] = std::from_chars(begin, end, number); - if (ec != std::errc{} || ptr == begin) { - return std::nullopt; + static std::optional + parse_duration(const std::string& raw) + { + // Single source of truth lives in Time/Format.hpp. + return Void::Time::parse_duration(raw); } - const std::string_view suffix{ptr, end}; - using namespace std::chrono; - const auto as_ns = [&](auto unit) { - return std::optional{duration_cast( - duration{ - number})}; - }; - if (suffix == "ns") { - return as_ns(nanoseconds{}); - } - if (suffix == "us") { - return as_ns(microseconds{}); - } - if (suffix == "ms") { - return as_ns(milliseconds{}); - } - if (suffix == "s" || suffix.empty()) { - return as_ns(seconds{}); - } - if (suffix == "m") { - return as_ns(minutes{}); - } - if (suffix == "h") { - return as_ns(hours{}); - } - return std::nullopt; - } - std::unordered_map values_; -}; + // Parse a byte-size string: a number followed by an SI + // (KB/MB/GB/TB, powers of 1000) or binary (KiB/MiB/GiB/TiB, powers + // of 1024) unit. A bare "B" or empty suffix means bytes. Returns + // nullopt otherwise. + static std::optional + parse_bytes(const std::string& raw) + { + double number = 0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, number); + if (ec != std::errc{} || ptr == begin) { + return std::nullopt; + } + std::string_view suffix{ptr, end}; + while (!suffix.empty() && suffix.front() == ' ') { + suffix.remove_prefix(1); + } + double mult = 0; + if (suffix.empty() || suffix == "B") { + mult = 1.0; + } else if (suffix == "KB") { + mult = 1e3; + } else if (suffix == "MB") { + mult = 1e6; + } else if (suffix == "GB") { + mult = 1e9; + } else if (suffix == "TB") { + mult = 1e12; + } else if (suffix == "KiB") { + mult = 1024.0; + } else if (suffix == "MiB") { + mult = 1024.0 * 1024.0; + } else if (suffix == "GiB") { + mult = 1024.0 * 1024.0 * 1024.0; + } else if (suffix == "TiB") { + mult = 1024.0 * 1024.0 * 1024.0 * 1024.0; + } else { + return std::nullopt; + } + return static_cast(number * mult); + } + + std::unordered_map values_; + }; } // namespace Void::Configuration diff --git a/include/Void/Containers/BufferPool.hpp b/include/Void/Containers/BufferPool.hpp new file mode 100644 index 0000000..b4e1c83 --- /dev/null +++ b/include/Void/Containers/BufferPool.hpp @@ -0,0 +1,203 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::BufferPool +{ + + // ── BufferPool + // ───────────────────────────────────────────────────────────── A pool of + // reusable, variable-length buffers of T — e.g. audio sample blocks (int16 + // / float). Distinct from Containers/Pool.hpp's ObjectPool, which pools + // fixed-size *objects*: this pools backing storage sized by request. + // + // acquire(n) hands back a Buffer of logical length n backed by capacity + // rounded up to the next power-of-two size class; on drop the storage + // returns to the pool's bucket for that size class, so a later acquire of + // the same class reuses it with no reallocation. + // + // Not thread-safe — guard externally if shared. + + template class BufferPool + { + public: + + BufferPool() = default; + + BufferPool(const BufferPool&) = delete; + BufferPool& operator=(const BufferPool&) = delete; + BufferPool(BufferPool&&) = default; + BufferPool& operator=(BufferPool&&) = default; + + struct Stats { + std::uint64_t allocations = 0; // fresh storage allocated + std::uint64_t reuses = 0; // requests served from a bucket + std::size_t pooled = 0; // buffers currently idle in buckets + }; + + // An owning view returned by acquire(); recycles its storage on + // drop. + class Buffer + { + public: + + Buffer() = default; + + Buffer(const Buffer&) = delete; + Buffer& operator=(const Buffer&) = delete; + + Buffer(Buffer&& other) noexcept + : pool_{other.pool_}, + storage_{std::move(other.storage_)}, + size_{other.size_} + { + other.pool_ = nullptr; + other.size_ = 0; + } + + Buffer& operator=(Buffer&& other) noexcept + { + if (this != &other) { + recycle(); + pool_ = other.pool_; + storage_ = std::move(other.storage_); + size_ = other.size_; + other.pool_ = nullptr; + other.size_ = 0; + } + return *this; + } + + ~Buffer() { recycle(); } + + [[nodiscard]] T* data() noexcept { return storage_.data(); } + [[nodiscard]] const T* data() const noexcept + { + return storage_.data(); + } + [[nodiscard]] std::size_t size() const noexcept + { + return size_; + } + [[nodiscard]] bool empty() const noexcept + { + return size_ == 0; + } + // Backing capacity (the size class) — always >= size(). + [[nodiscard]] std::size_t capacity() const noexcept + { + return storage_.size(); + } + + [[nodiscard]] T& operator[](std::size_t i) noexcept + { + return storage_[i]; + } + [[nodiscard]] const T& + operator[](std::size_t i) const noexcept + { + return storage_[i]; + } + + [[nodiscard]] T* begin() noexcept { return data(); } + [[nodiscard]] T* end() noexcept { return data() + size_; } + [[nodiscard]] const T* begin() const noexcept + { + return data(); + } + [[nodiscard]] const T* end() const noexcept + { + return data() + size_; + } + + [[nodiscard]] std::span span() noexcept + { + return {data(), size_}; + } + [[nodiscard]] std::span span() const noexcept + { + return {data(), size_}; + } + + private: + + friend class BufferPool; + + Buffer(BufferPool* pool, std::vector storage, + std::size_t n) noexcept + : pool_{pool}, storage_{std::move(storage)}, size_{n} + { + } + + void recycle() noexcept + { + if (pool_) { + pool_->recycle(std::move(storage_)); + pool_ = nullptr; + } + } + + BufferPool* pool_ = nullptr; + std::vector storage_; + std::size_t size_ = 0; + }; + + // Hand out a buffer of logical length n (capacity rounded up to a + // power of two), reusing pooled storage of that size class when + // available. + [[nodiscard]] Buffer acquire(std::size_t n) + { + const std::size_t cls = size_class(n); + std::vector storage; + auto bucket = free_.find(cls); + if (bucket != free_.end() && !bucket->second.empty()) { + storage = std::move(bucket->second.back()); + bucket->second.pop_back(); + ++reuses_; + } else { + storage.resize(cls); + ++allocations_; + } + return Buffer{this, std::move(storage), n}; + } + + [[nodiscard]] Stats stats() const + { + std::size_t pooled = 0; + for (const auto& [cls, bucket] : free_) { + pooled += bucket.size(); + } + return Stats{allocations_, reuses_, pooled}; + } + + // Drop all pooled (idle) storage. Outstanding Buffers are + // unaffected. + void shrink() noexcept { free_.clear(); } + + private: + + static std::size_t size_class(std::size_t n) noexcept + { + return n == 0 ? 0 : std::bit_ceil(n); + } + + void recycle(std::vector storage) + { + if (storage.empty()) { + return; + } + free_[storage.size()].push_back(std::move(storage)); + } + + std::unordered_map>> free_; + std::uint64_t allocations_ = 0; + std::uint64_t reuses_ = 0; + }; + +} // namespace Void::BufferPool diff --git a/include/Void/Containers/Cache.hpp b/include/Void/Containers/Cache.hpp new file mode 100644 index 0000000..4ffdca9 --- /dev/null +++ b/include/Void/Containers/Cache.hpp @@ -0,0 +1,268 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Cache +{ + + // ── Cache + // ─────────────────────────────────────────────────────────────── A + // fixed-capacity cache with per-entry TTL, a selectable eviction policy, + // and hit/miss/eviction/expiration counters. Built on the same + // doubly-linked-list + hash-map structure as Containers/LRU.hpp (which + // stays the minimal primitive). + // + // Not thread-safe — guard externally if shared, like LruCache. + // + // Expiry is lazy: an entry past its TTL is treated as a miss and dropped on + // the next access (or in bulk via sweep()). The clock is injectable for + // tests. + + enum class Policy { + LRU, // evict the least-recently-used entry (default) + LFU, // evict the least-frequently-used entry + FIFO // evict the oldest inserted entry + }; + + template class Cache + { + public: + + using Clock = + std::function; + using Duration = std::chrono::steady_clock::duration; + using TimePoint = std::chrono::steady_clock::time_point; + + struct Stats { + std::uint64_t hits = 0; + std::uint64_t misses = 0; + std::uint64_t evictions = + 0; // dropped to make room (capacity) + std::uint64_t expirations = + 0; // dropped because the TTL elapsed + std::size_t size = 0; + }; + + explicit Cache(std::size_t capacity, Policy policy = Policy::LRU, + std::optional default_ttl = std::nullopt, + Clock clock = default_clock()) + : capacity_{capacity}, policy_{policy}, + default_ttl_{default_ttl}, clock_{std::move(clock)} + { + if (capacity == 0) { + throw std::invalid_argument{"capacity must be > 0"}; + } + } + + [[nodiscard]] std::size_t capacity() const noexcept + { + return capacity_; + } + [[nodiscard]] std::size_t size() const noexcept + { + return map_.size(); + } + [[nodiscard]] bool empty() const noexcept { return map_.empty(); } + [[nodiscard]] bool full() const noexcept + { + return map_.size() == capacity_; + } + [[nodiscard]] Policy policy() const noexcept { return policy_; } + + // Retrieve a value. nullopt on miss or expiry; updates recency / + // frequency and the hit/miss counters on every call. + [[nodiscard]] std::optional get(const K& key) + { + auto it = map_.find(key); + if (it == map_.end()) { + ++misses_; + return std::nullopt; + } + const auto now = clock_(); + if (expired(*it->second, now)) { + drop(it); + ++expirations_; + ++misses_; + return std::nullopt; + } + ++hits_; + touch(it->second); + return it->second->value; + } + + // Peek without recency promotion and without touching hit/miss + // stats. Still respects expiry (an expired entry is invisible and + // dropped). + [[nodiscard]] const V* peek(const K& key) + { + auto it = map_.find(key); + if (it == map_.end()) { + return nullptr; + } + if (expired(*it->second, clock_())) { + drop(it); + ++expirations_; + return nullptr; + } + return &it->second->value; + } + + // Insert or update with the cache's default TTL. + void put(const K& key, V value) + { + put(key, std::move(value), default_ttl_); + } + + // Insert or update with an explicit TTL (nullopt = never expires). + void put(const K& key, V value, std::optional ttl) + { + const auto now = clock_(); + if (auto it = map_.find(key); it != map_.end()) { + it->second->value = std::move(value); + set_expiry(*it->second, ttl, now); + touch(it->second); + return; + } + if (map_.size() == capacity_) { + evict_one(); + } + list_.push_front(Node{key, std::move(value), 1, {}, false}); + set_expiry(list_.front(), ttl, now); + map_[key] = list_.begin(); + } + + bool erase(const K& key) + { + auto it = map_.find(key); + if (it == map_.end()) { + return false; + } + drop(it); + return true; + } + + void clear() noexcept + { + list_.clear(); + map_.clear(); + } + + // Present and not expired. Const: does not drop the expired entry. + [[nodiscard]] bool contains(const K& key) const + { + auto it = map_.find(key); + return it != map_.end() && !expired(*it->second, clock_()); + } + + // Purge every expired entry; returns how many were removed. + std::size_t sweep() + { + const auto now = clock_(); + std::size_t purged = 0; + for (auto it = list_.begin(); it != list_.end();) { + if (expired(*it, now)) { + map_.erase(it->key); + it = list_.erase(it); + ++purged; + ++expirations_; + } else { + ++it; + } + } + return purged; + } + + [[nodiscard]] Stats stats() const + { + return Stats{hits_, misses_, evictions_, expirations_, + map_.size()}; + } + + private: + + struct Node { + K key; + V value; + std::uint64_t freq = 0; + TimePoint expiry{}; + bool has_expiry = false; + }; + using List = std::list; + using Map = std::unordered_map; + + static Clock default_clock() + { + return [] { return std::chrono::steady_clock::now(); }; + } + + static bool expired(const Node& n, TimePoint now) + { + return n.has_expiry && now >= n.expiry; + } + + void set_expiry(Node& n, std::optional ttl, TimePoint now) + { + n.has_expiry = ttl.has_value(); + if (ttl) { + n.expiry = now + *ttl; + } + } + + // Record a use: bump frequency and (for LRU) promote to + // most-recent. + void touch(typename List::iterator lit) + { + ++lit->freq; + if (policy_ == Policy::LRU) { + list_.splice(list_.begin(), list_, lit); + } + } + + void drop(typename Map::iterator it) + { + list_.erase(it->second); + map_.erase(it); + } + + void evict_one() + { + typename List::iterator victim; + if (policy_ == Policy::LFU) { + victim = list_.begin(); + for (auto i = list_.begin(); i != list_.end(); ++i) { + if (i->freq < victim->freq) { + victim = i; + } + } + } else { + // LRU and FIFO both evict from the back: LRU keeps the list + // in recency order via touch(); FIFO never reorders, so the + // back is the oldest insertion. + victim = std::prev(list_.end()); + } + map_.erase(victim->key); + list_.erase(victim); + ++evictions_; + } + + std::size_t capacity_; + Policy policy_; + std::optional default_ttl_; + Clock clock_; + List list_; + Map map_; + std::uint64_t hits_ = 0; + std::uint64_t misses_ = 0; + std::uint64_t evictions_ = 0; + std::uint64_t expirations_ = 0; + }; + +} // namespace Void::Cache diff --git a/include/Void/Containers/Debug.hpp b/include/Void/Containers/Debug.hpp new file mode 100644 index 0000000..9c5db3f --- /dev/null +++ b/include/Void/Containers/Debug.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include + +#include +#include + +namespace Void::Containers +{ + /// Render any range's elements as "[e0, e1, …]" using the shared + /// reflection renderer Void::Meta::repr (so structs print their fields): + /// Containers::debug_dump(my_ring); // "[Point{x: 1, y: 2}, …]" + template + [[nodiscard]] std::string debug_dump(const R& range) + { + std::string out = "["; + bool first = true; + for (const auto& e : range) { + if (!first) { + out += ", "; + } + out += Void::Meta::repr(e); + first = false; + } + out += ']'; + return out; + } +} // namespace Void::Containers diff --git a/include/Void/Core/Flags.hpp b/include/Void/Core/Flags.hpp index 79173b4..40d7858 100644 --- a/include/Void/Core/Flags.hpp +++ b/include/Void/Core/Flags.hpp @@ -1,114 +1,233 @@ #pragma once +#include + #include +#include +#include #include namespace Void::Flags { -// ── Flags ───────────────────────────────────────────────────────────────── -// Type-safe bitmask wrapper over a scoped enum class E. -// E's enumerators must be distinct single-bit values (1, 2, 4, 8, …). + // ── Flags + // ───────────────────────────────────────────────────────────────── + // Type-safe bitmask wrapper over a scoped enum class E. + // E's enumerators must be distinct single-bit values (1, 2, 4, 8, …). -template - requires std::is_enum_v -class Flags -{ -public: - using underlying = std::underlying_type_t; + template + requires std::is_enum_v + class Flags + { + public: - constexpr Flags() noexcept = default; - constexpr Flags(E bit) noexcept : bits_{static_cast(bit)} {} - constexpr explicit Flags(underlying raw) noexcept : bits_{raw} {} - constexpr Flags(std::initializer_list list) noexcept - { - for (const E e : list) bits_ |= static_cast(e); - } + using underlying = std::underlying_type_t; - // ── query ───────────────────────────────────────────────────────────────── + constexpr Flags() noexcept = default; + constexpr Flags(E bit) noexcept + : bits_{static_cast(bit)} + { + } + constexpr explicit Flags(underlying raw) noexcept : bits_{raw} {} + constexpr Flags(std::initializer_list list) noexcept + { + for (const E e : list) { + bits_ |= static_cast(e); + } + } - [[nodiscard]] constexpr bool test(E bit) const noexcept - { - return (bits_ & static_cast(bit)) != 0; - } + // ── query + // ───────────────────────────────────────────────────────────────── - [[nodiscard]] constexpr bool any() const noexcept { return bits_ != 0; } - [[nodiscard]] constexpr bool none() const noexcept { return bits_ == 0; } + [[nodiscard]] constexpr bool test(E bit) const noexcept + { + return (bits_ & static_cast(bit)) != 0; + } - [[nodiscard]] constexpr bool all(Flags mask) const noexcept - { - return (bits_ & mask.bits_) == mask.bits_; - } + [[nodiscard]] constexpr bool any() const noexcept + { + return bits_ != 0; + } + [[nodiscard]] constexpr bool none() const noexcept + { + return bits_ == 0; + } - [[nodiscard]] constexpr bool any_of(Flags mask) const noexcept - { - return (bits_ & mask.bits_) != 0; - } + [[nodiscard]] constexpr bool all(Flags mask) const noexcept + { + return (bits_ & mask.bits_) == mask.bits_; + } - [[nodiscard]] constexpr underlying raw() const noexcept { return bits_; } + [[nodiscard]] constexpr bool any_of(Flags mask) const noexcept + { + return (bits_ & mask.bits_) != 0; + } - // ── mutation ────────────────────────────────────────────────────────────── + [[nodiscard]] constexpr underlying raw() const noexcept + { + return bits_; + } - constexpr Flags& set(E bit) noexcept - { - bits_ |= static_cast(bit); - return *this; - } + // ── mutation + // ────────────────────────────────────────────────────────────── - constexpr Flags& unset(E bit) noexcept - { - bits_ &= ~static_cast(bit); - return *this; - } + constexpr Flags& set(E bit) noexcept + { + bits_ |= static_cast(bit); + return *this; + } - constexpr Flags& toggle(E bit) noexcept - { - bits_ ^= static_cast(bit); - return *this; - } + constexpr Flags& unset(E bit) noexcept + { + bits_ &= ~static_cast(bit); + return *this; + } - constexpr void clear() noexcept { bits_ = 0; } + constexpr Flags& toggle(E bit) noexcept + { + bits_ ^= static_cast(bit); + return *this; + } - // ── operators ───────────────────────────────────────────────────────────── + constexpr void clear() noexcept { bits_ = 0; } - [[nodiscard]] constexpr Flags operator|(Flags o) const noexcept { return Flags{static_cast(bits_ | o.bits_)}; } - [[nodiscard]] constexpr Flags operator&(Flags o) const noexcept { return Flags{static_cast(bits_ & o.bits_)}; } - [[nodiscard]] constexpr Flags operator^(Flags o) const noexcept { return Flags{static_cast(bits_ ^ o.bits_)}; } - [[nodiscard]] constexpr Flags operator~() const noexcept { return Flags{static_cast(~bits_)}; } + // ── operators + // ───────────────────────────────────────────────────────────── - [[nodiscard]] constexpr Flags operator|(E bit) const noexcept { return *this | Flags{bit}; } - [[nodiscard]] constexpr Flags operator&(E bit) const noexcept { return *this & Flags{bit}; } - [[nodiscard]] constexpr Flags operator^(E bit) const noexcept { return *this ^ Flags{bit}; } + [[nodiscard]] constexpr Flags operator|(Flags o) const noexcept + { + return Flags{static_cast(bits_ | o.bits_)}; + } + [[nodiscard]] constexpr Flags operator&(Flags o) const noexcept + { + return Flags{static_cast(bits_ & o.bits_)}; + } + [[nodiscard]] constexpr Flags operator^(Flags o) const noexcept + { + return Flags{static_cast(bits_ ^ o.bits_)}; + } + [[nodiscard]] constexpr Flags operator~() const noexcept + { + return Flags{static_cast(~bits_)}; + } - constexpr Flags& operator|=(Flags o) noexcept { bits_ |= o.bits_; return *this; } - constexpr Flags& operator&=(Flags o) noexcept { bits_ &= o.bits_; return *this; } - constexpr Flags& operator^=(Flags o) noexcept { bits_ ^= o.bits_; return *this; } + [[nodiscard]] constexpr Flags operator|(E bit) const noexcept + { + return *this | Flags{bit}; + } + [[nodiscard]] constexpr Flags operator&(E bit) const noexcept + { + return *this & Flags{bit}; + } + [[nodiscard]] constexpr Flags operator^(E bit) const noexcept + { + return *this ^ Flags { bit }; + } - constexpr Flags& operator|=(E bit) noexcept { return set(bit); } - constexpr Flags& operator&=(E bit) noexcept { bits_ &= static_cast(bit); return *this; } - constexpr Flags& operator^=(E bit) noexcept { return toggle(bit); } + constexpr Flags& operator|=(Flags o) noexcept + { + bits_ |= o.bits_; + return *this; + } + constexpr Flags& operator&=(Flags o) noexcept + { + bits_ &= o.bits_; + return *this; + } + constexpr Flags& operator^=(Flags o) noexcept + { + bits_ ^= o.bits_; + return *this; + } - [[nodiscard]] constexpr bool operator==(const Flags&) const noexcept = default; - [[nodiscard]] constexpr explicit operator bool() const noexcept { return any(); } + constexpr Flags& operator|=(E bit) noexcept { return set(bit); } + constexpr Flags& operator&=(E bit) noexcept + { + bits_ &= static_cast(bit); + return *this; + } + constexpr Flags& operator^=(E bit) noexcept { return toggle(bit); } -private: - underlying bits_{0}; -}; + [[nodiscard]] constexpr bool + operator==(const Flags&) const noexcept = default; + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return any(); + } -// ── make_flags — convenience factory ───────────────────────────────────────── + private: -template - requires std::is_enum_v -[[nodiscard]] constexpr Flags make_flags(std::initializer_list list) noexcept -{ - return Flags{list}; -} + underlying bits_{0}; + }; -template - requires std::is_enum_v -[[nodiscard]] constexpr Flags operator|(E a, E b) noexcept -{ - return Flags{a} | Flags{b}; -} + // ── make_flags — convenience factory + // ───────────────────────────────────────── + + template + requires std::is_enum_v + [[nodiscard]] constexpr Flags + make_flags(std::initializer_list list) noexcept + { + return Flags{list}; + } + + template + requires std::is_enum_v + [[nodiscard]] constexpr Flags operator|(E a, E b) noexcept + { + return Flags{a} | Flags{b}; + } + + // ── reflective names (Void::Meta enum reflection) + // ──────────────────────────── + +#ifdef VOID_HAS_META_REFLECTION + + /// Render the set bits as their enumerator names, joined by `sep` + /// (e.g. "Read|Write"). A zero-valued enumerator never appears. + template + requires std::is_enum_v + [[nodiscard]] std::string to_string(Flags f, std::string_view sep = "|") + { + std::string out; + for (const auto& [value, name] : Void::Meta::enum_entries()) { + if (f.test(value)) { + if (!out.empty()) { + out += sep; + } + out += name; + } + } + return out; + } + + /// Parse a `sep`-separated list of enumerator names into a Flags. + /// Unknown names are ignored. + template + requires std::is_enum_v + [[nodiscard]] Flags parse(std::string_view text, char sep = '|') + { + Flags f; + std::size_t pos = 0; + while (pos <= text.size()) { + const auto next = text.find(sep, pos); + const auto end = + (next == std::string_view::npos) ? text.size() : next; + const auto token = text.substr(pos, end - pos); + if (!token.empty()) { + if (const auto e = Void::Meta::enum_parse(token); + e.has_value()) { + f.set(*e); + } + } + if (next == std::string_view::npos) { + break; + } + pos = next + 1; + } + return f; + } + +#endif // VOID_HAS_META_REFLECTION } // namespace Void::Flags diff --git a/include/Void/Core/Meta.hpp b/include/Void/Core/Meta.hpp new file mode 100644 index 0000000..660edeb --- /dev/null +++ b/include/Void/Core/Meta.hpp @@ -0,0 +1,351 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#define VOID_HAS_META_REFLECTION 1 +#endif + +// ── Void::Meta +// ──────────────────────────────────────────────────────────────── The shared +// C++26 P2996 reflection layer for VoidLibrary. One place for the member walk, +// leaf-shape traits, annotation helpers, generic algorithms over data members +// (equal / compare / hash / repr) and enum utilities. Every other module that +// reflects structs or enums builds on this (Data/Json, Configuration/Bind, +// Functional/Repr, Math, Text, Log, Time, ...). +// +// Annotations carry a value-based fixed-capacity string (`Meta::Str`) because +// std::string_view is not a structural type and a const char* payload cannot be +// promoted to a constant; domain vocabularies (json::Rename, config::Key, +// arg::Help, ...) are small structs over `Str`. + +namespace Void::Meta +{ + // ── leaf / container shape traits (single source) ───────────────────── + template inline constexpr bool is_optional_v = false; + template + inline constexpr bool is_optional_v> = true; + + template inline constexpr bool is_vector_v = false; + template inline constexpr bool is_vector_v> = true; + + template inline constexpr bool is_string_map_v = false; + template + inline constexpr bool is_string_map_v> = true; + + template inline constexpr bool is_duration_v = false; + template + inline constexpr bool is_duration_v> = true; + + template inline constexpr bool is_time_point_v = false; + template + inline constexpr bool is_time_point_v> = true; + + template inline constexpr bool is_variant_v = false; + template + inline constexpr bool is_variant_v> = true; + + template inline constexpr bool is_std_array_v = false; + template + inline constexpr bool is_std_array_v> = true; + + // A keyed map whose key is *not* std::string. String-keyed maps stay on the + // dedicated is_string_map_v object path; these serialize as an array of + // {key, value} pairs so an arbitrary reflectable key type works. + template inline constexpr bool is_map_v = false; + template + inline constexpr bool is_map_v> = + !std::same_as; + template + inline constexpr bool is_map_v> = + !std::same_as; + + template + concept Leaf = std::same_as || std::is_arithmetic_v || + std::is_enum_v || std::same_as; + +#ifdef VOID_HAS_META_REFLECTION + + namespace meta = std::meta; + + // ── member walk (the single reflection of a struct's data members) ──── + template + inline constexpr auto members_v = + std::define_static_array(meta::nonstatic_data_members_of( + ^^T, meta::access_context::unchecked())); + + /// Number of non-static data members of T. + template [[nodiscard]] consteval std::size_t field_count() + { + return members_v.size(); + } + + /// A class type with at least one reflectable data member. + template + concept Struct = + (std::is_class_v || std::is_union_v) && (field_count() > 0); + + /// Identifier of a data-member reflection. + [[nodiscard]] consteval std::string_view field_name(meta::info m) + { + return meta::identifier_of(m); + } + + /// The declared field names of T (in declaration order). + template + [[nodiscard]] std::vector field_names() + { + std::vector out; + out.reserve(field_count()); + template for (constexpr auto m : members_v) + { + out.push_back(meta::identifier_of(m)); + } + return out; + } + + /// Invoke `fn(name, fieldref)` for each data member of `obj` + /// (mutable or const depending on `obj`). + template void for_each_field(T&& obj, Fn&& fn) + { + using U = std::remove_reference_t; + template for (constexpr auto m : members_v) + { + fn(std::string_view{meta::identifier_of(m)}, obj.[:m:]); + } + } + + // ── annotations ─────────────────────────────────────────────────────── + /// Value-based fixed-capacity string usable as an annotation payload + /// (structural; copies up to 63 chars). + struct Str { + char data[64]{}; + std::size_t len{}; + consteval Str(const char* s) + { + while (s[len] != '\0' && len < 63) { + data[len] = s[len]; + ++len; + } + } + [[nodiscard]] constexpr std::string_view view() const + { + return {data, len}; + } + [[nodiscard]] constexpr operator std::string_view() const + { + return view(); + } + }; + + /// True if reflection `m` carries an annotation of type `Tag`. + template + [[nodiscard]] consteval bool has_annotation(meta::info m) + { + return !meta::annotations_of_with_type(m, ^^Tag).empty(); + } + + /// The first `Tag` annotation on `m` (its value), or nullopt. + template + [[nodiscard]] consteval std::optional annotation_of(meta::info m) + { + for (meta::info a : meta::annotations_of_with_type(m, ^^Tag)) { + return meta::extract(a); + } + return std::nullopt; + } + + /// The (unqualified) name of a type, e.g. type_name() == "Foo". + template [[nodiscard]] std::string type_name() + { + if constexpr (meta::has_identifier(^^T)) { + return std::string{meta::identifier_of(^^T)}; + } else { + return std::string{meta::display_string_of(^^T)}; + } + } + + // ── enum utilities (extend Void::Detail enum reflection) ────────────── + using Void::Detail::enum_cast; + using Void::Detail::enum_name; + using Void::Detail::enum_parse; + + /// Number of enumerators of E. + template + requires std::is_enum_v + inline constexpr std::size_t enum_count = meta::enumerators_of(^^E).size(); + + /// The enumerator values of E (declaration order). + template + requires std::is_enum_v + [[nodiscard]] consteval std::array> enum_values() + { + std::array> out{}; + std::size_t i = 0; + template for (constexpr auto e : + std::define_static_array(meta::enumerators_of(^^E))) + { + out[i++] = [:e:]; + } + return out; + } + + /// (value, identifier) pairs for every enumerator of E (declaration order). + template + requires std::is_enum_v + [[nodiscard]] std::array, enum_count> + enum_entries() + { + std::array, enum_count> out{}; + std::size_t i = 0; + template for (constexpr auto e : + std::define_static_array(meta::enumerators_of(^^E))) + { + out[i++] = {[:e:], meta::identifier_of(e)}; + } + return out; + } + +#else // no reflection + + template + concept Struct = false; + +#endif // VOID_HAS_META_REFLECTION + + // ── repr (diagnostic rendering) ─────────────────────────────────────── + // 1. std::formatter → std::format. 2. a .format() method. 3. reflect + // the data members as `Type{a: 1, b: 2}`. 4. "". + template [[nodiscard]] std::string repr(const T& value); + + template + concept Formattable = std::formattable; + + template + concept HasFormatMethod = requires(const T& v) { + { v.format() } -> std::convertible_to; + }; + +#ifdef VOID_HAS_META_REFLECTION + template [[nodiscard]] std::string reflect_struct(const T& obj) + { + std::string out; + if constexpr (meta::has_identifier(^^T)) { + out += meta::identifier_of(^^T); + } else { + out += "?"; + } + out += '{'; + bool first = true; + template for (constexpr auto m : members_v) + { + if (!first) { + out += ", "; + } + out += meta::identifier_of(m); + out += ": "; + out += repr(obj.[:m:]); + first = false; + } + out += '}'; + return out; + } +#endif + + template [[nodiscard]] std::string repr(const T& value) + { + if constexpr (Formattable) { + return std::format("{}", value); + } else if constexpr (HasFormatMethod) { + return std::string{value.format()}; + } +#ifdef VOID_HAS_META_REFLECTION + else if constexpr (std::is_class_v || std::is_union_v) { + return reflect_struct(value); + } +#endif + else { + return ""; + } + } + + // ── generic algorithms over data members ────────────────────────────── +#ifdef VOID_HAS_META_REFLECTION + + /// Member-wise equality for reflectable structs (recurses on members). + template [[nodiscard]] bool equal(const T& a, const T& b) + { + if constexpr (Struct && !Leaf) { + bool eq = true; + template for (constexpr auto m : members_v) + { + if (eq && !equal(a.[:m:], b.[:m:])) { + eq = false; + } + } + return eq; + } else { + return a == b; + } + } + + /// Lexicographic member-wise ordering for reflectable structs. + template + [[nodiscard]] std::strong_ordering compare(const T& a, const T& b) + { + if constexpr (Struct && !Leaf) { + std::strong_ordering result = std::strong_ordering::equal; + template for (constexpr auto m : members_v) + { + if (result == std::strong_ordering::equal) { + result = compare(a.[:m:], b.[:m:]); + } + } + return result; + } else { + return a <=> b; + } + } + + /// 64-bit member-folded hash for reflectable structs (recurses). + template [[nodiscard]] std::uint64_t hash(const T& v) + { + auto mix = [](std::uint64_t seed, std::uint64_t x) { + x ^= x >> 33; + x *= 0xff51afd7ed558ccdULL; + x ^= x >> 33; + return seed ^ + (x + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2)); + }; + if constexpr (Struct && !Leaf) { + std::uint64_t h = 0xcbf29ce484222325ULL; + template for (constexpr auto m : members_v) + { + h = mix(h, hash(v.[:m:])); + } + return h; + } else { + return static_cast(std::hash{}(v)); + } + } + +#endif // VOID_HAS_META_REFLECTION + +} // namespace Void::Meta diff --git a/include/Void/Data/Csv.hpp b/include/Void/Data/Csv.hpp index b47b191..ed495ad 100644 --- a/include/Void/Data/Csv.hpp +++ b/include/Void/Data/Csv.hpp @@ -1,5 +1,9 @@ #pragma once +#include + +#include +#include #include #include #include @@ -9,130 +13,227 @@ namespace Void::Csv { -using Row = std::vector; -using Table = std::vector; + using Row = std::vector; + using Table = std::vector; -// ── parse ───────────────────────────────────────────────────────────────────── -// RFC 4180-compatible parser. Fields may be quoted ("..."). CRLF and LF -// both accepted as row terminators. + // ── parse + // ───────────────────────────────────────────────────────────────────── RFC + // 4180-compatible parser. Fields may be quoted ("..."). CRLF and LF both + // accepted as row terminators. -[[nodiscard]] inline Table parse(std::string_view text, char delim = ',') -{ - Table result; - Row row; - std::string field; - bool in_quote = false; + [[nodiscard]] inline Table parse(std::string_view text, char delim = ',') + { + Table result; + Row row; + std::string field; + bool in_quote = false; - for (std::size_t i = 0; i < text.size(); ++i) { - const char c = text[i]; + for (std::size_t i = 0; i < text.size(); ++i) { + const char c = text[i]; - if (in_quote) { - if (c == '"') { - // Peek for doubled quote - if (i + 1 < text.size() && text[i + 1] == '"') { - field += '"'; ++i; - } else { - in_quote = false; - } - } else { - field += c; - } - } else { - if (c == '"') { - in_quote = true; - } else if (c == delim) { - row.push_back(std::move(field)); - field.clear(); - } else if (c == '\n') { - row.push_back(std::move(field)); - field.clear(); - result.push_back(std::move(row)); - row.clear(); - } else if (c == '\r') { - // skip CR in CRLF - } else { - field += c; - } - } - } + if (in_quote) { + if (c == '"') { + // Peek for doubled quote + if (i + 1 < text.size() && text[i + 1] == '"') { + field += '"'; + ++i; + } else { + in_quote = false; + } + } else { + field += c; + } + } else { + if (c == '"') { + in_quote = true; + } else if (c == delim) { + row.push_back(std::move(field)); + field.clear(); + } else if (c == '\n') { + row.push_back(std::move(field)); + field.clear(); + result.push_back(std::move(row)); + row.clear(); + } else if (c == '\r') { + // skip CR in CRLF + } else { + field += c; + } + } + } - // Flush last field/row - row.push_back(std::move(field)); - if (!row.empty() && !(row.size() == 1 && row[0].empty())) { - result.push_back(std::move(row)); - } + // Flush last field/row + row.push_back(std::move(field)); + if (!row.empty() && !(row.size() == 1 && row[0].empty())) { + result.push_back(std::move(row)); + } - return result; -} + return result; + } -// ── serialize ───────────────────────────────────────────────────────────────── -// Produces RFC 4180 CSV. Fields that contain the delimiter, quote, or newline -// are wrapped in double quotes; embedded quotes are doubled. + // ── serialize + // ───────────────────────────────────────────────────────────────── + // Produces RFC 4180 CSV. Fields that contain the delimiter, quote, or + // newline are wrapped in double quotes; embedded quotes are doubled. -[[nodiscard]] inline std::string serialize(const Table& table, - char delim = ',') -{ - std::string out; - for (const auto& row : table) { - for (std::size_t i = 0; i < row.size(); ++i) { - const auto& field = row[i]; - const bool needs_quote = - field.find(delim) != std::string::npos || - field.find('"') != std::string::npos || - field.find('\n') != std::string::npos || - field.find('\r') != std::string::npos; - if (needs_quote) { - out += '"'; - for (char c : field) { - if (c == '"') out += '"'; - out += c; - } - out += '"'; - } else { - out += field; - } - if (i + 1 < row.size()) out += delim; - } - out += '\n'; - } - return out; -} + [[nodiscard]] inline std::string serialize(const Table& table, + char delim = ',') + { + std::string out; + for (const auto& row : table) { + for (std::size_t i = 0; i < row.size(); ++i) { + const auto& field = row[i]; + const bool needs_quote = + field.find(delim) != std::string::npos || + field.find('"') != std::string::npos || + field.find('\n') != std::string::npos || + field.find('\r') != std::string::npos; + if (needs_quote) { + out += '"'; + for (char c : field) { + if (c == '"') { + out += '"'; + } + out += c; + } + out += '"'; + } else { + out += field; + } + if (i + 1 < row.size()) { + out += delim; + } + } + out += '\n'; + } + return out; + } -// ── with_header convenience ─────────────────────────────────────────────────── + // ── with_header convenience + // ─────────────────────────────────────────────────── -struct CsvWithHeader -{ - Row header; - Table rows; + struct CsvWithHeader { + Row header; + Table rows; - [[nodiscard]] std::optional - col_index(std::string_view name) const - { - for (std::size_t i = 0; i < header.size(); ++i) { - if (header[i] == name) return i; - } - return std::nullopt; - } + [[nodiscard]] std::optional + col_index(std::string_view name) const + { + for (std::size_t i = 0; i < header.size(); ++i) { + if (header[i] == name) { + return i; + } + } + return std::nullopt; + } - [[nodiscard]] std::optional - get(const Row& row, std::string_view name) const - { - auto idx = col_index(name); - if (!idx || *idx >= row.size()) return std::nullopt; - return row[*idx]; - } -}; + [[nodiscard]] std::optional + get(const Row& row, std::string_view name) const + { + auto idx = col_index(name); + if (!idx || *idx >= row.size()) { + return std::nullopt; + } + return row[*idx]; + } + }; -[[nodiscard]] inline std::optional - parse_with_header(std::string_view text, char delim = ',') -{ - auto table = parse(text, delim); - if (table.empty()) return std::nullopt; - CsvWithHeader result; - result.header = std::move(table[0]); - result.rows.assign(std::make_move_iterator(table.begin() + 1), - std::make_move_iterator(table.end())); - return result; -} + [[nodiscard]] inline std::optional + parse_with_header(std::string_view text, char delim = ',') + { + auto table = parse(text, delim); + if (table.empty()) { + return std::nullopt; + } + CsvWithHeader result; + result.header = std::move(table[0]); + result.rows.assign(std::make_move_iterator(table.begin() + 1), + std::make_move_iterator(table.end())); + return result; + } + + // ── reflective struct ↔ row + // ─────────────────────────────────────────────────── Map a flat aggregate + // to/from a CSV Row by reflecting its data members (column order = + // declaration order; header = field names). Supported field types: + // std::string, arithmetic, bool. + +#ifdef VOID_HAS_META_REFLECTION + + namespace Detail + { + template + [[nodiscard]] std::string cell_to_string(const F& f) + { + if constexpr (std::same_as) { + return f; + } else if constexpr (std::same_as) { + return f ? "true" : "false"; + } else if constexpr (std::is_arithmetic_v) { + return std::format("{}", f); + } else { + return Void::Meta::repr(f); + } + } + + template + [[nodiscard]] bool cell_from_string(std::string_view s, F& f) + { + if constexpr (std::same_as) { + f = std::string{s}; + return true; + } else if constexpr (std::same_as) { + f = (s == "true" || s == "1"); + return true; + } else if constexpr (std::is_integral_v) { + return std::from_chars(s.data(), s.data() + s.size(), f).ec == + std::errc{}; + } else if constexpr (std::is_floating_point_v) { + return std::from_chars(s.data(), s.data() + s.size(), f).ec == + std::errc{}; + } else { + return false; + } + } + } // namespace Detail + + /// The header row (field names) for T. + template [[nodiscard]] Row header_row() + { + Row h; + for (auto name : Void::Meta::field_names()) { + h.emplace_back(name); + } + return h; + } + + /// Stringify a struct into a CSV Row (declaration order). + template [[nodiscard]] Row to_row(const T& v) + { + Row r; + Void::Meta::for_each_field(v, [&](std::string_view, const auto& f) { + r.push_back(Detail::cell_to_string(f)); + }); + return r; + } + + /// Parse a CSV Row back into a struct (by position). Returns nullopt if any + /// cell fails to convert. + template + [[nodiscard]] std::optional from_row(const Row& row) + { + T out{}; + std::size_t i = 0; + bool ok = true; + Void::Meta::for_each_field(out, [&](std::string_view, auto& f) { + if (i < row.size()) { + ok = Detail::cell_from_string(row[i], f) && ok; + } + ++i; + }); + return ok ? std::optional{std::move(out)} : std::nullopt; + } + +#endif // VOID_HAS_META_REFLECTION } // namespace Void::Csv diff --git a/include/Void/Data/Json.hpp b/include/Void/Data/Json.hpp index e5550a8..c02b3ab 100644 --- a/include/Void/Data/Json.hpp +++ b/include/Void/Data/Json.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -17,427 +18,989 @@ namespace Void::Json { -// ── Value ───────────────────────────────────────────────────────────────────── + // ── Value + // ───────────────────────────────────────────────────────────────────── -class Value; + class Value; -struct ParseError { - std::size_t line{1}, col{1}; - std::string message; -}; + struct ParseError { + std::size_t line{1}, col{1}; + std::string message; + }; -class Value -{ -public: - using Array_t = std::vector; - using Object_t = std::vector>; + class Value + { + public: -private: - using Data = std::variant< - std::monostate, // null - bool, // bool - double, // number - std::string, // string - std::unique_ptr, // array (boxed to avoid incomplete-type issues) - std::unique_ptr // object (same) - >; - Data data_{}; + using Array_t = std::vector; + using Object_t = std::vector>; - static Data clone(const Data& src) - { - return std::visit([](const auto& v) -> Data { - using T = std::decay_t; - if constexpr (std::is_same_v>) - return std::make_unique(*v); - else if constexpr (std::is_same_v>) - return std::make_unique(*v); - else - return v; - }, src); - } + private: -public: - // ── construction ────────────────────────────────────────────────────────── - Value() noexcept = default; - Value(std::nullptr_t) noexcept {} - Value(bool b) noexcept : data_{b} {} - Value(double n) noexcept : data_{n} {} - Value(int n) noexcept : data_{static_cast(n)} {} - Value(long long n) noexcept : data_{static_cast(n)} {} - Value(std::string s) : data_{std::move(s)} {} - Value(std::string_view s) : data_{std::string{s}} {} - Value(const char* s) : data_{std::string{s}} {} - Value(Array_t a) : data_{std::make_unique(std::move(a))} {} - Value(Object_t o) : data_{std::make_unique(std::move(o))} {} + using Data = + std::variant, // array (boxed to avoid + // incomplete-type + // issues) + std::unique_ptr // object (same) + >; + Data data_{}; - Value(const Value& o) : data_{clone(o.data_)} {} - Value& operator=(const Value& o) { if (this != &o) data_ = clone(o.data_); return *this; } - Value(Value&&) noexcept = default; - Value& operator=(Value&&) noexcept = default; - ~Value() = default; + static Data clone(const Data& src) + { + return std::visit( + [](const auto& v) -> Data { + using T = std::decay_t; + if constexpr (std::is_same_v< + T, std::unique_ptr>) { + return std::make_unique(*v); + } else if constexpr (std::is_same_v>) { + return std::make_unique(*v); + } else { + return v; + } + }, + src); + } - // ── type query ──────────────────────────────────────────────────────────── - [[nodiscard]] bool is_null() const noexcept { return data_.index() == 0; } - [[nodiscard]] bool is_bool() const noexcept { return data_.index() == 1; } - [[nodiscard]] bool is_number() const noexcept { return data_.index() == 2; } - [[nodiscard]] bool is_string() const noexcept { return data_.index() == 3; } - [[nodiscard]] bool is_array() const noexcept { return data_.index() == 4; } - [[nodiscard]] bool is_object() const noexcept { return data_.index() == 5; } + public: - // ── typed access (throws std::bad_variant_access on wrong type) ─────────── - [[nodiscard]] bool as_bool() const { return std::get(data_); } - [[nodiscard]] double as_number() const { return std::get(data_); } - [[nodiscard]] std::int64_t as_int() const { return static_cast(as_number()); } - [[nodiscard]] const std::string& as_string() const { return std::get(data_); } - [[nodiscard]] const Array_t& as_array() const { return *std::get>(data_); } - [[nodiscard]] const Object_t& as_object() const { return *std::get>(data_); } - [[nodiscard]] Array_t& as_array() { return *std::get>(data_); } - [[nodiscard]] Object_t& as_object() { return *std::get>(data_); } + // ── construction + // ────────────────────────────────────────────────────────── + Value() noexcept = default; + Value(std::nullptr_t) noexcept {} + Value(bool b) noexcept : data_{b} {} + Value(double n) noexcept : data_{n} {} + Value(int n) noexcept : data_{static_cast(n)} {} + Value(long long n) noexcept : data_{static_cast(n)} {} + Value(std::string s) : data_{std::move(s)} {} + Value(std::string_view s) : data_{std::string{s}} {} + Value(const char* s) : data_{std::string{s}} {} + Value(Array_t a) : data_{std::make_unique(std::move(a))} {} + Value(Object_t o) : data_{std::make_unique(std::move(o))} + { + } - // ── optional access ─────────────────────────────────────────────────────── - [[nodiscard]] std::optional get_bool() const noexcept { if (!is_bool()) return {}; return as_bool(); } - [[nodiscard]] std::optional get_number() const noexcept { if (!is_number()) return {}; return as_number(); } - [[nodiscard]] std::optional get_string() const noexcept { if (!is_string()) return {}; return as_string(); } + Value(const Value& o) : data_{clone(o.data_)} {} + Value& operator=(const Value& o) + { + if (this != &o) { + data_ = clone(o.data_); + } + return *this; + } + Value(Value&&) noexcept = default; + Value& operator=(Value&&) noexcept = default; + ~Value() = default; - // ── subscript (array by index, object by key) ───────────────────────────── - [[nodiscard]] const Value& operator[](std::size_t i) const { return as_array().at(i); } - [[nodiscard]] Value& operator[](std::size_t i) { return as_array().at(i); } + // ── type query + // ──────────────────────────────────────────────────────────── + [[nodiscard]] bool is_null() const noexcept + { + return data_.index() == 0; + } + [[nodiscard]] bool is_bool() const noexcept + { + return data_.index() == 1; + } + [[nodiscard]] bool is_number() const noexcept + { + return data_.index() == 2; + } + [[nodiscard]] bool is_string() const noexcept + { + return data_.index() == 3; + } + [[nodiscard]] bool is_array() const noexcept + { + return data_.index() == 4; + } + [[nodiscard]] bool is_object() const noexcept + { + return data_.index() == 5; + } - [[nodiscard]] const Value* find(std::string_view key) const noexcept - { - if (!is_object()) return nullptr; - for (const auto& [k, v] : as_object()) - if (k == key) return &v; - return nullptr; - } - [[nodiscard]] Value* find(std::string_view key) noexcept - { - if (!is_object()) return nullptr; - for (auto& [k, v] : as_object()) - if (k == key) return &v; - return nullptr; - } + // ── typed access (throws std::bad_variant_access on wrong type) + // ─────────── + [[nodiscard]] bool as_bool() const { return std::get(data_); } + [[nodiscard]] double as_number() const + { + return std::get(data_); + } + [[nodiscard]] std::int64_t as_int() const + { + return static_cast(as_number()); + } + [[nodiscard]] const std::string& as_string() const + { + return std::get(data_); + } + [[nodiscard]] const Array_t& as_array() const + { + return *std::get>(data_); + } + [[nodiscard]] const Object_t& as_object() const + { + return *std::get>(data_); + } + [[nodiscard]] Array_t& as_array() + { + return *std::get>(data_); + } + [[nodiscard]] Object_t& as_object() + { + return *std::get>(data_); + } - [[nodiscard]] const Value& operator[](std::string_view key) const - { - const auto* p = find(key); - if (!p) throw std::out_of_range{std::string{"key not found: "} + std::string{key}}; - return *p; - } + // ── optional access + // ─────────────────────────────────────────────────────── + [[nodiscard]] std::optional get_bool() const noexcept + { + if (!is_bool()) { + return {}; + } + return as_bool(); + } + [[nodiscard]] std::optional get_number() const noexcept + { + if (!is_number()) { + return {}; + } + return as_number(); + } + [[nodiscard]] std::optional + get_string() const noexcept + { + if (!is_string()) { + return {}; + } + return as_string(); + } - [[nodiscard]] std::size_t size() const noexcept - { - if (is_array()) return as_array().size(); - if (is_object()) return as_object().size(); - if (is_string()) return as_string().size(); - return 0; - } - [[nodiscard]] bool empty() const noexcept { return size() == 0; } + // ── subscript (array by index, object by key) + // ───────────────────────────── + [[nodiscard]] const Value& operator[](std::size_t i) const + { + return as_array().at(i); + } + [[nodiscard]] Value& operator[](std::size_t i) + { + return as_array().at(i); + } - [[nodiscard]] bool operator==(const Value& o) const noexcept - { - if (data_.index() != o.data_.index()) return false; - if (is_array()) return as_array() == o.as_array(); - if (is_object()) return as_object() == o.as_object(); - // For monostate, bool, double, string — variant equality works - return std::visit([&](const auto& lhs) -> bool { - using T = std::decay_t; - if constexpr (std::is_same_v> || - std::is_same_v>) - return false; // unreachable (handled above) - else - return lhs == std::get(o.data_); - }, data_); - } -}; + [[nodiscard]] const Value* find(std::string_view key) const noexcept + { + if (!is_object()) { + return nullptr; + } + for (const auto& [k, v] : as_object()) { + if (k == key) { + return &v; + } + } + return nullptr; + } + [[nodiscard]] Value* find(std::string_view key) noexcept + { + if (!is_object()) { + return nullptr; + } + for (auto& [k, v] : as_object()) { + if (k == key) { + return &v; + } + } + return nullptr; + } -// ── static factories ────────────────────────────────────────────────────────── -[[nodiscard]] inline Value array(Value::Array_t a = {}) { return Value{std::move(a)}; } -[[nodiscard]] inline Value object(Value::Object_t o = {}) { return Value{std::move(o)}; } + [[nodiscard]] const Value& operator[](std::string_view key) const + { + const auto* p = find(key); + if (!p) { + throw std::out_of_range{std::string{"key not found: "} + + std::string{key}}; + } + return *p; + } -// ── parse ───────────────────────────────────────────────────────────────────── + // ── JSON Pointer (RFC 6901) query + // ───────────────────────────────────────── at("/a/b/0") walks + // object keys and array indices. Returns nullptr if any step is + // missing or type-mismatched. The empty pointer "" yields the whole + // document. Tokens unescape "~1" -> '/' and "~0" -> '~'. + [[nodiscard]] const Value* + at(std::string_view pointer) const noexcept + { + const Value* cur = this; + if (pointer.empty()) { + return cur; + } + if (pointer.front() != '/') { + return nullptr; + } + std::size_t pos = 1; + for (;;) { + const std::size_t slash = pointer.find('/', pos); + const std::string_view raw = + pointer.substr(pos, slash == std::string_view::npos + ? std::string_view::npos + : slash - pos); + std::string token; + token.reserve(raw.size()); + for (std::size_t i = 0; i < raw.size(); ++i) { + if (raw[i] == '~' && i + 1 < raw.size()) { + if (raw[i + 1] == '1') { + token += '/'; + ++i; + continue; + } + if (raw[i + 1] == '0') { + token += '~'; + ++i; + continue; + } + } + token += raw[i]; + } + if (cur->is_object()) { + cur = cur->find(token); + if (!cur) { + return nullptr; + } + } else if (cur->is_array()) { + std::size_t idx = 0; + const char* b = token.data(); + const char* e = b + token.size(); + const auto [p, ec] = std::from_chars(b, e, idx); + if (ec != std::errc{} || p != e || + idx >= cur->as_array().size()) { + return nullptr; + } + cur = &cur->as_array()[idx]; + } else { + return nullptr; + } + if (slash == std::string_view::npos) { + break; + } + pos = slash + 1; + } + return cur; + } -namespace Detail -{ + [[nodiscard]] std::size_t size() const noexcept + { + if (is_array()) { + return as_array().size(); + } + if (is_object()) { + return as_object().size(); + } + if (is_string()) { + return as_string().size(); + } + return 0; + } + [[nodiscard]] bool empty() const noexcept { return size() == 0; } -struct Parser -{ - std::string_view src; - std::size_t pos{0}, line{1}, col{1}; + [[nodiscard]] bool operator==(const Value& o) const noexcept + { + if (data_.index() != o.data_.index()) { + return false; + } + if (is_array()) { + return as_array() == o.as_array(); + } + if (is_object()) { + return as_object() == o.as_object(); + } + // For monostate, bool, double, string — variant equality works + return std::visit( + [&](const auto& lhs) -> bool { + using T = std::decay_t; + if constexpr (std::is_same_v< + T, std::unique_ptr> || + std::is_same_v< + T, std::unique_ptr>) { + return false; // unreachable (handled above) + } else { + return lhs == std::get(o.data_); + } + }, + data_); + } + }; - [[nodiscard]] char peek() const noexcept { return pos < src.size() ? src[pos] : '\0'; } + // ── static factories + // ────────────────────────────────────────────────────────── + [[nodiscard]] inline Value array(Value::Array_t a = {}) + { + return Value{std::move(a)}; + } + [[nodiscard]] inline Value object(Value::Object_t o = {}) + { + return Value{std::move(o)}; + } - char advance() noexcept - { - const char c = src[pos++]; - if (c == '\n') { ++line; col = 1; } else ++col; - return c; - } + // ── parse + // ───────────────────────────────────────────────────────────────────── - bool at_end() const noexcept { return pos >= src.size(); } + namespace Detail + { - void skip_ws() noexcept - { - while (!at_end() && (peek() == ' ' || peek() == '\t' || peek() == '\n' || peek() == '\r')) - advance(); - } + struct Parser { + std::string_view src; + std::size_t pos{0}, line{1}, col{1}; - ParseError err(std::string msg) const { return {line, col, std::move(msg)}; } + [[nodiscard]] char peek() const noexcept + { + return pos < src.size() ? src[pos] : '\0'; + } - bool match(std::string_view lit) noexcept - { - if (pos + lit.size() > src.size()) return false; - if (src.substr(pos, lit.size()) != lit) return false; - for (std::size_t i = 0; i < lit.size(); ++i) advance(); - return true; - } + char advance() noexcept + { + const char c = src[pos++]; + if (c == '\n') { + ++line; + col = 1; + } else { + ++col; + } + return c; + } - std::expected parse_value() - { - skip_ws(); - if (at_end()) return std::unexpected{err("unexpected end of input")}; - const char c = peek(); - if (c == 'n') return parse_literal("null", Value{nullptr}); - if (c == 't') return parse_literal("true", Value{true}); - if (c == 'f') return parse_literal("false", Value{false}); - if (c == '"') return parse_string(); - if (c == '[') return parse_array(); - if (c == '{') return parse_object(); - if (c == '-' || (c >= '0' && c <= '9')) return parse_number(); - return std::unexpected{err(std::string{"unexpected character '"} + c + "'")}; - } + bool at_end() const noexcept { return pos >= src.size(); } - std::expected parse_literal(std::string_view lit, Value v) - { - if (!match(lit)) - return std::unexpected{err(std::string{"expected '"} + std::string{lit} + "'")}; - return v; - } + void skip_ws() noexcept + { + while (!at_end() && (peek() == ' ' || peek() == '\t' || + peek() == '\n' || peek() == '\r')) { + advance(); + } + } - std::expected parse_number() - { - const std::size_t start = pos; - if (peek() == '-') advance(); - if (peek() == '0') { advance(); } - else { while (peek() >= '1' && peek() <= '9') advance(); while (peek() >= '0' && peek() <= '9') advance(); } - if (peek() == '.') { advance(); while (peek() >= '0' && peek() <= '9') advance(); } - if (peek() == 'e' || peek() == 'E') { - advance(); - if (peek() == '+' || peek() == '-') advance(); - while (peek() >= '0' && peek() <= '9') advance(); - } - const std::string_view raw = src.substr(start, pos - start); - double val = 0.0; - const auto [ptr, ec] = std::from_chars(raw.data(), raw.data() + raw.size(), val); - if (ec != std::errc{}) - return std::unexpected{err("invalid number: " + std::string{raw})}; - return Value{val}; - } + ParseError err(std::string msg) const + { + return {line, col, std::move(msg)}; + } - std::expected parse_string_raw() - { - if (peek() != '"') return std::unexpected{err("expected '\"'")}; - advance(); // consume opening quote - std::string out; - while (!at_end() && peek() != '"') { - const char c = advance(); - if (c != '\\') { out += c; continue; } - if (at_end()) return std::unexpected{err("unterminated escape")}; - const char esc = advance(); - switch (esc) { - case '"': out += '"'; break; - case '\\': out += '\\'; break; - case '/': out += '/'; break; - case 'b': out += '\b'; break; - case 'f': out += '\f'; break; - case 'n': out += '\n'; break; - case 'r': out += '\r'; break; - case 't': out += '\t'; break; - case 'u': { - if (pos + 4 > src.size()) return std::unexpected{err("incomplete \\uXXXX")}; - const auto hex = src.substr(pos, 4); - unsigned cp = 0; - const auto [p, e] = std::from_chars(hex.data(), hex.data() + 4, cp, 16); - if (e != std::errc{} || p != hex.data() + 4) - return std::unexpected{err("invalid \\uXXXX escape")}; - for (std::size_t i = 0; i < 4; ++i) advance(); - // Encode as UTF-8 - if (cp < 0x80) { - out += static_cast(cp); - } else if (cp < 0x800) { - out += static_cast(0xC0 | (cp >> 6)); - out += static_cast(0x80 | (cp & 0x3F)); - } else { - out += static_cast(0xE0 | (cp >> 12)); - out += static_cast(0x80 | ((cp >> 6) & 0x3F)); - out += static_cast(0x80 | (cp & 0x3F)); - } - break; - } - default: return std::unexpected{err(std::string{"unknown escape '\\"} + esc + "'")}; - } - } - if (at_end()) return std::unexpected{err("unterminated string")}; - advance(); // consume closing quote - return out; - } + bool match(std::string_view lit) noexcept + { + if (pos + lit.size() > src.size()) { + return false; + } + if (src.substr(pos, lit.size()) != lit) { + return false; + } + for (std::size_t i = 0; i < lit.size(); ++i) { + advance(); + } + return true; + } - std::expected parse_string() - { - auto r = parse_string_raw(); - if (!r) return std::unexpected{r.error()}; - return Value{std::move(*r)}; - } + std::expected parse_value() + { + skip_ws(); + if (at_end()) { + return std::unexpected{err("unexpected end of input")}; + } + const char c = peek(); + if (c == 'n') { + return parse_literal("null", Value{nullptr}); + } + if (c == 't') { + return parse_literal("true", Value{true}); + } + if (c == 'f') { + return parse_literal("false", Value{false}); + } + if (c == '"') { + return parse_string(); + } + if (c == '[') { + return parse_array(); + } + if (c == '{') { + return parse_object(); + } + if (c == '-' || (c >= '0' && c <= '9')) { + return parse_number(); + } + return std::unexpected{ + err(std::string{"unexpected character '"} + c + "'")}; + } - std::expected parse_array() - { - advance(); // '[' - Value::Array_t arr; - skip_ws(); - if (peek() == ']') { advance(); return Value{std::move(arr)}; } - while (true) { - auto v = parse_value(); - if (!v) return v; - arr.push_back(std::move(*v)); - skip_ws(); - if (peek() == ']') { advance(); break; } - if (peek() != ',') return std::unexpected{err("expected ',' or ']' in array")}; - advance(); - } - return Value{std::move(arr)}; - } + std::expected + parse_literal(std::string_view lit, Value v) + { + if (!match(lit)) { + return std::unexpected{err(std::string{"expected '"} + + std::string{lit} + "'")}; + } + return v; + } - std::expected parse_object() - { - advance(); // '{' - Value::Object_t obj; - skip_ws(); - if (peek() == '}') { advance(); return Value{std::move(obj)}; } - while (true) { - skip_ws(); - auto key = parse_string_raw(); - if (!key) return std::unexpected{key.error()}; - skip_ws(); - if (peek() != ':') return std::unexpected{err("expected ':' after object key")}; - advance(); - auto val = parse_value(); - if (!val) return val; - obj.emplace_back(std::move(*key), std::move(*val)); - skip_ws(); - if (peek() == '}') { advance(); break; } - if (peek() != ',') return std::unexpected{err("expected ',' or '}' in object")}; - advance(); - } - return Value{std::move(obj)}; - } -}; + std::expected parse_number() + { + const std::size_t start = pos; + if (peek() == '-') { + advance(); + } + if (peek() == '0') { + advance(); + } else { + while (peek() >= '1' && peek() <= '9') { + advance(); + } + while (peek() >= '0' && peek() <= '9') { + advance(); + } + } + if (peek() == '.') { + advance(); + while (peek() >= '0' && peek() <= '9') { + advance(); + } + } + if (peek() == 'e' || peek() == 'E') { + advance(); + if (peek() == '+' || peek() == '-') { + advance(); + } + while (peek() >= '0' && peek() <= '9') { + advance(); + } + } + const std::string_view raw = src.substr(start, pos - start); + double val = 0.0; + const auto [ptr, ec] = std::from_chars( + raw.data(), raw.data() + raw.size(), val); + if (ec != std::errc{}) { + return std::unexpected{ + err("invalid number: " + std::string{raw})}; + } + return Value{val}; + } -} // namespace Detail + std::expected parse_string_raw() + { + if (peek() != '"') { + return std::unexpected{err("expected '\"'")}; + } + advance(); // consume opening quote + std::string out; + while (!at_end() && peek() != '"') { + const char c = advance(); + if (c != '\\') { + out += c; + continue; + } + if (at_end()) { + return std::unexpected{err("unterminated escape")}; + } + const char esc = advance(); + switch (esc) { + case '"': + out += '"'; + break; + case '\\': + out += '\\'; + break; + case '/': + out += '/'; + break; + case 'b': + out += '\b'; + break; + case 'f': + out += '\f'; + break; + case 'n': + out += '\n'; + break; + case 'r': + out += '\r'; + break; + case 't': + out += '\t'; + break; + case 'u': + { + if (pos + 4 > src.size()) { + return std::unexpected{ + err("incomplete \\uXXXX")}; + } + const auto hex = src.substr(pos, 4); + unsigned cp = 0; + const auto [p, e] = std::from_chars( + hex.data(), hex.data() + 4, cp, 16); + if (e != std::errc{} || + p != hex.data() + 4) { + return std::unexpected{ + err("invalid \\uXXXX escape")}; + } + for (std::size_t i = 0; i < 4; ++i) { + advance(); + } + // Encode as UTF-8 + if (cp < 0x80) { + out += static_cast(cp); + } else if (cp < 0x800) { + out += + static_cast(0xC0 | (cp >> 6)); + out += static_cast(0x80 | + (cp & 0x3F)); + } else { + out += static_cast(0xE0 | + (cp >> 12)); + out += static_cast( + 0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | + (cp & 0x3F)); + } + break; + } + default: + return std::unexpected{ + err(std::string{"unknown escape '\\"} + + esc + "'")}; + } + } + if (at_end()) { + return std::unexpected{err("unterminated string")}; + } + advance(); // consume closing quote + return out; + } -[[nodiscard]] inline std::expected parse(std::string_view json) -{ - Detail::Parser p{json}; - auto r = p.parse_value(); - if (!r) return r; - p.skip_ws(); - if (!p.at_end()) - return std::unexpected{p.err("trailing characters after JSON value")}; - return r; -} + std::expected parse_string() + { + auto r = parse_string_raw(); + if (!r) { + return std::unexpected{r.error()}; + } + return Value{std::move(*r)}; + } -// ── serialize ───────────────────────────────────────────────────────────────── + std::expected parse_array() + { + advance(); // '[' + Value::Array_t arr; + skip_ws(); + if (peek() == ']') { + advance(); + return Value{std::move(arr)}; + } + while (true) { + auto v = parse_value(); + if (!v) { + return v; + } + arr.push_back(std::move(*v)); + skip_ws(); + if (peek() == ']') { + advance(); + break; + } + if (peek() != ',') { + return std::unexpected{ + err("expected ',' or ']' in array")}; + } + advance(); + } + return Value{std::move(arr)}; + } -struct SerializeOptions { - bool pretty{false}; - int indent_width{2}; -}; + std::expected parse_object() + { + advance(); // '{' + Value::Object_t obj; + skip_ws(); + if (peek() == '}') { + advance(); + return Value{std::move(obj)}; + } + while (true) { + skip_ws(); + auto key = parse_string_raw(); + if (!key) { + return std::unexpected{key.error()}; + } + skip_ws(); + if (peek() != ':') { + return std::unexpected{ + err("expected ':' after object key")}; + } + advance(); + auto val = parse_value(); + if (!val) { + return val; + } + obj.emplace_back(std::move(*key), std::move(*val)); + skip_ws(); + if (peek() == '}') { + advance(); + break; + } + if (peek() != ',') { + return std::unexpected{ + err("expected ',' or '}' in object")}; + } + advance(); + } + return Value{std::move(obj)}; + } + }; -namespace Detail -{ + } // namespace Detail -inline void escape_string(std::string& out, std::string_view s) -{ - out += '"'; - for (const unsigned char c : s) { - switch (c) { - case '"': out += "\\\""; break; - case '\\': out += "\\\\"; break; - case '\n': out += "\\n"; break; - case '\r': out += "\\r"; break; - case '\t': out += "\\t"; break; - case '\b': out += "\\b"; break; - case '\f': out += "\\f"; break; - default: - if (c < 0x20) { - out += "\\u00"; - const char hex[] = "0123456789abcdef"; - out += hex[c >> 4]; - out += hex[c & 0xF]; - } else { - out += static_cast(c); - } - } - } - out += '"'; -} + [[nodiscard]] inline std::expected + parse(std::string_view json) + { + Detail::Parser p{json}; + auto r = p.parse_value(); + if (!r) { + return r; + } + p.skip_ws(); + if (!p.at_end()) { + return std::unexpected{ + p.err("trailing characters after JSON value")}; + } + return r; + } -inline void serialize_impl(std::string& out, const Value& v, const SerializeOptions& opts, int depth) -{ - if (v.is_null()) { out += "null"; return; } - if (v.is_bool()) { out += v.as_bool() ? "true" : "false"; return; } - if (v.is_number()) { - const double n = v.as_number(); - if (std::floor(n) == n && std::abs(n) < 1e15) { - out += std::to_string(static_cast(n)); - } else { - char buf[32]; - const auto [ptr, ec] = std::to_chars(buf, buf + sizeof(buf), n, - std::chars_format::general, 17); - if (ec == std::errc{}) out.append(buf, ptr); - } - return; - } - if (v.is_string()) { escape_string(out, v.as_string()); return; } + // ── streaming (SAX) parse + // ────────────────────────────────────────────────────── Event-callback + // parser for large inputs: fires callbacks as tokens are scanned rather + // than building a DOM. Any unset callback is skipped. Returns a ParseError + // on malformed input, or nullopt on success. - const std::string nl = opts.pretty ? "\n" : ""; - const std::string sep = opts.pretty ? " " : ""; - auto indent = [&](int d) { - if (opts.pretty) out.append(static_cast(d * opts.indent_width), ' '); - }; + struct SaxHandler { + std::function on_null; + std::function on_bool; + std::function on_number; + std::function on_string; + std::function on_key; + std::function on_object_begin; + std::function on_object_end; + std::function on_array_begin; + std::function on_array_end; + }; - if (v.is_array()) { - out += '['; - const auto& arr = v.as_array(); - for (std::size_t i = 0; i < arr.size(); ++i) { - out += nl; indent(depth + 1); - serialize_impl(out, arr[i], opts, depth + 1); - if (i + 1 < arr.size()) out += ','; - } - if (!arr.empty()) { out += nl; indent(depth); } - out += ']'; - return; - } - // object - out += '{'; - const auto& obj = v.as_object(); - for (std::size_t i = 0; i < obj.size(); ++i) { - out += nl; indent(depth + 1); - escape_string(out, obj[i].first); - out += ':'; out += sep; - serialize_impl(out, obj[i].second, opts, depth + 1); - if (i + 1 < obj.size()) out += ','; - } - if (!obj.empty()) { out += nl; indent(depth); } - out += '}'; -} + namespace Detail + { -} // namespace Detail + // Drives the existing Parser's primitives, emitting events instead of a + // Value. + struct SaxDriver { + Parser p; + const SaxHandler& h; -[[nodiscard]] inline std::string serialize(const Value& v, SerializeOptions opts = {}) -{ - std::string out; - Detail::serialize_impl(out, v, opts, 0); - return out; -} + std::optional value() + { + p.skip_ws(); + if (p.at_end()) { + return p.err("unexpected end of input"); + } + const char c = p.peek(); + if (c == '{') { + return object(); + } + if (c == '[') { + return array(); + } + if (c == '"') { + auto s = p.parse_string_raw(); + if (!s) { + return s.error(); + } + if (h.on_string) { + h.on_string(*s); + } + return std::nullopt; + } + if (c == 'n') { + if (!p.match("null")) { + return p.err("expected 'null'"); + } + if (h.on_null) { + h.on_null(); + } + return std::nullopt; + } + if (c == 't') { + if (!p.match("true")) { + return p.err("expected 'true'"); + } + if (h.on_bool) { + h.on_bool(true); + } + return std::nullopt; + } + if (c == 'f') { + if (!p.match("false")) { + return p.err("expected 'false'"); + } + if (h.on_bool) { + h.on_bool(false); + } + return std::nullopt; + } + if (c == '-' || (c >= '0' && c <= '9')) { + auto v = p.parse_number(); + if (!v) { + return v.error(); + } + if (h.on_number) { + h.on_number(v->as_number()); + } + return std::nullopt; + } + return p.err(std::string{"unexpected character '"} + c + + "'"); + } + + std::optional array() + { + p.advance(); // '[' + if (h.on_array_begin) { + h.on_array_begin(); + } + p.skip_ws(); + if (p.peek() == ']') { + p.advance(); + if (h.on_array_end) { + h.on_array_end(); + } + return std::nullopt; + } + for (;;) { + if (auto e = value()) { + return e; + } + p.skip_ws(); + if (p.peek() == ']') { + p.advance(); + break; + } + if (p.peek() != ',') { + return p.err("expected ',' or ']' in array"); + } + p.advance(); + } + if (h.on_array_end) { + h.on_array_end(); + } + return std::nullopt; + } + + std::optional object() + { + p.advance(); // '{' + if (h.on_object_begin) { + h.on_object_begin(); + } + p.skip_ws(); + if (p.peek() == '}') { + p.advance(); + if (h.on_object_end) { + h.on_object_end(); + } + return std::nullopt; + } + for (;;) { + p.skip_ws(); + auto key = p.parse_string_raw(); + if (!key) { + return key.error(); + } + if (h.on_key) { + h.on_key(*key); + } + p.skip_ws(); + if (p.peek() != ':') { + return p.err("expected ':' after object key"); + } + p.advance(); + if (auto e = value()) { + return e; + } + p.skip_ws(); + if (p.peek() == '}') { + p.advance(); + break; + } + if (p.peek() != ',') { + return p.err("expected ',' or '}' in object"); + } + p.advance(); + } + if (h.on_object_end) { + h.on_object_end(); + } + return std::nullopt; + } + }; + + } // namespace Detail + + [[nodiscard]] inline std::optional + parse_sax(std::string_view json, const SaxHandler& handler) + { + Detail::SaxDriver d{Detail::Parser{json}, handler}; + if (auto e = d.value()) { + return e; + } + d.p.skip_ws(); + if (!d.p.at_end()) { + return d.p.err("trailing characters after JSON value"); + } + return std::nullopt; + } + + // ── serialize + // ───────────────────────────────────────────────────────────────── + + struct SerializeOptions { + bool pretty{false}; + int indent_width{2}; + }; + + namespace Detail + { + + inline void escape_string(std::string& out, std::string_view s) + { + out += '"'; + for (const unsigned char c : s) { + switch (c) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + case '\b': + out += "\\b"; + break; + case '\f': + out += "\\f"; + break; + default: + if (c < 0x20) { + out += "\\u00"; + const char hex[] = "0123456789abcdef"; + out += hex[c >> 4]; + out += hex[c & 0xF]; + } else { + out += static_cast(c); + } + } + } + out += '"'; + } + + inline void serialize_impl(std::string& out, const Value& v, + const SerializeOptions& opts, int depth) + { + if (v.is_null()) { + out += "null"; + return; + } + if (v.is_bool()) { + out += v.as_bool() ? "true" : "false"; + return; + } + if (v.is_number()) { + const double n = v.as_number(); + if (std::floor(n) == n && std::abs(n) < 1e15) { + out += std::to_string(static_cast(n)); + } else { + char buf[32]; + const auto [ptr, ec] = + std::to_chars(buf, buf + sizeof(buf), n, + std::chars_format::general, 17); + if (ec == std::errc{}) { + out.append(buf, ptr); + } + } + return; + } + if (v.is_string()) { + escape_string(out, v.as_string()); + return; + } + + const std::string nl = opts.pretty ? "\n" : ""; + const std::string sep = opts.pretty ? " " : ""; + auto indent = [&](int d) { + if (opts.pretty) { + out.append(static_cast(d * opts.indent_width), + ' '); + } + }; + + if (v.is_array()) { + out += '['; + const auto& arr = v.as_array(); + for (std::size_t i = 0; i < arr.size(); ++i) { + out += nl; + indent(depth + 1); + serialize_impl(out, arr[i], opts, depth + 1); + if (i + 1 < arr.size()) { + out += ','; + } + } + if (!arr.empty()) { + out += nl; + indent(depth); + } + out += ']'; + return; + } + // object + out += '{'; + const auto& obj = v.as_object(); + for (std::size_t i = 0; i < obj.size(); ++i) { + out += nl; + indent(depth + 1); + escape_string(out, obj[i].first); + out += ':'; + out += sep; + serialize_impl(out, obj[i].second, opts, depth + 1); + if (i + 1 < obj.size()) { + out += ','; + } + } + if (!obj.empty()) { + out += nl; + indent(depth); + } + out += '}'; + } + + } // namespace Detail + + [[nodiscard]] inline std::string serialize(const Value& v, + SerializeOptions opts = {}) + { + std::string out; + Detail::serialize_impl(out, v, opts, 0); + return out; + } } // namespace Void::Json diff --git a/include/Void/Data/Reflect.hpp b/include/Void/Data/Reflect.hpp index 4b2de92..6c31fcf 100644 --- a/include/Void/Data/Reflect.hpp +++ b/include/Void/Data/Reflect.hpp @@ -1,9 +1,14 @@ #pragma once +#include #include #include +#include +#include +#include #include +#include #include #include #include @@ -11,8 +16,10 @@ #include #include #include +#include #include #include +#include #include #if __has_include() @@ -20,7 +27,8 @@ #define VOID_HAS_JSON_REFLECTION 1 #endif -// ── Reflection → JSON ───────────────────────────────────────────────────────── +// ── Reflection → JSON +// ───────────────────────────────────────────────────────── // Serialize/deserialize aggregate structs to Json::Value using C++26 P2996 // reflection (GCC 16+, -freflection). Field names become object keys. // @@ -43,381 +51,575 @@ namespace Void::Json { -struct ReflectError { - std::string field; // dotted path of the offending field ("" if global) - std::string message; -}; + struct ReflectError { + std::string + field; // dotted path of the offending field ("" if global) + std::string message; + }; -// ── customization point ─────────────────────────────────────────────────────── + // ── field annotations + // ───────────────────────────────────────────────────────── Annotate + // aggregate members to control (de)serialization: + // struct User { + // [[= Json::Rename{"user_id"}]] int id; // JSON key override + // [[= Json::Skip{}]] int cache; // never + // (de)serialized + // [[= Json::Required{}]] std::string nm; // error if absent + // [[= Json::Flatten{}]] Address addr; // inline nested + // object + // }; + struct Rename { + Void::Meta::Str key; + }; + struct Skip { + }; + struct Required { + }; + struct Flatten { + }; -template -concept HasMemberToJson = requires(const T& t) { - { t.to_json() } -> std::same_as; -}; + // ── customization point + // ─────────────────────────────────────────────────────── -template -concept HasMemberFromJson = requires(const Value& v) { - { T::from_json(v) } -> std::same_as>; -}; + template + concept HasMemberToJson = requires(const T& t) { + { t.to_json() } -> std::same_as; + }; -// ── supported leaf / container shapes ───────────────────────────────────────── + template + concept HasMemberFromJson = requires(const Value& v) { + { T::from_json(v) } -> std::same_as>; + }; -namespace ReflectDetail -{ - template - struct IsOptional : std::false_type {}; - template - struct IsOptional> : std::true_type {}; - - template - struct IsVector : std::false_type {}; - template - struct IsVector> : std::true_type {}; - - template - struct IsStringMap : std::false_type {}; - template - struct IsStringMap> : std::true_type {}; -} // namespace ReflectDetail + // ── supported leaf / container shapes (single source: Void::Meta) + // ───────────── #ifdef VOID_HAS_JSON_REFLECTION -template -concept ReflectableAggregate = - std::is_aggregate_v && !std::is_array_v && - std::is_default_constructible_v; + template + concept ReflectableAggregate = + std::is_aggregate_v && !std::is_array_v && + std::is_default_constructible_v; #else -template -concept ReflectableAggregate = false; + template + concept ReflectableAggregate = false; #endif -template -concept JsonConvertible = - HasMemberToJson || std::same_as || std::is_arithmetic_v || - std::is_enum_v || std::same_as || - ReflectDetail::IsOptional::value || ReflectDetail::IsVector::value || - ReflectDetail::IsStringMap::value || ReflectableAggregate; + template + concept JsonConvertible = + HasMemberToJson || std::same_as || + std::is_arithmetic_v || std::is_enum_v || + std::same_as || Void::Meta::is_optional_v || + Void::Meta::is_vector_v || Void::Meta::is_string_map_v || + Void::Meta::is_duration_v || Void::Meta::is_time_point_v || + Void::Meta::is_variant_v || Void::Meta::is_std_array_v || + Void::Meta::is_map_v || ReflectableAggregate; -// Anything serializable through this header (customized or reflected). -template -concept Reflectable = JsonConvertible; + // Anything serializable through this header (customized or reflected). + template + concept Reflectable = JsonConvertible; -// ── to_json ─────────────────────────────────────────────────────────────────── + // ── to_json + // ─────────────────────────────────────────────────────────────────── -template -[[nodiscard]] Value to_json(const T& v); + template [[nodiscard]] Value to_json(const T& v); -namespace ReflectDetail -{ - template - Value leaf_to_json(const T& v) - { - if constexpr (HasMemberToJson) { - return v.to_json(); - } - else if constexpr (std::same_as) { - return Value{v}; - } - else if constexpr (std::is_enum_v) { + namespace ReflectDetail + { + template Value leaf_to_json(const T& v) + { + if constexpr (HasMemberToJson) { + return v.to_json(); + } else if constexpr (std::same_as) { + return Value{v}; + } else if constexpr (std::is_enum_v) { #ifdef VOID_HAS_ENUM_REFLECTION - // Enum values serialize by name — stable across binary versions. - return Value{Void::Detail::enum_name(v)}; + // Enum values serialize by name — stable across binary + // versions. + return Value{Void::Detail::enum_name(v)}; #else - return Value{static_cast( - static_cast>(v))}; + return Value{static_cast( + static_cast>(v))}; #endif - } - else if constexpr (std::is_arithmetic_v) { - return Value{static_cast(v)}; - } - else if constexpr (std::same_as) { - return Value{v}; - } - else if constexpr (IsOptional::value) { - return v ? Json::to_json(*v) : Value{nullptr}; - } - else if constexpr (IsVector::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::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, - "type is not serializable via Json reflection"); + } else if constexpr (std::is_arithmetic_v) { + return Value{static_cast(v)}; + } else if constexpr (std::same_as) { + return Value{v}; + } else if constexpr (Void::Meta::is_optional_v) { + return v ? Json::to_json(*v) : Value{nullptr}; + } else if constexpr (Void::Meta::is_vector_v) { + 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 (Void::Meta::is_string_map_v) { + auto obj = Json::object(); + for (const auto& [k, e] : v) { + obj.as_object().emplace_back(k, Json::to_json(e)); + } + return obj; + } else if constexpr (Void::Meta::is_duration_v) { + return Value{Void::Time::duration_to_string(v)}; + } else if constexpr (Void::Meta::is_time_point_v) { + // Encode as milliseconds-since-epoch (e.g. "1750000000000ms"). + // Millisecond magnitude stays exact through the double-based + // parse_duration, where a native-nanosecond count would not. + return Value{Void::Time::duration_to_string( + std::chrono::duration_cast( + v.time_since_epoch()))}; + } else if constexpr (Void::Meta::is_std_array_v) { + 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 (Void::Meta::is_map_v) { + // Non-string-keyed map: array of {key, value} objects. + auto arr = Json::array(); + for (const auto& [k, e] : v) { + auto pair = Json::object(); + pair.as_object().emplace_back("key", Json::to_json(k)); + pair.as_object().emplace_back("value", Json::to_json(e)); + arr.as_array().push_back(std::move(pair)); + } + return arr; + } else if constexpr (Void::Meta::is_variant_v) { + return std::visit( + [](const auto& alt) -> Value { + using Alt = std::decay_t; + auto obj = Json::object(); + obj.as_object().emplace_back( + "type", Value{Void::Meta::type_name()}); + obj.as_object().emplace_back("value", + Json::to_json(alt)); + return obj; + }, + v); + } else { + static_assert(ReflectableAggregate, + "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; + auto obj = Json::object(); + template for (constexpr auto m : Void::Meta::members_v) + { + if constexpr (!Void::Meta::has_annotation(m)) { + if constexpr (Void::Meta::has_annotation(m)) { + // Inline the nested object's keys into this object. + auto sub = Json::to_json(v.[:m:]); + if (sub.is_object()) { + for (auto& kv : sub.as_object()) { + obj.as_object().emplace_back( + kv.first, std::move(kv.second)); + } + } + } else { + constexpr auto rn = + Void::Meta::annotation_of(m); + std::string key = + rn.has_value() + ? std::string{rn->key.view()} + : std::string{std::meta::identifier_of(m)}; + obj.as_object().emplace_back( + std::move(key), Json::to_json(v.[:m:])); + } + } + } + return obj; #endif - } - } -} // namespace ReflectDetail + } + } + } // namespace ReflectDetail -template -[[nodiscard]] Value to_json(const T& v) -{ - return ReflectDetail::leaf_to_json(v); -} + template [[nodiscard]] Value to_json(const T& v) + { + return ReflectDetail::leaf_to_json(v); + } -// ── from_json ───────────────────────────────────────────────────────────────── + // ── from_json + // ───────────────────────────────────────────────────────────────── -template -[[nodiscard]] std::expected from_json(const Value& j); + template + [[nodiscard]] std::expected 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; - } + 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 - std::expected leaf_from_json(const Value& j) - { - if constexpr (HasMemberFromJson) { - return T::from_json(j); - } - else if constexpr (std::same_as) { - if (!j.is_bool()) { - return std::unexpected{ReflectError{"", "expected bool"}}; - } - return j.as_bool(); - } - else if constexpr (std::is_enum_v) { + template + std::expected leaf_from_json(const Value& j) + { + if constexpr (HasMemberFromJson) { + return T::from_json(j); + } else if constexpr (std::same_as) { + if (!j.is_bool()) { + return std::unexpected{ReflectError{"", "expected bool"}}; + } + return j.as_bool(); + } else if constexpr (std::is_enum_v) { #ifdef VOID_HAS_ENUM_REFLECTION - if (!j.is_string()) { - return std::unexpected{ - ReflectError{"", "expected enum name string"}}; - } - auto parsed = Void::Detail::enum_parse(j.as_string()); - if (!parsed) { - return std::unexpected{ReflectError{ - "", "unknown enumerator '" + j.as_string() + "'"}}; - } - return *parsed; + if (!j.is_string()) { + return std::unexpected{ + ReflectError{"", "expected enum name string"}}; + } + auto parsed = Void::Detail::enum_parse(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( - static_cast>(j.as_number())); + if (!j.is_number()) { + return std::unexpected{ + ReflectError{"", "expected enum number"}}; + } + return static_cast( + static_cast>(j.as_number())); #endif - } - else if constexpr (std::is_arithmetic_v) { - if (!j.is_number()) { - return std::unexpected{ReflectError{"", "expected number"}}; - } - return static_cast(j.as_number()); - } - else if constexpr (std::same_as) { - if (!j.is_string()) { - return std::unexpected{ReflectError{"", "expected string"}}; - } - return j.as_string(); - } - else if constexpr (IsOptional::value) { - using U = typename T::value_type; - if (j.is_null()) { - return T{std::nullopt}; - } - auto inner = Json::from_json(j); - if (!inner) { - return std::unexpected{std::move(inner).error()}; - } - return T{std::move(*inner)}; - } - else if constexpr (IsVector::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(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::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(e); - if (!inner) { - return std::unexpected{nest(k, std::move(inner).error())}; - } - out.emplace(k, std::move(*inner)); - } - return out; - } - else { - static_assert(ReflectableAggregate, - "type is not deserializable via Json reflection"); + } else if constexpr (std::is_arithmetic_v) { + if (!j.is_number()) { + return std::unexpected{ReflectError{"", "expected number"}}; + } + return static_cast(j.as_number()); + } else if constexpr (std::same_as) { + if (!j.is_string()) { + return std::unexpected{ReflectError{"", "expected string"}}; + } + return j.as_string(); + } else if constexpr (Void::Meta::is_optional_v) { + using U = typename T::value_type; + if (j.is_null()) { + return T{std::nullopt}; + } + auto inner = Json::from_json(j); + if (!inner) { + return std::unexpected{std::move(inner).error()}; + } + return T{std::move(*inner)}; + } else if constexpr (Void::Meta::is_vector_v) { + 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(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 (Void::Meta::is_string_map_v) { + 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(e); + if (!inner) { + return std::unexpected{ + nest(k, std::move(inner).error())}; + } + out.emplace(k, std::move(*inner)); + } + return out; + } else if constexpr (Void::Meta::is_duration_v) { + if (!j.is_string()) { + return std::unexpected{ + ReflectError{"", "expected duration string"}}; + } + auto parsed = Void::Time::parse_duration(j.as_string()); + if (!parsed) { + return std::unexpected{ReflectError{ + "", "invalid duration '" + j.as_string() + "'"}}; + } + return std::chrono::duration_cast(*parsed); + } else if constexpr (Void::Meta::is_time_point_v) { + if (!j.is_string()) { + return std::unexpected{ + ReflectError{"", "expected time_point string"}}; + } + auto parsed = Void::Time::parse_duration(j.as_string()); + if (!parsed) { + return std::unexpected{ReflectError{ + "", "invalid time_point '" + j.as_string() + "'"}}; + } + return T{std::chrono::duration_cast( + *parsed)}; + } else if constexpr (Void::Meta::is_std_array_v) { + using U = typename T::value_type; + if (!j.is_array()) { + return std::unexpected{ReflectError{"", "expected array"}}; + } + constexpr std::size_t N = std::tuple_size_v; + if (j.as_array().size() != N) { + return std::unexpected{ReflectError{ + "", "expected array of length " + std::to_string(N)}}; + } + T out{}; + std::size_t index = 0; + for (const auto& e : j.as_array()) { + auto inner = Json::from_json(e); + if (!inner) { + return std::unexpected{ + nest("[" + std::to_string(index) + "]", + std::move(inner).error())}; + } + out[index] = std::move(*inner); + ++index; + } + return out; + } else if constexpr (Void::Meta::is_map_v) { + using K = typename T::key_type; + using MV = typename T::mapped_type; + if (!j.is_array()) { + return std::unexpected{ + ReflectError{"", "expected array of key/value pairs"}}; + } + T out; + std::size_t index = 0; + for (const auto& e : j.as_array()) { + const auto where = "[" + std::to_string(index) + "]"; + const Value* kf = e.is_object() ? e.find("key") : nullptr; + const Value* vf = e.is_object() ? e.find("value") : nullptr; + if (!kf || !vf) { + return std::unexpected{nest( + where, + ReflectError{"", "expected {key, value} object"})}; + } + auto key = Json::from_json(*kf); + if (!key) { + return std::unexpected{ + nest(where, std::move(key).error())}; + } + auto val = Json::from_json(*vf); + if (!val) { + return std::unexpected{ + nest(where, std::move(val).error())}; + } + out.emplace(std::move(*key), std::move(*val)); + ++index; + } + return out; + } else if constexpr (Void::Meta::is_variant_v) { + if (!j.is_object()) { + return std::unexpected{ + ReflectError{"", "expected tagged variant object"}}; + } + const Value* tf = j.find("type"); + const Value* vf = j.find("value"); + if (!tf || !tf->is_string()) { + return std::unexpected{ + ReflectError{"", "variant missing 'type' tag"}}; + } + if (!vf) { + return std::unexpected{ + ReflectError{"", "variant missing 'value'"}}; + } + const std::string tag = tf->as_string(); + std::optional result; + std::optional failure; + [&](std::index_sequence) { + ( + [&] { + if (result || failure) { + return; + } + using Alt = std::variant_alternative_t; + if (Void::Meta::type_name() == tag) { + auto inner = Json::from_json(*vf); + if (!inner) { + failure = std::move(inner).error(); + } else { + result = T{std::in_place_index, + std::move(*inner)}; + } + } + }(), + ...); + }(std::make_index_sequence>{}); + if (failure) { + return std::unexpected{std::move(*failure)}; + } + if (!result) { + return std::unexpected{ + ReflectError{"", "unknown variant type '" + tag + "'"}}; + } + return std::move(*result); + } else { + static_assert(ReflectableAggregate, + "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 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(*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; + if (!j.is_object()) { + return std::unexpected{ReflectError{"", "expected object"}}; + } + T out{}; + std::optional failure; + template for (constexpr auto m : Void::Meta::members_v) + { + if (!failure) { + if constexpr (!Void::Meta::has_annotation(m)) { + using MT = [:std::meta::type_of(m):]; + if constexpr (Void::Meta::has_annotation( + m)) { + // Read the nested object's keys from this + // object. + auto inner = Json::from_json(j); + if (!inner) { + failure = std::move(inner).error(); + } else { + out.[:m:] = std::move(*inner); + } + } else { + constexpr auto rn = + Void::Meta::annotation_of(m); + const std::string key = + rn.has_value() + ? std::string{rn->key.view()} + : std::string{ + std::meta::identifier_of(m)}; + if (const Value* field = j.find(key)) { + auto inner = Json::from_json(*field); + if (!inner) { + failure = + nest(key, std::move(inner).error()); + } else { + out.[:m:] = std::move(*inner); + } + } else if constexpr (Void::Meta::has_annotation< + Required>(m)) { + failure = ReflectError{ + key, "required field is missing"}; + } + // absent + not required: keep the default value + } + } + } + } + if (failure) { + return std::unexpected{std::move(*failure)}; + } + return out; #endif - } - } -} // namespace ReflectDetail + } + } + } // namespace ReflectDetail -template -[[nodiscard]] std::expected from_json(const Value& j) -{ - return ReflectDetail::leaf_from_json(j); -} + template + [[nodiscard]] std::expected from_json(const Value& j) + { + return ReflectDetail::leaf_from_json(j); + } -// ── versioned envelope + migrations ─────────────────────────────────────────── + // ── versioned envelope + migrations + // ─────────────────────────────────────────── -// Specialize to bump a state type's schema version: -// template <> struct Void::Json::StateTraits { -// static constexpr std::uint32_t version = 3; -// }; -template -struct StateTraits { - static constexpr std::uint32_t version = 1; -}; + // Specialize to bump a state type's schema version: + // template <> struct Void::Json::StateTraits { + // static constexpr std::uint32_t version = 3; + // }; + template 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; + // Ordered chain of per-version JSON transforms. Each step upgrades the bare + // "data" payload from `from_version` to `from_version + 1`. + class MigrationChain + { + public: - MigrationChain& add(std::uint32_t from_version, Step step) - { - steps_.emplace(from_version, std::move(step)); - return *this; - } + using State = std::function; - [[nodiscard]] std::expected - 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; - } + MigrationChain& add(std::uint32_t from_version, State step) + { + steps_.emplace(from_version, std::move(step)); + return *this; + } - [[nodiscard]] bool empty() const noexcept { return steps_.empty(); } + [[nodiscard]] std::expected + 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; + } -private: - std::map steps_; -}; + [[nodiscard]] bool empty() const noexcept { return steps_.empty(); } -template -[[nodiscard]] Value to_versioned_json(const T& v) -{ - auto envelope = object(); - envelope.as_object().emplace_back( - "__version", Value{static_cast(StateTraits::version)}); - envelope.as_object().emplace_back("data", to_json(v)); - return envelope; -} + private: -template -[[nodiscard]] std::expected - 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(version->as_number()); - constexpr auto to = StateTraits::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(*data); - } - auto migrated = migrations.migrate(*data, from, to); - if (!migrated) { - return std::unexpected{std::move(migrated).error()}; - } - return from_json(*migrated); -} + std::map steps_; + }; + + template [[nodiscard]] Value to_versioned_json(const T& v) + { + auto envelope = object(); + envelope.as_object().emplace_back( + "__version", Value{static_cast(StateTraits::version)}); + envelope.as_object().emplace_back("data", to_json(v)); + return envelope; + } + + template + [[nodiscard]] std::expected + 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(version->as_number()); + constexpr auto to = StateTraits::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(*data); + } + auto migrated = migrations.migrate(*data, from, to); + if (!migrated) { + return std::unexpected{std::move(migrated).error()}; + } + return from_json(*migrated); + } } // namespace Void::Json diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp index 450efc1..fbf42da 100644 --- a/include/Void/Fsm/Detail/Engine.hpp +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include diff --git a/include/Void/Fsm/Detail/Introspect.hpp b/include/Void/Fsm/Detail/Introspect.hpp index 165ed91..d8005a3 100644 --- a/include/Void/Fsm/Detail/Introspect.hpp +++ b/include/Void/Fsm/Detail/Introspect.hpp @@ -2,29 +2,21 @@ #include #include -#include namespace Void::Fsm { - /// A declarable transition edge (from a reactive state's table). - struct EdgeInfo { - std::string event; // event type name, or "(timeout)" - std::string target; // target state, "(success)"/"(fail)" - bool guarded{false}; - }; - - /// A registered state plus the edges that are statically knowable - /// (reactive states only; imperative run()-chosen edges are not). + /// A registered state. Behaviour (and therefore transitions) is chosen + /// imperatively inside each state's entry, so edges are not statically + /// knowable — the description is node-level. struct StateInfo { std::string name; - bool reactive{false}; bool initial{false}; - std::vector edges; }; namespace Detail { - /// Render a state description as a Mermaid `stateDiagram-v2` string. + /// Render a state description as a Mermaid `stateDiagram-v2` string: + /// the initial marker plus one node per registered state. [[nodiscard]] inline std::string to_mermaid(std::span states) { @@ -35,13 +27,7 @@ namespace Void::Fsm } } for (const auto& s : states) { - for (const auto& e : s.edges) { - out += " " + s.name + " --> " + e.target + " : " + e.event; - if (e.guarded) { - out += " [guard]"; - } - out += "\n"; - } + out += " " + s.name + "\n"; } return out; } diff --git a/include/Void/Fsm/Detail/Reactive.hpp b/include/Void/Fsm/Detail/Reactive.hpp deleted file mode 100644 index 0d9dc90..0000000 --- a/include/Void/Fsm/Detail/Reactive.hpp +++ /dev/null @@ -1,271 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// The declarative transition DSL for reactive states, lifted out of the -// Machine template so the core stays small. Every type is parameterised by the -// owning machine's `Derived` (guards/actions take `Derived&`); the machine's -// typed Success/Failure (nested types, default void) are reflected from -// `Derived` for finish()/fail(). Machine::Reactive aliases these and the engine -// drives them; see include/Void/Fsm/Machine.hpp. - -namespace Void::Fsm::Detail -{ - namespace Coro = Void::Coro; - - /// One declared transition: event type, optional guard/action, the Step to - /// take, plus names for introspection. An `internal` entry runs its action - /// and stays in the state (no exit/enter/transition). - template struct EventEntry { - const std::type_info* type{nullptr}; - std::function guard; - std::function(Derived&, const std::any&)> action; - Step step; - bool internal{false}; - std::string event_name; // for introspection - std::string target_name; // for introspection - }; - - /// A reactive state's full transition table (events + an optional timeout, - /// deferred event types, and entry/exit actions). - template struct TransitionTable { - std::vector> events; - bool has_timeout{false}; - std::chrono::steady_clock::duration timeout_after{}; - Step timeout_step; - std::string timeout_target_name; - // Event types deferred while in this state (held, re-posted on the - // next transition) instead of dropped. - std::vector deferred; - // Entry/exit actions (run by the reactive loop around the state). - std::function(Derived&)> enter_action; - std::function(Derived&)> exit_action; - }; - - /// Fluent builder for one event row: `on.event().guard(..).action(..) - /// .to()` (or `.finish(v)` / `.fail(v)`). - template class EventClause - { - public: - - explicit EventClause(TransitionTable& table) - : m_table(&table) - { - } - - EventClause& guard(std::function g) - { - m_guard = std::move(g); - return *this; - } - - EventClause& - action(std::function(Derived&, const E&)> a) - { - m_action = std::move(a); - return *this; - } - - EventClause& action(std::function a) - { - m_action = [a = std::move(a)](Derived& d, - const E& e) -> Coro::Task { - a(d, e); - co_return; - }; - return *this; - } - - template void to() - { - if constexpr (requires { typename Derived::States; }) { - static_assert(Derived::States::template contains(), - "to: S is not in this machine's " - "States<...> list"); - } - commit(Step::transition(typeid(S)), type_name()); - } - - void finish() - requires std::is_void_v> - { - commit(Step::success(std::any{}), "(success)"); - } - template - void finish(V&& value) - requires(!std::is_void_v>) - { - commit(Step::success(std::any{ - SuccessOf(std::forward(value))}), - "(success)"); - } - - void fail() - requires std::is_void_v> - { - commit(Step::failure(std::any{}), "(fail)"); - } - template - void fail(V&& value) - requires(!std::is_void_v>) - { - commit(Step::failure(std::any{ - FailureOf{std::forward(value)}}), - "(fail)"); - } - - /// Internal transition: run `fn` on the event but stay in the - /// state (no exit/enter, no transition). - void internal(std::function fn) - { - action(std::move(fn)); - commit(Step::success(std::any{}), "(internal)", true); - } - - private: - - void commit(Step step, std::string target, bool is_internal = false) - { - EventEntry entry; - entry.type = &typeid(E); - if (m_guard) { - entry.guard = [g = std::move(m_guard)](Derived& d, - const std::any& a) { - return g(d, std::any_cast(a)); - }; - } - if (m_action) { - entry.action = - [a = std::move(m_action)]( - Derived& d, - const std::any& any) -> Coro::Task { - co_await a(d, std::any_cast(any)); - }; - } - entry.step = std::move(step); - entry.internal = is_internal; - entry.event_name = type_name(); - entry.target_name = std::move(target); - m_table->events.push_back(std::move(entry)); - } - - TransitionTable* m_table; - std::function m_guard; - std::function(Derived&, const E&)> m_action; - }; - - /// Fluent builder for the timeout row: `on.after(d).to()` / `.fail(v)`. - template class AfterClause - { - public: - - AfterClause(TransitionTable& table, - std::chrono::steady_clock::duration after) - : m_table(&table), m_after(after) - { - } - - template void to() - { - if constexpr (requires { typename Derived::States; }) { - static_assert(Derived::States::template contains(), - "after().to: S not in States<...>"); - } - m_table->has_timeout = true; - m_table->timeout_after = m_after; - m_table->timeout_step = Step::transition(typeid(S)); - m_table->timeout_target_name = type_name(); - } - - void fail() - requires std::is_void_v> - { - m_table->has_timeout = true; - m_table->timeout_after = m_after; - m_table->timeout_step = Step::failure(std::any{}); - m_table->timeout_target_name = "(fail)"; - } - template - void fail(V&& value) - requires(!std::is_void_v>) - { - m_table->has_timeout = true; - m_table->timeout_after = m_after; - m_table->timeout_step = Step::failure( - std::any{FailureOf{std::forward(value)}}); - m_table->timeout_target_name = "(fail)"; - } - - private: - - TransitionTable* m_table; - std::chrono::steady_clock::duration m_after; - }; - - /// Entry point handed to `transitions(TransitionBuilder& on)`. - template class TransitionBuilder - { - public: - - explicit TransitionBuilder(TransitionTable& table) - : m_table(&table) - { - } - - template [[nodiscard]] EventClause event() - { - return EventClause{*m_table}; - } - - template - [[nodiscard]] AfterClause - after(std::chrono::duration d) - { - return AfterClause{ - *m_table, std::chrono::duration_cast< - std::chrono::steady_clock::duration>(d)}; - } - - /// Defer event `E` while in this state: hold it (don't drop) and - /// re-post it after the next transition (UML deferred events). - template void defer() - { - m_table->deferred.push_back(&typeid(E)); - } - - /// Entry action — run when the state is entered (before it waits). - void enter(std::function fn) - { - m_table->enter_action = - [fn = std::move(fn)](Derived& d) -> Coro::Task { - fn(d); - co_return; - }; - } - /// Exit action — run when the state is left (on any transition). - void exit(std::function fn) - { - m_table->exit_action = - [fn = std::move(fn)](Derived& d) -> Coro::Task { - fn(d); - co_return; - }; - } - - private: - - TransitionTable* m_table; - }; -} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/Roles.hpp b/include/Void/Fsm/Detail/Roles.hpp index cc5fea9..19f6107 100644 --- a/include/Void/Fsm/Detail/Roles.hpp +++ b/include/Void/Fsm/Detail/Roles.hpp @@ -1,10 +1,12 @@ #pragma once #include +#include #include -#include #include -#include +#include +#include +#include #include #include @@ -23,122 +25,137 @@ // Signature-inferred state roles. There is ONE state base (`State`); the engine // discovers what each state does purely from its member signatures via P2996 — // no `override`, no framework-mandated names: -// - entry : a member returning Step / Coro::Task, no params +// - entry : a member returning State / Coro::Task>, no +// params // - startup-entry: the same taking the sub-machine's startup-data argument -// - reactive : a member taking TransitionBuilder& -// - result handlers (continuation): members taking `ChildSuccess auto` / -// `ChildFailure auto` (the boxes below) +// - result handlers (continuation): members taking `ChildSuccess` / +// `ChildFailure` (the type-erased result structs below) // All discovery is invocability-based (types known at the generation site), so -// no parameter-type reflection (P3096) is required. +// no parameter-type reflection (P3096) is required. Event handling is +// imperative inside an entry (co_await await_event()), so there is no +// reactive role. namespace Void::Fsm { - // Defined in Machine.hpp; forward-declared so InitialStateOf can pattern - // match the state list. - template struct States; - /// The success value of a launched sub-machine, handed to a continuation - /// handler written `ok(ChildSuccess auto s)` — `s.value` is the sub's - /// typed Success (absent for a void-result sub). - template struct ChildSuccessBox { - T value; - }; - template <> struct ChildSuccessBox { + /// handler written `ok(ChildSuccess s)`. The sub's typed Success is read + /// with `s.as()` (the value is empty for a void-result sub). + struct ChildSuccess { + std::any value; + template [[nodiscard]] T as() const + { + return std::any_cast(value); + } }; - /// The failure value of a launched sub-machine (`no(ChildFailure auto f)`; - /// `f.value` is the sub's typed Failure, absent for void). - template struct ChildFailureBox { - T value; - }; - template <> struct ChildFailureBox { + /// The failure value of a launched sub-machine, handed to `no(ChildFailure + /// f)`. The sub's typed Failure is read with `f.as()` (empty for void). + struct ChildFailure { + std::any value; + template [[nodiscard]] T as() const + { + return std::any_cast(value); + } }; - namespace Detail - { - template inline constexpr bool is_csucc = false; - template - inline constexpr bool is_csucc> = true; - template inline constexpr bool is_cfail = false; - template - inline constexpr bool is_cfail> = true; - } // namespace Detail - - template - concept ChildSuccess = Detail::is_csucc>; - template - concept ChildFailure = Detail::is_cfail>; + /// Marker to designate a state's entry when several members match the entry + /// signature: annotate the chosen one `[[= Void::Fsm::entry]]`. Unmarked, + /// the first-declared matching member is used. + inline constexpr struct EntryTag { + } entry; namespace Detail { namespace Coro = Void::Coro; namespace meta = std::meta; - /// The owning machine type of a state S (via State::self()). - template - using MachineOf = - std::remove_cvref_t().self())>; + // InitialStateOf / FirstStateOf live in Detail/StateList.hpp (they + // reflect the nested `struct States { … }`). - template struct first_state_helper; - template - struct first_state_helper> { - using type = F; - }; - - /// A machine's initial state type: its nested `Initial` if declared, - /// else the first entry of `States<...>`. - template consteval auto initial_state_probe() + /// True if member `m` carries the `[[= Void::Fsm::entry]]` annotation. + /// Routed through the shared Void::Meta annotation helper. + consteval bool is_entry_marked(meta::info m) { - if constexpr (requires { typename M::Initial; }) { - return std::type_identity{}; - } else { - return std::type_identity< - typename first_state_helper::type>{}; - } + return Void::Meta::has_annotation(m); } - template - using InitialStateOf = - typename decltype(initial_state_probe())::type; - /// Wrap a ready Step in a Task. (The reflection selectors below must + /// Wrap a ready State in a Task. (The reflection selectors below must /// NOT be coroutines — `template for` + member splicing fails inside a /// coroutine body in this build — so they return a Task instead.) - inline Coro::Task ready_task(Step s) { co_return s; } + inline Coro::Task ready_task(StateKey s) { co_return s; } - // ── entry (0-arg member returning Step / Task) ────────────── - template Coro::Task invoke_entry(S& s) + // ── entry (0-arg member returning StateKey / Task) ────── + // When several members match, one annotated `[[= Fsm::entry]]` wins; + // otherwise the first-declared match is used. + template Coro::Task invoke_entry(S& s) { static constexpr auto members = std::define_static_array( meta::members_of(^^S, meta::access_context::current())); + // Pass 1: a member annotated [[= Fsm::entry]] takes precedence. template for (constexpr auto m : members) { - if constexpr (requires(S& x) { x.[:m:](); }) { + if constexpr (is_entry_marked(m) && + requires(S& x) { x.[:m:](); }) { using R = decltype(std::declval().[:m:]()); - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { return ready_task(s.[:m:]()); - } else if constexpr (std::is_same_v>) { + } else if constexpr (std::is_same_v>) { return s.[:m:](); } } } - return ready_task(Step::fault(FsmError{ - "state has no entry (a no-arg method returning Step)"})); + // Pass 2: the first-declared matching member. + template for (constexpr auto m : members) + { + if constexpr (requires(S& x) { x.[:m:](); }) { + using R = decltype(std::declval().[:m:]()); + if constexpr (std::is_same_v) { + return ready_task(s.[:m:]()); + } else if constexpr (std::is_same_v>) { + return s.[:m:](); + } + } + } + return ready_task(StateKey::fault(FsmError{ + "state has no entry (a no-arg method returning StateKey)"})); } // ── startup-entry (member taking the startup-data argument[s]) ──── + // Same precedence as invoke_entry: an annotated `[[= Fsm::entry]]` + // data-taking member wins, else the first-declared one; if none takes + // the data, fall back to the plain (nullary) entry. template - Coro::Task invoke_startup(S& s, DataT... data) + Coro::Task invoke_startup(S& s, DataT... data) { static constexpr auto members = std::define_static_array( meta::members_of(^^S, meta::access_context::current())); + // Pass 1: an annotated data-taking member takes precedence. + template for (constexpr auto m : members) + { + if constexpr (is_entry_marked(m) && + requires(S& x, DataT... d) { x.[:m:](d...); }) { + using R = decltype(std::declval().[:m:]( + std::declval()...)); + if constexpr (std::is_same_v) { + return ready_task(s.[:m:](std::move(data)...)); + } else if constexpr (std::is_same_v>) { + return s.[:m:](std::move(data)...); + } + } + } + // Pass 2: the first-declared data-taking member. template for (constexpr auto m : members) { if constexpr (requires(S& x, DataT... d) { x.[:m:](d...); }) { using R = decltype(std::declval().[:m:]( std::declval()...)); - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { return ready_task(s.[:m:](std::move(data)...)); - } else if constexpr (std::is_same_v>) { + } else if constexpr (std::is_same_v>) { return s.[:m:](std::move(data)...); } } @@ -149,7 +166,7 @@ namespace Void::Fsm // ── continuation handler (member taking a ChildSuccess/Failure box) template - Coro::Task invoke_handler(S& s, Box box) + Coro::Task invoke_handler(S& s, Box box) { static constexpr auto members = std::define_static_array( meta::members_of(^^S, meta::access_context::current())); @@ -158,161 +175,43 @@ namespace Void::Fsm if constexpr (requires(S& x, Box b) { x.[:m:](b); }) { using R = decltype(std::declval().[:m:](std::declval())); - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { return ready_task(s.[:m:](std::move(box))); - } else if constexpr (std::is_same_v>) { + } else if constexpr (std::is_same_v>) { return s.[:m:](std::move(box)); } } } - return ready_task(Step::fault( + return ready_task(StateKey::fault( FsmError{"continuation has no handler for this sub-machine " - "result (ChildSuccess auto / ChildFailure auto)"})); + "result (ChildSuccess / ChildFailure)"})); } /// Dispatch a sub-machine's LaunchResult into the Next state's - /// signature-matched handler. Knows Next and Sub (so the box types are - /// concrete); built at the startMachine call site. + /// signature-matched handler (`ok(ChildSuccess)` / `no(ChildFailure)`). + /// The typed payload rides type-erased in the result struct's `value`; + /// the handler reads it with `.as()`. (Sub is retained in the + /// signature so the call site stays `dispatch_result`.) template - Coro::Task dispatch_result(Next& s, LaunchResult lr) + Coro::Task dispatch_result(Next& s, LaunchResult lr) { - using Succ = SuccessOf; - using Fail = FailureOf; if (lr.kind == LaunchResult::Kind::Failure) { - ChildFailureBox box; - if constexpr (!std::is_void_v) { - box.value = std::any_cast(std::move(lr.failure)); - } - return invoke_handler(s, std::move(box)); + return invoke_handler(s, ChildFailure{std::move(lr.failure)}); } - ChildSuccessBox box; - if constexpr (!std::is_void_v) { - box.value = std::any_cast(std::move(lr.value)); - } - return invoke_handler(s, std::move(box)); + return invoke_handler(s, ChildSuccess{std::move(lr.value)}); } - // ── reactive (member taking TransitionBuilder&) ──────────────── - template consteval bool has_transitions() - { - using D = MachineOf; - bool found = false; - template for (constexpr auto m : - std::define_static_array(meta::members_of( - ^^S, meta::access_context::current()))) - { - if constexpr (requires(S& x, TransitionBuilder& b) { - x.[:m:](b); - }) { - found = true; - } - } - return found; - } - - /// Fill `table` from S's transitions-shaped member (if any). - template - void collect_transitions(S& s, TransitionTable& table) - { - TransitionBuilder builder{table}; - static constexpr auto members = std::define_static_array( - meta::members_of(^^S, meta::access_context::current())); - template for (constexpr auto m : members) - { - if constexpr (requires(S& x, TransitionBuilder& b) { - x.[:m:](b); - }) { - s.[:m:](builder); - } - } - } - - /// The reactive drive loop (relocated from the old Reactive::run()): - /// wait for a declared event or the timeout, check guards in order, run - /// the action, transition. - template Coro::Task drive_reactive(S& s) - { - using D = MachineOf; - TransitionTable table; - collect_transitions(s, table); - // Await the declared event types *and* the deferred ones (so a - // deferred event wakes us to be held, not dropped). - std::vector types; - types.reserve(table.events.size() + table.deferred.size()); - for (const auto& e : table.events) { - types.push_back(e.type); - } - for (const auto* dt : table.deferred) { - types.push_back(dt); - } - D& d = s.self(); - if (table.enter_action) { - co_await table.enter_action(d); - } - // Events deferred while here, re-posted on exit. - std::vector held; - auto leave = [&](Step step) -> Coro::Task { - if (table.exit_action) { - co_await table.exit_action(d); - } - for (auto& h : held) { - s.machine().repost(std::move(h)); - } - co_return std::move(step); - }; - for (;;) { - std::optional deadline; - if (table.has_timeout) { - deadline = - std::chrono::steady_clock::now() + table.timeout_after; - } - auto ev = co_await s.machine().await_any_event(types, deadline); - if (!ev) { - co_return co_await leave(std::move(table.timeout_step)); - } - bool matched = false; - for (auto& e : table.events) { - if (*e.type != *ev->type) { - continue; - } - if (e.guard && !e.guard(d, ev->value)) { - continue; - } - if (e.action) { - co_await e.action(d, ev->value); - } - matched = true; - if (!e.internal) { - co_return co_await leave(std::move(e.step)); - } - break; // internal: handled, stay in the state - } - if (!matched) { - // No entry took it: hold if deferred, else drop. - const bool is_deferred = std::any_of( - table.deferred.begin(), table.deferred.end(), - [&](const std::type_info* t) { - return *t == *ev->type; - }); - if (is_deferred) { - held.push_back(std::move(*ev)); - } - } - } - } - - /// Per-state driver thunk built at registration (S is complete): - /// reactive states run the table, others run the entry. + /// Per-state driver thunk built at registration (S is complete): run + /// the state's entry. Event handling, timeouts, guards and deferral are + /// all expressed imperatively inside the entry (await_event / await_any + /// / await_event_for / delay), so there is no separate reactive driver. template - [[nodiscard]] std::function(StateBase&)> make_driver() + [[nodiscard]] std::function(StateBase&)> + make_driver() { - return [](StateBase& base) -> Coro::Task { - S& s = static_cast(base); - if constexpr (has_transitions()) { - co_return co_await drive_reactive(s); - } else { - co_return co_await invoke_entry(s); - } + return [](StateBase& base) -> Coro::Task { + co_return co_await invoke_entry(static_cast(base)); }; } } // namespace Detail diff --git a/include/Void/Fsm/Detail/StateList.hpp b/include/Void/Fsm/Detail/StateList.hpp new file mode 100644 index 0000000..ad7bb3d --- /dev/null +++ b/include/Void/Fsm/Detail/StateList.hpp @@ -0,0 +1,102 @@ +#pragma once + +#include + +#include +#include +#include + +// State-list reflection helpers. A machine declares its states as a nested +// struct of forward declarations: +// struct States { struct Idle; struct Run; struct Done; }; +// defined out-of-line in the .cpp, and the Machine base auto-registers them by +// reflecting `members_of(^^States)` — the first nested state is the initial one +// unless the machine declares `using Initial = S;`. These helpers replace the +// old `Fsm::States` template: the list is now an ordinary struct whose +// nested state types are enumerated via P2996 (already a hard dependency of the +// module — see Detail/Roles.hpp). + +namespace Void::Fsm::Detail +{ + namespace meta = std::meta; + + /// True if reflection `m` names a nested type that is one of this machine's + /// states (a class deriving StateBase) — filters out the + /// injected-class-name and any non-state members. + template consteval bool is_state_member() + { + if constexpr (meta::is_type(M)) { + using S = typename[:M:]; + return std::is_class_v && std::derived_from; + } else { + return false; + } + } + + /// Reflection of the first state member of `StatesT` (declaration order), + /// or + /// `^^void` when the list has none. + template consteval meta::info first_state_member() + { + template for (constexpr auto m : + std::define_static_array(meta::members_of( + ^^StatesT, meta::access_context::current()))) + { + if constexpr (is_state_member()) { + return m; + } + } + return ^^void; + } + + /// The first declared state type of `StatesT` (void if empty). + template + using FirstStateOf = typename[:first_state_member():]; + + /// A machine's initial state type: its nested `Initial` if declared, else + /// the first member of its `States` list. + template consteval auto initial_state_probe() + { + if constexpr (requires { typename M::Initial; }) { + return std::type_identity{}; + } else { + return std::type_identity>{}; + } + } + template + using InitialStateOf = typename decltype(initial_state_probe())::type; + + /// Compile-time membership test: is `S` one of `StatesT`'s state members? + /// Drives the next() / startMachine<,Next>() target validation. + template consteval bool states_contains() + { + bool found = false; + template for (constexpr auto m : + std::define_static_array(meta::members_of( + ^^StatesT, meta::access_context::current()))) + { + if constexpr (is_state_member()) { + if constexpr (std::is_same_v) { + found = true; + } + } + } + return found; + } + + /// Register every state member of `StatesT` on `machine` (declaration order + /// = registration order). Instantiated from the derived machine's .cpp + /// constructor, where the out-of-line state definitions are complete. + template + void register_states_from(M& machine) + { + template for (constexpr auto m : + std::define_static_array(meta::members_of( + ^^StatesT, meta::access_context::current()))) + { + if constexpr (is_state_member()) { + machine.template add(); + } + } + } +} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Fsm.hpp b/include/Void/Fsm/Fsm.hpp index f13710e..fbc421e 100644 --- a/include/Void/Fsm/Fsm.hpp +++ b/include/Void/Fsm/Fsm.hpp @@ -2,13 +2,14 @@ // Umbrella header for the FSM module. The implementation is split for // maintainability: -// - Machine.hpp — the Machine template + States -// list, nested State / Reactive bases, lifecycle, -// events, nesting, persistence. -// - Detail/Reactive.hpp — the declarative transition DSL -// (TransitionBuilder / EventClause / AfterClause). +// - Machine.hpp — the Machine template, the nested State +// base, lifecycle, events, nesting, persistence. +// - Detail/StateList.hpp — reflection over the nested `struct States { … }` +// (auto-registration, initial-state, membership). +// - Detail/Roles.hpp — signature-inferred state roles (entry, +// startup-entry, continuation handlers). // - Detail/Awaiter.hpp — the unified event awaiter. -// - Detail/Introspect.hpp — StateInfo / EdgeInfo + to_mermaid. +// - Detail/Introspect.hpp — StateInfo + to_mermaid (node-level diagram). // - Detail/Engine.{hpp,cpp} — the non-template execution context. // Include to get the whole machine API as before. diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index 41166f1..13ecb24 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -6,11 +6,11 @@ #include #include #include -#include #include #include +#include #include -#include +#include #include #include @@ -43,20 +43,6 @@ namespace Void::Fsm { - /// Compile-time list of a machine's states. Declare it in the derived - /// machine to auto-register every state and enable compile-time - /// validation of next() targets: - /// using States = Void::Fsm::States; - /// The first entry is the initial state unless `using Initial = S;`. - template struct States { - static constexpr std::size_t size = sizeof...(Ss); - - template static constexpr bool contains() - { - return (std::is_same_v || ...); - } - }; - /// Options for a Machine (namespace scope to dodge the GCC /// nested-default-arg trap). struct MachineOptions { @@ -76,25 +62,33 @@ namespace Void::Fsm // ── Machine ────────────────────────────────────────────────── // - // Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it, - // declare states as nested structs deriving the single `State`, list them - // in `using States = Fsm::States<...>`. The engine infers each state's role - // from member signatures (entry / reactive table / continuation handlers); - // states reach their machine (data + sub-methods) via self(). Result types - // are the nested `Success`/`Failure` (default void). + // Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it + // and declare the states as a nested struct of forward declarations: + // struct States { struct FirstState; struct SecondState; … }; + // defined out-of-line (typically in a .cpp), each deriving the single + // `State`. The Machine base auto-registers them by reflecting `States` + // (Detail/StateList.hpp) — the first declared state is the initial one + // unless `using Initial = S;`. All behaviour lives inside a state: the + // engine infers each state's role from its member signatures (entry / + // startup-entry / continuation handlers); states reach their machine (data + // + sub-methods) via self(). Events are handled imperatively inside an + // entry (co_await await_event()) — there is no declarative transition + // table. Result types are the nested `Success`/`Failure` (default void). // + // // header // class Login : public Void::Fsm::Machine { // public: // using Success = Token; // int attempts = 0; - // struct Check : State { // entry by signature - // Coro::Task run() { - // if (++self().attempts > 3) co_return fail(); - // co_return self().service().ok() ? succeed(Token{}) - // : next(); - // } - // }; - // using States = Void::Fsm::States; + // struct States { struct Check; }; + // }; + // // source (namespace scope) + // struct Login::States::Check : Login::State { // entry by signature + // Coro::Task> run() { + // if (++self().attempts > 3) co_return fail(); + // co_return self().service().ok() ? succeed(Token{}) + // : next(); + // } // }; template class Machine { @@ -135,43 +129,44 @@ namespace Void::Fsm protected: /// Transition to another state. Validated at compile - /// time when the machine declares `using States`. - template [[nodiscard]] Step next() const + /// time when the machine declares a `States` list. + template [[nodiscard]] StateKey next() const { if constexpr (requires { typename Derived::States; }) { - static_assert( - Derived::States::template contains(), - "next: S is not in this machine's " - "States<...> list"); + static_assert(Detail::states_contains< + typename Derived::States, S>(), + "next: S is not in this machine's " + "States { … } list"); } - return Step::transition(typeid(S)); + return StateKey::transition(typeid(S)); } /// Transition to a state registered dynamically /// (add()/add_if()), skipping the static check. template - [[nodiscard]] Step next_dynamic() const + [[nodiscard]] StateKey next_dynamic() const { - return Step::transition(typeid(S)); + return StateKey::transition(typeid(S)); } /// Free jump to any registered state — no declared /// transition required ("each state can be moved to /// another state"). Like next_dynamic, skips the - /// States<...> compile-time check; runtime-fails only if S + /// States{ … } compile-time check; runtime-fails only if S /// was never registered. - template [[nodiscard]] Step goto_state() const + template + [[nodiscard]] StateKey goto_state() const { - return Step::transition(typeid(S)); + return StateKey::transition(typeid(S)); } /// Route to a fallback state if `step` is a failure, /// otherwise pass it through — for error policies: /// co_return next_or(co_await try_work()); template - [[nodiscard]] Step next_or(Step step) const + [[nodiscard]] StateKey next_or(StateKey step) const { - if (step.kind() == Step::Kind::Fail) { + if (step.kind() == StateKey::Kind::Fail) { return next(); } return step; @@ -209,32 +204,32 @@ namespace Void::Fsm /// Finish with the machine's typed Success result (nested /// `Success`; nullary when it is void). - [[nodiscard]] Step succeed() const + [[nodiscard]] StateKey succeed() const requires std::is_void_v> { - return Step::success(std::any{}); + return StateKey::success(std::any{}); } template - [[nodiscard]] Step succeed(V&& value) const + [[nodiscard]] StateKey succeed(V&& value) const requires(!std::is_void_v>) { - return Step::success( + return StateKey::success( std::any{Detail::SuccessOf( std::forward(value))}); } /// Finish with the machine's typed Failure result (nested /// `Failure`; nullary when it is void). - [[nodiscard]] Step fail() const + [[nodiscard]] StateKey fail() const requires std::is_void_v> { - return Step::failure(std::any{}); + return StateKey::failure(std::any{}); } template - [[nodiscard]] Step fail(V&& value) const + [[nodiscard]] StateKey fail(V&& value) const requires(!std::is_void_v>) { - return Step::failure( + return StateKey::failure( std::any{Detail::FailureOf{ std::forward(value)}}); } @@ -311,11 +306,11 @@ namespace Void::Fsm /// initial-state startup-entry; shares this machine's /// executor/events/services), then transition to `Next`. /// When Sub finishes the engine calls Next's signature - /// -matched handler — a member taking `ChildSuccess auto` - /// (Sub succeeded) or `ChildFailure auto` (Sub failed): + /// -matched handler — a member taking `ChildSuccess` + /// (Sub succeeded) or `ChildFailure` (Sub failed): /// co_return startMachine(seed); template - [[nodiscard]] Step startMachine(Args&&... args) const + [[nodiscard]] StateKey startMachine(Args&&... args) const { return m_machine->template start_machine( std::forward(args)...); @@ -337,37 +332,35 @@ namespace Void::Fsm // There is a single base, `State`. The engine infers what each // state does from member signatures (no `override`, no fixed // names): - // - entry : a member returning Step/Coro::Task, + // - entry : a member returning + // State/Coro::Task>, // no params (a startup-data overload may take // the sub's startup argument); - // - reactive : a member taking `TransitionBuilder&` (the - // declarative table below); - // - continuation : members taking `ChildSuccess auto` / - // `ChildFailure auto` (the sub's typed result - // after `startMachine()`). + // - continuation : members taking `ChildSuccess` / + // `ChildFailure` (the sub's typed result, read + // via .as(), after `startMachine`). // - // struct Idle : State { // reactive - // void transitions(TransitionBuilder& on) { - // on.event().to(); - // on.after(5s).to(); } }; + // Events are handled imperatively inside an entry: + // struct Idle : State { // entry + // Coro::Task run() { + // auto e = co_await await_any(); + // co_return std::holds_alternative(e) ? next() + // : next(); } + // }; // struct After : State { // continuation - // Coro::Task ok(ChildSuccess auto s){ ... } - // Coro::Task no(ChildFailure auto f){ ... } }; - // - // The declarative DSL lives in Detail/Reactive.hpp; these aliases - // give the `transitions(TransitionBuilder&)` member its type. - using TransitionTable = Detail::TransitionTable; - using TransitionBuilder = Detail::TransitionBuilder; + // Coro::Task ok(ChildSuccess s){ ... } + // Coro::Task no(ChildFailure f){ ... } }; // ── construction ────────────────────────────────────────────── explicit Machine(Options options = {}) : m_options(options) { if constexpr (requires { typename Derived::States; }) { - register_states(typename Derived::States{}); - if constexpr (requires { typename Derived::Initial; }) { - m_initial = &typeid(typename Derived::Initial); - } else { - m_initial = first_type(typename Derived::States{}); + Detail::register_states_from( + *this); + using Init = Detail::InitialStateOf; + if constexpr (!std::is_void_v) { + m_initial = &typeid(Init); } } } @@ -397,20 +390,8 @@ namespace Void::Fsm s->m_machine = this; return s; }); - // Signature-inferred driver thunk (entry or reactive table). + // Signature-inferred driver thunk (runs the state's entry). m_drivers.emplace(key, Detail::make_driver()); - // describe() collector: fills a table if S is reactive. - m_collectors.emplace( - key, - [](Detail::StateBase& base, - TransitionTable& table) -> bool { - if constexpr (Detail::has_transitions()) { - Detail::collect_transitions(static_cast(base), - table); - return true; - } - return false; - }); } template void initial() @@ -459,7 +440,6 @@ namespace Void::Fsm m_names.erase(m_names.begin() + idx); m_factories.erase(key); m_drivers.erase(key); - m_collectors.erase(key); m_index.erase(idxIt); // Re-pack the indices of states that followed S. for (auto& [k, v] : m_index) { @@ -973,12 +953,13 @@ namespace Void::Fsm /// machine's shared executor, then enter `Next` carrying Sub's /// outcome as a LaunchResult. Reached via State::startMachine. template - [[nodiscard]] Step start_machine(Args&&... args) + [[nodiscard]] StateKey start_machine(Args&&... args) { if constexpr (requires { typename Derived::States; }) { static_assert( - Derived::States::template contains(), - "startMachine: Next is not in States<...>"); + Detail::states_contains(), + "startMachine: Next is not in States { … }"); } using Init = Detail::InitialStateOf; auto launcher = @@ -993,7 +974,7 @@ namespace Void::Fsm child.m_startup_injector = [... d = std::move(data)]( Detail::StateBase& base) mutable - -> Coro::Task { + -> Coro::Task { return Detail::invoke_startup( static_cast(base), std::move(d)...); }; @@ -1017,14 +998,14 @@ namespace Void::Fsm } co_return lr; }; - Step::Dispatch dispatch = + StateKey::Dispatch dispatch = [](Detail::StateBase& base, - LaunchResult lr) -> Coro::Task { + LaunchResult lr) -> Coro::Task { return Detail::dispatch_result( static_cast(base), std::move(lr)); }; - return Step::launch(typeid(Next), std::move(launcher), - std::move(dispatch)); + return StateKey::launch(typeid(Next), std::move(launcher), + std::move(dispatch)); } // ── observation ─────────────────────────────────────────────── @@ -1066,12 +1047,12 @@ namespace Void::Fsm } // ── introspection / diagram ─────────────────────────────────── - // EdgeInfo / StateInfo are namespace-scope (Detail/Introspect.hpp). + // StateInfo is namespace-scope (Detail/Introspect.hpp). - /// Structural description: every registered state plus the - /// transitions declared by reactive states (imperative states' - /// run()-chosen transitions are not statically knowable, so - /// they appear as nodes without edges). + /// Structural description: every registered state (name + whether + /// it is the initial state). Transitions are chosen imperatively + /// inside each state's entry, so they are not statically knowable — + /// the description is node-level (no edges). [[nodiscard]] std::vector describe() { std::vector out; @@ -1082,22 +1063,6 @@ namespace Void::Fsm StateInfo si; si.name = name; si.initial = (name == initial_name); - const auto* ti = m_name_to_type.at(name); - const std::type_index key{*ti}; - auto state = m_factories.at(key)(); - TransitionTable table; - si.reactive = m_collectors.at(key)(*state, table); - if (si.reactive) { - for (const auto& e : table.events) { - si.edges.push_back( - EdgeInfo{e.event_name, e.target_name, - static_cast(e.guard)}); - } - if (table.has_timeout) { - si.edges.push_back(EdgeInfo{ - "(timeout)", table.timeout_target_name, false}); - } - } out.push_back(std::move(si)); } return out; @@ -1151,6 +1116,15 @@ namespace Void::Fsm virtual void on_serialize(Json::Value& /*data*/) const {} virtual void on_restore(const Json::Value& /*data*/) {} + /// Machine-level entry/exit hooks (default no-ops; override for + /// machine-wide setup/teardown). `on_machine_enter()` runs once + /// before the initial state is entered; `on_machine_exit()` runs + /// once when the machine reaches a terminal outcome (Success, + /// Failure, or a system Fault). Per-state entry/exit lives on the + /// state itself (State::on_enter()/on_exit()). + virtual void on_machine_enter() {} + virtual void on_machine_exit() {} + /// Called on every transition (and the initial entry). Default /// logs at debug; override for custom observability. virtual void on_transition(std::string_view from, @@ -1176,21 +1150,6 @@ namespace Void::Fsm m_status.store(Status::Running); } - template void register_states(States) - { - (add(), ...); - } - - template - static const std::type_info* first_type(States) - { - return &typeid(First); - } - static const std::type_info* first_type(States<>) - { - return nullptr; - } - template [[nodiscard]] std::string state_name() { #ifdef VOID_HAS_FSM_REFLECTION @@ -1261,6 +1220,7 @@ namespace Void::Fsm fault("no initial state"); co_return; } + on_machine_enter(); bool first = true; for (;;) { // Apply an external jump() at this transition boundary. @@ -1274,6 +1234,7 @@ namespace Void::Fsm const auto it = m_factories.find(std::type_index{*cur}); if (it == m_factories.end()) { fault("transition to unregistered state"); + on_machine_exit(); co_return; } set_current(cur); @@ -1282,7 +1243,7 @@ namespace Void::Fsm // Decide how the state runs: a launched sub's result (via // the bound dispatcher), the startup injector for the first // state, or the signature-inferred driver thunk. - Step step; + StateKey step; if (m_pending_dispatch) { LaunchResult pending = std::move(*m_pending_result); auto dispatch = std::move(m_pending_dispatch); @@ -1290,6 +1251,7 @@ namespace Void::Fsm m_pending_dispatch = nullptr; if (pending.kind == LaunchResult::Kind::Fault) { fault(std::move(pending.fault.message)); + on_machine_exit(); co_return; } step = co_await dispatch(*state, std::move(pending)); @@ -1305,28 +1267,31 @@ namespace Void::Fsm co_await state->on_exit(); fire_after(current_state()); switch (step.kind()) { - case Step::Kind::Transition: + case StateKey::Kind::Transition: cur = step.target(); continue; - case Step::Kind::Launch: + case StateKey::Kind::Launch: m_pending_result.emplace( co_await step.run_launch()); m_pending_dispatch = step.take_dispatch(); cur = step.target(); continue; - case Step::Kind::Success: + case StateKey::Kind::Success: m_result_value = std::move(step.payload()); m_status.store(Status::Succeeded, std::memory_order_release); + on_machine_exit(); co_return; - case Step::Kind::Fail: + case StateKey::Kind::Fail: m_result_value = std::move(step.payload()); m_status.store(Status::Failed, std::memory_order_release); + on_machine_exit(); co_return; - case Step::Kind::Fault: + case StateKey::Kind::Fault: fault(std::any_cast(step.payload()) .message); + on_machine_exit(); co_return; } } @@ -1385,15 +1350,11 @@ namespace Void::Fsm std::type_index, std::function()>> m_factories; - // Per-state signature-inferred driver thunk (entry / reactive). - std::unordered_map( - Detail::StateBase&)>> - m_drivers; - // Per-state describe() collector (reactive table, if any). + // Per-state signature-inferred driver thunk (runs the entry). std::unordered_map< std::type_index, - std::function> - m_collectors; + std::function(Detail::StateBase&)>> + m_drivers; std::unordered_map m_index; std::vector m_names; std::unordered_map @@ -1421,11 +1382,11 @@ namespace Void::Fsm // Set by a Launch step's sub-machine result; consumed by the next // state via the bound dispatcher below. std::optional m_pending_result; - Step::Dispatch m_pending_dispatch; + StateKey::Dispatch m_pending_dispatch; // Seeds the initial state's startup-entry with launch data (set by // the parent's launcher before driving this machine). - std::function(Detail::StateBase&)> + std::function(Detail::StateBase&)> m_startup_injector; // External jump request (jump()); applied by drive() at the @@ -1437,5 +1398,5 @@ namespace Void::Fsm // suspended frame chain of a machine parked on an event. std::optional> m_driver; }; - + template using State = Machine::State; } // namespace Void::Fsm diff --git a/include/Void/Fsm/Orchestrator.hpp b/include/Void/Fsm/Orchestrator.hpp index 52e8707..fb8b344 100644 --- a/include/Void/Fsm/Orchestrator.hpp +++ b/include/Void/Fsm/Orchestrator.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include #include #include diff --git a/include/Void/Fsm/Step.hpp b/include/Void/Fsm/StateKey.hpp similarity index 88% rename from include/Void/Fsm/Step.hpp rename to include/Void/Fsm/StateKey.hpp index 52227b5..205e9f5 100644 --- a/include/Void/Fsm/Step.hpp +++ b/include/Void/Fsm/StateKey.hpp @@ -46,15 +46,16 @@ namespace Void::Fsm /// What a state's entry returns: move to another state, finish with a typed /// Success / Failure, or launch a sub-machine. Built only through the State /// helpers (next() / succeed(...) / fail(...) / startMachine). - class Step + class StateKey { public: enum class Kind { Transition, Success, Fail, Launch, Fault }; - [[nodiscard]] static Step transition(const std::type_info& target) + [[nodiscard]] static StateKey + transition(const std::type_info& target) { - Step s; + StateKey s; s.m_kind = Kind::Transition; s.m_target = ⌖ return s; @@ -62,9 +63,9 @@ namespace Void::Fsm /// Signal a system fault (programming error) — distinct from a /// typed Failure. Routed to Machine::system_error(). - [[nodiscard]] static Step fault(FsmError error) + [[nodiscard]] static StateKey fault(FsmError error) { - Step s; + StateKey s; s.m_kind = Kind::Fault; s.m_payload = std::any{std::move(error)}; return s; @@ -72,17 +73,17 @@ namespace Void::Fsm /// A bound dispatcher: given the entered Next state and the sub's /// LaunchResult, calls Next's signature-matched handler. - using Dispatch = std::function(Detail::StateBase&, - LaunchResult)>; + using Dispatch = std::function( + Detail::StateBase&, LaunchResult)>; /// Launch a sub-machine, then enter `target` (a continuation state) /// with the sub's LaunchResult, dispatched via `dispatch`. - [[nodiscard]] static Step + [[nodiscard]] static StateKey launch(const std::type_info& target, std::function()> launcher, Dispatch dispatch) { - Step s; + StateKey s; s.m_kind = Kind::Launch; s.m_target = ⌖ s.m_launcher = std::move(launcher); @@ -91,18 +92,18 @@ namespace Void::Fsm } /// Finish with a typed Success payload (empty std::any for void). - [[nodiscard]] static Step success(std::any value) + [[nodiscard]] static StateKey success(std::any value) { - Step s; + StateKey s; s.m_kind = Kind::Success; s.m_payload = std::move(value); return s; } /// Finish with a typed Failure payload (empty std::any for void). - [[nodiscard]] static Step failure(std::any value) + [[nodiscard]] static StateKey failure(std::any value) { - Step s; + StateKey s; s.m_kind = Kind::Fail; s.m_payload = std::move(value); return s; diff --git a/include/Void/Functional/Detail/Repr.hpp b/include/Void/Functional/Detail/Repr.hpp index 3db0291..dab6d9e 100644 --- a/include/Void/Functional/Detail/Repr.hpp +++ b/include/Void/Functional/Detail/Repr.hpp @@ -1,81 +1,24 @@ #pragma once -#include -#include -#include -#include +#include -#if __has_include() && defined(__cpp_consteval) -#include +#include + +#ifdef VOID_HAS_META_REFLECTION #define VOID_RESULT_HAS_REFLECTION 1 #endif namespace Void::Result::Detail { - /// Render a value for diagnostic / log output. - /// - /// Resolution order: - /// 1. If a `std::formatter` exists, use `std::format("{}", v)`. - /// 2. Otherwise, if `T` exposes a `.format()` method returning - /// something convertible to `std::string`, call it. - /// 3. Otherwise, if C++26 reflection is available, walk the - /// non-static data members of `T` and render - /// `Type{field1: value1, field2: value2}`. - /// 4. Otherwise, return `""`. - template [[nodiscard]] std::string repr(const T& value); - - template - concept Formattable = std::formattable; - - template - concept HasFormatMethod = requires(const T& v) { - { v.format() } -> std::convertible_to; - }; - -#ifdef VOID_RESULT_HAS_REFLECTION - template [[nodiscard]] std::string reflect_struct(const T& obj) - { - std::string out; - if constexpr (std::meta::has_identifier(^^T)) { - out += std::meta::identifier_of(^^T); - } else { - out += "?"; - } - out += '{'; - static constexpr auto members = - std::define_static_array(std::meta::nonstatic_data_members_of( - ^^T, std::meta::access_context::unchecked())); - bool first = true; - template for (constexpr auto member : members) - { - if (!first) { - out += ", "; - } - out += std::meta::identifier_of(member); - out += ": "; - out += repr(obj.[:member:]); - first = false; - } - out += '}'; - return out; - } -#endif - + /// Render a value for diagnostic / log output. Thin alias over the shared + /// reflection layer `Void::Meta::repr`: + /// 1. std::formatter → std::format("{}", v) + /// 2. a `.format()` method returning something string-convertible + /// 3. C++26 reflection: `Type{field1: value1, field2: value2}` + /// 4. otherwise `""` template [[nodiscard]] std::string repr(const T& value) { - if constexpr (Formattable) { - return std::format("{}", value); - } else if constexpr (HasFormatMethod) { - return std::string{value.format()}; - } -#ifdef VOID_RESULT_HAS_REFLECTION - else if constexpr (std::is_class_v || std::is_union_v) { - return reflect_struct(value); - } -#endif - else { - return ""; - } + return Void::Meta::repr(value); } } // namespace Void::Result::Detail diff --git a/include/Void/Functional/Retry.hpp b/include/Void/Functional/Retry.hpp index c83f10a..3ed0ebe 100644 --- a/include/Void/Functional/Retry.hpp +++ b/include/Void/Functional/Retry.hpp @@ -5,122 +5,209 @@ #include #include #include +#include #include #include namespace Void::Retry { -// ── Backoff policies ────────────────────────────────────────────────────────── + // ── Backoff policies + // ────────────────────────────────────────────────────────── -struct NoDelay -{ - [[nodiscard]] std::chrono::milliseconds delay(std::size_t /*attempt*/) const noexcept - { - return std::chrono::milliseconds{0}; - } -}; + struct NoDelay { + [[nodiscard]] std::chrono::milliseconds + delay(std::size_t /*attempt*/) const noexcept + { + return std::chrono::milliseconds{0}; + } + }; -struct ConstantDelay -{ - std::chrono::milliseconds interval{100}; + struct ConstantDelay { + std::chrono::milliseconds interval{100}; - [[nodiscard]] std::chrono::milliseconds delay(std::size_t) const noexcept - { - return interval; - } -}; + [[nodiscard]] std::chrono::milliseconds + delay(std::size_t) const noexcept + { + return interval; + } + }; -struct LinearBackoff -{ - std::chrono::milliseconds base{100}; - std::chrono::milliseconds max{10'000}; + struct LinearBackoff { + std::chrono::milliseconds base{100}; + std::chrono::milliseconds max{10'000}; - [[nodiscard]] std::chrono::milliseconds delay(std::size_t attempt) const noexcept - { - const auto raw = base.count() * static_cast(attempt + 1); - const auto capped = std::min(raw, static_cast(max.count())); - return std::chrono::milliseconds{capped}; - } -}; + [[nodiscard]] std::chrono::milliseconds + delay(std::size_t attempt) const noexcept + { + const auto raw = + base.count() * static_cast(attempt + 1); + const auto capped = + std::min(raw, static_cast(max.count())); + return std::chrono::milliseconds{capped}; + } + }; -struct ExponentialBackoff -{ - std::chrono::milliseconds base{100}; - std::chrono::milliseconds max{30'000}; - double multiplier{2.0}; + struct ExponentialBackoff { + std::chrono::milliseconds base{100}; + std::chrono::milliseconds max{30'000}; + double multiplier{2.0}; - [[nodiscard]] std::chrono::milliseconds delay(std::size_t attempt) const noexcept - { - double ms = static_cast(base.count()); - for (std::size_t i = 0; i < attempt; ++i) ms *= multiplier; - const auto clamped = std::min(ms, static_cast(max.count())); - return std::chrono::milliseconds{static_cast(clamped)}; - } -}; + [[nodiscard]] std::chrono::milliseconds + delay(std::size_t attempt) const noexcept + { + double ms = static_cast(base.count()); + for (std::size_t i = 0; i < attempt; ++i) { + ms *= multiplier; + } + const auto clamped = + std::min(ms, static_cast(max.count())); + return std::chrono::milliseconds{ + static_cast(clamped)}; + } + }; -// ── Policy ──────────────────────────────────────────────────────────────────── + // ── Jitter + // ──────────────────────────────────────────────────────────────────── Wrap + // any backoff to randomize its delay and avoid thundering-herd retries. + // Full: uniform in [0, base] + // Equal: base/2 + uniform in [0, base/2] (keeps a guaranteed floor) -template -struct Policy -{ - std::size_t max_attempts{3}; - Backoff backoff{}; + enum class JitterMode { Full, Equal }; - using BackoffType = Backoff; -}; + template struct Jittered { + Backoff inner{}; + JitterMode mode{JitterMode::Full}; -// ── retry — retries a callable up to max_attempts times ────────────────────── -// The callable must return std::expected. Retries on unexpected values. -// Returns the last result (success or final error) after all attempts. + [[nodiscard]] std::chrono::milliseconds + delay(std::size_t attempt) const + { + const auto base = inner.delay(attempt).count(); + if (base <= 0) { + return std::chrono::milliseconds{0}; + } + thread_local std::mt19937_64 rng{std::random_device{}()}; + const long long floor = + (mode == JitterMode::Equal) ? base / 2 : 0; + std::uniform_int_distribution dist{0, base - floor}; + return std::chrono::milliseconds{floor + dist(rng)}; + } + }; -template - requires std::invocable -auto retry(const Policy& policy, F&& fn) -{ - using Result = std::invoke_result_t; - Result last_result; - for (std::size_t attempt = 0; attempt < policy.max_attempts; ++attempt) { - last_result = fn(); - if (last_result.has_value()) return last_result; - if (attempt + 1 < policy.max_attempts) { - const auto wait = policy.backoff.delay(attempt); - if (wait.count() > 0) std::this_thread::sleep_for(wait); - } - } - return last_result; -} + // ── Policy + // ──────────────────────────────────────────────────────────────────── -// ── retry_or_throw — throws on final failure ────────────────────────────────── + template struct Policy { + std::size_t max_attempts{3}; + Backoff backoff{}; + // Total wall-clock budget across all attempts (0 = unlimited). Once + // the elapsed time reaches this, no further attempts are made and + // the inter- attempt sleep is clamped so it never overshoots the + // budget. + std::chrono::milliseconds max_elapsed{0}; -template - requires std::invocable -auto retry_or_throw(const Policy& policy, F&& fn) -{ - auto result = retry(policy, std::forward(fn)); - if (!result.has_value()) { - throw std::runtime_error{"all retry attempts failed"}; - } - return *result; -} + using BackoffType = Backoff; + }; -// ── retry_while — retries while a predicate on the result holds ─────────────── -// Useful for retrying on specific error codes without expected. + namespace Detail + { + // Sleep for `wait`, honoring a total budget measured from `start`. + // Returns false if the budget is exhausted (caller should stop + // retrying). + template + [[nodiscard]] inline bool + backoff_sleep(const Policy& policy, std::size_t attempt, + std::chrono::steady_clock::time_point start) + { + using namespace std::chrono; + if (policy.max_elapsed.count() > 0) { + const auto elapsed = + duration_cast(steady_clock::now() - start); + if (elapsed >= policy.max_elapsed) { + return false; + } + auto wait = policy.backoff.delay(attempt); + const auto rem = policy.max_elapsed - elapsed; + wait = std::min(wait, rem); + if (wait.count() > 0) { + std::this_thread::sleep_for(wait); + } + return true; + } + const auto wait = policy.backoff.delay(attempt); + if (wait.count() > 0) { + std::this_thread::sleep_for(wait); + } + return true; + } + } // namespace Detail -template - requires std::invocable && std::predicate> -std::invoke_result_t retry_while(const Policy& policy, F&& fn, Pred&& should_retry) -{ - std::invoke_result_t last{}; - for (std::size_t attempt = 0; attempt < policy.max_attempts; ++attempt) { - last = fn(); - if (!should_retry(last)) return last; - if (attempt + 1 < policy.max_attempts) { - const auto wait = policy.backoff.delay(attempt); - if (wait.count() > 0) std::this_thread::sleep_for(wait); - } - } - return last; -} + // ── retry — retries a callable up to max_attempts times + // ────────────────────── The callable must return std::expected. + // Retries on unexpected values. Returns the last result (success or final + // error) after all attempts. + + template + requires std::invocable + auto retry(const Policy& policy, F&& fn) + { + using Result = std::invoke_result_t; + const auto start = std::chrono::steady_clock::now(); + Result last_result; + for (std::size_t attempt = 0; attempt < policy.max_attempts; + ++attempt) { + last_result = fn(); + if (last_result.has_value()) { + return last_result; + } + if (attempt + 1 < policy.max_attempts) { + if (!Detail::backoff_sleep(policy, attempt, start)) { + break; + } + } + } + return last_result; + } + + // ── retry_or_throw — throws on final failure + // ────────────────────────────────── + + template + requires std::invocable + auto retry_or_throw(const Policy& policy, F&& fn) + { + auto result = retry(policy, std::forward(fn)); + if (!result.has_value()) { + throw std::runtime_error{"all retry attempts failed"}; + } + return *result; + } + + // ── retry_while — retries while a predicate on the result holds + // ─────────────── Useful for retrying on specific error codes without + // expected. + + template + requires std::invocable && + std::predicate> + std::invoke_result_t retry_while(const Policy& policy, F&& fn, + Pred&& should_retry) + { + const auto start = std::chrono::steady_clock::now(); + std::invoke_result_t last{}; + for (std::size_t attempt = 0; attempt < policy.max_attempts; + ++attempt) { + last = fn(); + if (!should_retry(last)) { + return last; + } + if (attempt + 1 < policy.max_attempts) { + if (!Detail::backoff_sleep(policy, attempt, start)) { + break; + } + } + } + return last; + } } // namespace Void::Retry diff --git a/include/Void/Log/Field.hpp b/include/Void/Log/Field.hpp index 64526df..9628377 100644 --- a/include/Void/Log/Field.hpp +++ b/include/Void/Log/Field.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -24,6 +26,23 @@ namespace Void::Logging explicit FieldScope( std::initializer_list> fields); + explicit FieldScope( + std::vector> fields); + + /// Reflect an aggregate's data members into structured fields + /// (key = field name, value = Void::Meta::repr of the value): + /// auto fs = Logging::FieldScope::from(request); + template + [[nodiscard]] static FieldScope from(const T& obj) + { + std::vector> fields; + Void::Meta::for_each_field( + obj, [&](std::string_view name, const auto& value) { + fields.emplace_back(std::string{name}, + Void::Meta::repr(value)); + }); + return FieldScope{std::move(fields)}; + } ~FieldScope() noexcept; diff --git a/include/Void/Log/Formatter.hpp b/include/Void/Log/Formatter.hpp index 1b4a573..67e54fe 100644 --- a/include/Void/Log/Formatter.hpp +++ b/include/Void/Log/Formatter.hpp @@ -134,12 +134,45 @@ namespace Void::Logging ColorPolicy m_colors; }; + /// An allow/deny list applied to an entry's structured fields by the + /// json/logfmt sinks. `include` empty means "all keys" (still subject to + /// `exclude`); a non-empty `include` admits only those keys. `exclude` + /// always wins. + struct FieldFilter { + std::vector include; + std::vector exclude; + + [[nodiscard]] bool allows(std::string_view key) const + { + for (const auto& e : exclude) { + if (e == key) { + return false; + } + } + if (include.empty()) { + return true; + } + for (const auto& i : include) { + if (i == key) { + return true; + } + } + return false; + } + }; + /// One compact JSON object per entry (includes fields when present). class JsonLinesFormatter final : public Formatter { public: [[nodiscard]] std::string format(const Entry& entry) const override; + + void set_field_filter(FieldFilter f) { m_fields = std::move(f); } + + private: + + FieldFilter m_fields; }; /// logfmt: time=... level=... thread=... msg="..." plus scopes/fields. @@ -148,6 +181,12 @@ namespace Void::Logging public: [[nodiscard]] std::string format(const Entry& entry) const override; + + void set_field_filter(FieldFilter f) { m_fields = std::move(f); } + + private: + + FieldFilter m_fields; }; namespace FormatDetail diff --git a/include/Void/Resilience/CircuitBreaker.hpp b/include/Void/Resilience/CircuitBreaker.hpp new file mode 100644 index 0000000..729b874 --- /dev/null +++ b/include/Void/Resilience/CircuitBreaker.hpp @@ -0,0 +1,140 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Resilience +{ + + // ── CircuitBreaker + // ──────────────────────────────────────────────────────────── A + // three-state breaker that stops hammering a failing dependency. + // + // Closed calls flow; `failure_threshold` consecutive failures trip it + // Open. Open calls are rejected until `cooldown` elapses, then one + // probe is let + // through (HalfOpen). + // HalfOpen `success_threshold` probe successes close it; any failure + // re-opens. + // + // Use allow()/record_success()/record_failure() to gate work directly, or + // execute() to wrap a std::expected-returning step. Thread-safe; clock + // injectable for deterministic tests. + + template + concept HasHasValue = requires(const R& r) { + { r.has_value() } -> std::convertible_to; + }; + + class CircuitBreaker + { + public: + + enum class State { Closed, Open, HalfOpen }; + + using Clock = + std::function; + using Duration = std::chrono::steady_clock::duration; + using TimePoint = std::chrono::steady_clock::time_point; + + CircuitBreaker(std::size_t failure_threshold, Duration cooldown, + std::size_t success_threshold = 1, + Clock clock = default_clock()) + : failure_threshold_{failure_threshold}, cooldown_{cooldown}, + success_threshold_{success_threshold}, + clock_{std::move(clock)} + { + } + + // Whether a call may proceed now. Transitions Open -> HalfOpen once + // the cooldown has elapsed (admitting a probe). + [[nodiscard]] bool allow() + { + std::lock_guard lock{mu_}; + if (state_ == State::Open && + clock_() - opened_at_ >= cooldown_) { + state_ = State::HalfOpen; + successes_ = 0; + } + return state_ != State::Open; + } + + void record_success() + { + std::lock_guard lock{mu_}; + if (state_ == State::HalfOpen) { + if (++successes_ >= success_threshold_) { + state_ = State::Closed; + failures_ = 0; + } + } else { + failures_ = 0; + } + } + + void record_failure() + { + std::lock_guard lock{mu_}; + if (state_ == State::HalfOpen) { + trip(); + } else if (++failures_ >= failure_threshold_) { + trip(); + } + } + + [[nodiscard]] State state() + { + std::lock_guard lock{mu_}; + return state_; + } + + // Gate a std::expected-returning callable. Returns nullopt when the + // circuit rejects the call; otherwise runs it, records the outcome, + // and returns its result. + template + requires HasHasValue> + auto execute(F&& fn) -> std::optional> + { + if (!allow()) { + return std::nullopt; + } + auto result = std::forward(fn)(); + if (result.has_value()) { + record_success(); + } else { + record_failure(); + } + return result; + } + + private: + + static Clock default_clock() + { + return [] { return std::chrono::steady_clock::now(); }; + } + + void trip() + { + state_ = State::Open; + opened_at_ = clock_(); + } + + std::size_t failure_threshold_; + Duration cooldown_; + std::size_t success_threshold_; + Clock clock_; + + State state_ = State::Closed; + std::size_t failures_ = 0; + std::size_t successes_ = 0; + TimePoint opened_at_{}; + std::mutex mu_; + }; + +} // namespace Void::Resilience diff --git a/include/Void/Resilience/KeyedRateLimiter.hpp b/include/Void/Resilience/KeyedRateLimiter.hpp new file mode 100644 index 0000000..7bec73f --- /dev/null +++ b/include/Void/Resilience/KeyedRateLimiter.hpp @@ -0,0 +1,123 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Resilience +{ + + // ── KeyedRateLimiter ─────────────────────────────────────────────── + // A rate limiter that maintains an independent TokenBucket per distinct + // Key. Every key shares the same capacity + refill rate; buckets are + // created lazily on first use and can be reclaimed with cleanup(). Thread- + // safe. Generic over the key type (e.g. a client id, IP, or user name). + + template > + class KeyedRateLimiter + { + public: + + using Clock = TokenBucket::Clock; + + // `capacity` is the burst size; `refill_per_sec` the sustained rate. + // The clock is shared with every bucket so tests stay deterministic. + explicit KeyedRateLimiter(double capacity, double refill_per_sec, + Clock clock = default_clock()) + : capacity_{capacity}, rate_{refill_per_sec}, + clock_{std::move(clock)} + { + } + + // Consume `tokens` for `key`. Returns false (without consuming) when + // the key's bucket is exhausted. + [[nodiscard]] bool allow(const Key& key, double tokens = 1.0) + { + std::lock_guard lock{mu_}; + return entry(key).bucket->try_acquire(tokens); + } + + // Tokens currently available to `key` (creates the bucket if new). + [[nodiscard]] double remaining(const Key& key) + { + std::lock_guard lock{mu_}; + return entry(key).bucket->available(); + } + + // Forget a key's bucket (its next use starts full). + void reset(const Key& key) + { + std::lock_guard lock{mu_}; + map_.erase(key); + } + + // Drop buckets not touched within `max_age`. Returns how many were + // removed. Call periodically to bound memory for churny key spaces. + std::size_t cleanup(std::chrono::steady_clock::duration max_age) + { + const auto now = std::chrono::steady_clock::now(); + std::lock_guard lock{mu_}; + std::size_t removed = 0; + for (auto it = map_.begin(); it != map_.end();) { + if (now - it->second.last_seen >= max_age) { + it = map_.erase(it); + ++removed; + } else { + ++it; + } + } + return removed; + } + + // Number of keys currently tracked. + [[nodiscard]] std::size_t tracked() const + { + std::lock_guard lock{mu_}; + return map_.size(); + } + + private: + + static Clock default_clock() + { + return [] { return std::chrono::steady_clock::now(); }; + } + + struct Entry { + // TokenBucket owns a std::mutex (non-movable), so hold it by + // pointer to keep Entry movable for the hash map. + std::unique_ptr bucket; + std::chrono::steady_clock::time_point last_seen; + }; + + Entry& entry(const Key& key) + { + const auto now = std::chrono::steady_clock::now(); + auto it = map_.find(key); + if (it == map_.end()) { + it = map_ + .emplace(key, + Entry{std::make_unique( + capacity_, rate_, clock_), + now}) + .first; + } else { + it->second.last_seen = now; + } + return it->second; + } + + double capacity_; + double rate_; + Clock clock_; + mutable std::mutex mu_; + std::unordered_map map_; + }; + +} // namespace Void::Resilience diff --git a/include/Void/Resilience/RateLimiter.hpp b/include/Void/Resilience/RateLimiter.hpp new file mode 100644 index 0000000..fca74b8 --- /dev/null +++ b/include/Void/Resilience/RateLimiter.hpp @@ -0,0 +1,82 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Void::Resilience +{ + + // ── TokenBucket + // ─────────────────────────────────────────────────────────────── A + // token-bucket rate limiter. The bucket holds up to `capacity` tokens and + // refills continuously at `refill_per_sec` tokens per second. + // try_acquire(n) consumes n tokens when available. Thread-safe; the clock + // is injectable so the refill behaviour is deterministic in tests. + + class TokenBucket + { + public: + + using Clock = + std::function; + using TimePoint = std::chrono::steady_clock::time_point; + + TokenBucket(double capacity, double refill_per_sec, + Clock clock = default_clock()) + : capacity_{capacity}, rate_{refill_per_sec}, tokens_{capacity}, + clock_{std::move(clock)}, last_{clock_()} + { + } + + // Consume `tokens` if the bucket (after refilling for elapsed time) + // holds at least that many. Returns false without consuming + // anything otherwise. + [[nodiscard]] bool try_acquire(double tokens = 1.0) + { + std::lock_guard lock{mu_}; + refill(); + if (tokens_ >= tokens) { + tokens_ -= tokens; + return true; + } + return false; + } + + // Current token count after refilling for elapsed time. + [[nodiscard]] double available() + { + std::lock_guard lock{mu_}; + refill(); + return tokens_; + } + + [[nodiscard]] double capacity() const noexcept { return capacity_; } + + private: + + static Clock default_clock() + { + return [] { return std::chrono::steady_clock::now(); }; + } + + void refill() + { + const auto now = clock_(); + const std::chrono::duration elapsed = now - last_; + last_ = now; + tokens_ = + std::min(capacity_, tokens_ + elapsed.count() * rate_); + } + + double capacity_; + double rate_; + double tokens_; + Clock clock_; + TimePoint last_; + std::mutex mu_; + }; + +} // namespace Void::Resilience diff --git a/include/Void/Resilience/Resilience.hpp b/include/Void/Resilience/Resilience.hpp new file mode 100644 index 0000000..f31ba9b --- /dev/null +++ b/include/Void/Resilience/Resilience.hpp @@ -0,0 +1,10 @@ +#pragma once + +// Umbrella header for the Resilience module: rate limiting, circuit breaking, +// and resource monitoring. These complement Functional/Retry.hpp (retry with +// backoff) rather than replacing it. + +#include +#include +#include +#include diff --git a/include/Void/Resilience/ResourceMonitor.hpp b/include/Void/Resilience/ResourceMonitor.hpp new file mode 100644 index 0000000..02d3e2e --- /dev/null +++ b/include/Void/Resilience/ResourceMonitor.hpp @@ -0,0 +1,117 @@ +#pragma once + +#include +#include +#include +#include + +namespace Void::Resilience +{ + + // ── ResourceMonitor + // ─────────────────────────────────────────────────────────── Tracks usage + // of a bounded resource (memory budget, in-flight requests, queue depth, + // ...) against a limit, with hysteresis watermark callbacks. + // + // try_acquire() refuses to exceed the limit. Crossing the high watermark + // upward fires on_high_watermark once; dropping back to the low watermark + // fires on_low_watermark once (the gap prevents callback flapping). + // Callbacks run outside the internal lock. + + class ResourceMonitor + { + public: + + using Callback = std::function; + + // high/low are fractions of `limit` in [0, 1]; high should exceed + // low. + explicit ResourceMonitor(std::uint64_t limit, double high = 0.9, + double low = 0.7) + : limit_{limit}, high_{static_cast( + static_cast(limit) * high)}, + low_{static_cast(static_cast(limit) * + low)} + { + } + + void on_high_watermark(Callback cb) { on_high_ = std::move(cb); } + void on_low_watermark(Callback cb) { on_low_ = std::move(cb); } + + // Reserve `amount`. Returns false (reserving nothing) if it would + // exceed the limit. May fire the high-watermark callback when + // crossing upward. + [[nodiscard]] bool try_acquire(std::uint64_t amount = 1) + { + Callback fire; + std::uint64_t at = 0; + { + std::lock_guard lock{mu_}; + if (usage_ + amount > limit_) { + return false; + } + usage_ += amount; + if (!alarmed_ && usage_ >= high_) { + alarmed_ = true; + fire = on_high_; + at = usage_; + } + } + if (fire) { + fire(at); + } + return true; + } + + // Release `amount` (clamped at zero). May fire the low-watermark + // callback when dropping back through the low threshold. + void release(std::uint64_t amount = 1) + { + Callback fire; + std::uint64_t at = 0; + { + std::lock_guard lock{mu_}; + usage_ = (amount >= usage_) ? 0 : usage_ - amount; + if (alarmed_ && usage_ <= low_) { + alarmed_ = false; + fire = on_low_; + at = usage_; + } + } + if (fire) { + fire(at); + } + } + + [[nodiscard]] std::uint64_t usage() const + { + std::lock_guard lock{mu_}; + return usage_; + } + + [[nodiscard]] std::uint64_t limit() const noexcept + { + return limit_; + } + + [[nodiscard]] double utilization() const + { + std::lock_guard lock{mu_}; + return limit_ == 0 ? 0.0 + : static_cast(usage_) / + static_cast(limit_); + } + + private: + + std::uint64_t limit_; + std::uint64_t high_; + std::uint64_t low_; + std::uint64_t usage_ = 0; + bool alarmed_ = false; + Callback on_high_; + Callback on_low_; + mutable std::mutex mu_; + }; + +} // namespace Void::Resilience diff --git a/include/Void/Service/Registry.hpp b/include/Void/Service/Registry.hpp index d818730..6d91112 100644 --- a/include/Void/Service/Registry.hpp +++ b/include/Void/Service/Registry.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -14,6 +15,16 @@ namespace Void::Service { +#ifdef VOID_HAS_META_REFLECTION + /// The reflected (unqualified) name of an interface type — a sensible + /// default service name when an IService impl doesn't override + /// service_name(). E.g. interface_name() == "IClock". + template [[nodiscard]] std::string interface_name() + { + return Void::Meta::type_name(); + } +#endif + /// Type-keyed service container: providers register an implementation /// against an interface type, consumers resolve by that interface and /// never name the concrete type — the core of the dependency-inversion @@ -32,6 +43,16 @@ namespace Void::Service ServiceRegistry(const ServiceRegistry&) = delete; ServiceRegistry& operator=(const ServiceRegistry&) = delete; + /// Create a scoped child registry that overlays `parent`: lookups + /// fall through to the parent when a key is not provided locally, + /// and a local provide() shadows the parent's entry. Lifecycle + /// (start_all/stop_all) covers only locally-provided services. The + /// parent must outlive this registry. + explicit ServiceRegistry(const ServiceRegistry* parent) + : m_parent{parent} + { + } + /// Register (or replace) the implementation for interface I. /// If I derives IService, the instance joins the lifecycle. template void provide(std::shared_ptr impl) @@ -54,15 +75,18 @@ namespace Void::Service m_services.insert_or_assign(key, std::move(entry)); } - /// Resolve I, or nullptr if not provided. + /// Resolve I, or nullptr if not provided. Falls through to the + /// parent registry (if any) on a local miss. template [[nodiscard]] std::shared_ptr get() const { - std::shared_lock lock{m_mutex}; - const auto it = m_services.find(std::type_index{typeid(I)}); - if (it == m_services.end()) { - return nullptr; + { + std::shared_lock lock{m_mutex}; + const auto it = m_services.find(std::type_index{typeid(I)}); + if (it != m_services.end()) { + return std::static_pointer_cast(it->second.impl); + } } - return std::static_pointer_cast(it->second.impl); + return m_parent ? m_parent->get() : nullptr; } /// Resolve I; throws std::runtime_error if not provided. @@ -79,8 +103,13 @@ namespace Void::Service template [[nodiscard]] bool has() const { - std::shared_lock lock{m_mutex}; - return m_services.contains(std::type_index{typeid(I)}); + { + std::shared_lock lock{m_mutex}; + if (m_services.contains(std::type_index{typeid(I)})) { + return true; + } + } + return m_parent ? m_parent->has() : false; } /// Call on_start() on every lifecycle service, registration @@ -119,6 +148,7 @@ namespace Void::Service IService* service = nullptr; // non-null iff I : IService }; + const ServiceRegistry* m_parent = nullptr; mutable std::shared_mutex m_mutex; std::unordered_map m_services; std::vector m_order; diff --git a/include/Void/System/Metrics.hpp b/include/Void/System/Metrics.hpp new file mode 100644 index 0000000..da1215d --- /dev/null +++ b/include/Void/System/Metrics.hpp @@ -0,0 +1,124 @@ +#pragma once + +#include +#include +#include + +#if defined(__linux__) +#include +#include +#include +#include +#include +#endif + +// Generic, app-agnostic process/system resource queries. Used to feed monitors +// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully +// supported; other platforms return nullopt / 0 so callers degrade gracefully. + +namespace Void::SystemInfo +{ + + // ── memory ────────────────────────────────────────────────────────────── + + /// Resident set size (physical memory) of the current process, in bytes. + /// nullopt if it cannot be determined on this platform. + [[nodiscard]] inline std::optional process_memory_bytes() + { +#if defined(__linux__) + // /proc/self/statm: "size resident shared text lib data dt" in pages. + std::ifstream statm{"/proc/self/statm"}; + std::uint64_t total_pages = 0, resident_pages = 0; + if (statm >> total_pages >> resident_pages) { + const long page = ::sysconf(_SC_PAGESIZE); + if (page > 0) { + return resident_pages * static_cast(page); + } + } + return std::nullopt; +#else + return std::nullopt; +#endif + } + + struct SystemMemory { + std::uint64_t total = 0; ///< total physical RAM, bytes + std::uint64_t available = 0; ///< approx. RAM available to new work + }; + + /// Total and (approximately) available system memory in bytes. + [[nodiscard]] inline std::optional system_memory() + { +#if defined(__linux__) + struct ::sysinfo info{}; + if (::sysinfo(&info) != 0) { + return std::nullopt; + } + const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1; + SystemMemory m; + m.total = static_cast(info.totalram) * unit; + // freeram excludes reclaimable cache/buffers, so this is conservative. + m.available = + (static_cast(info.freeram) + info.bufferram) * unit; + return m; +#else + return std::nullopt; +#endif + } + + // ── CPU ───────────────────────────────────────────────────────────────── + + /// Samples this process's CPU usage between successive calls. usage() + /// returns the fraction of a single core consumed since the previous + /// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on + /// multi-core workloads). The first call establishes the baseline and + /// returns 0. + class CpuSampler + { + public: + + CpuSampler() { reset(); } + + void reset() + { + wall_ = std::chrono::steady_clock::now(); +#if defined(__linux__) + struct ::tms t{}; + last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1)) + ? 0 + : (t.tms_utime + t.tms_stime); +#endif + } + + [[nodiscard]] double usage() + { + const auto now = std::chrono::steady_clock::now(); + const std::chrono::duration wall = now - wall_; + wall_ = now; +#if defined(__linux__) + const long hz = ::sysconf(_SC_CLK_TCK); + struct ::tms t{}; + if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) || + wall.count() <= 0.0) { + return 0.0; + } + const std::int64_t ticks = t.tms_utime + t.tms_stime; + const double cpu_seconds = + static_cast(ticks - last_ticks_) / + static_cast(hz); + last_ticks_ = ticks; + return cpu_seconds / wall.count(); +#else + return 0.0; +#endif + } + + private: + + std::chrono::steady_clock::time_point wall_; +#if defined(__linux__) + std::int64_t last_ticks_ = 0; +#endif + }; + +} // namespace Void::SystemInfo diff --git a/include/Void/System/Process.hpp b/include/Void/System/Process.hpp index a7bf5be..4950855 100644 --- a/include/Void/System/Process.hpp +++ b/include/Void/System/Process.hpp @@ -5,40 +5,62 @@ #include #include +#include #include +#include #include namespace Void::Process { -/// Captured output from a completed subprocess. -struct Output { - int exit_code{0}; - std::string out; ///< captured stdout - std::string err; ///< captured stderr -}; + /// Captured output from a completed subprocess. + struct Output { + int exit_code{0}; + std::string out; ///< captured stdout + std::string err; ///< captured stderr + }; -/// Run an executable synchronously, capturing stdout and stderr separately. -/// -/// @param executable Path to the binary (searched via PATH when relative). -/// @param args Additional arguments passed after argv[0]. -/// @param stdin_data Data written to the process's stdin before reading. -/// @param timeout Wall-clock limit; zero means no limit. On expiry the -/// process receives SIGTERM and the call returns. -/// -/// Returns an error only when process creation itself fails (pipe or fork -/// failure). A process that exits non-zero still yields a successful Result -/// with the appropriate exit_code. A process whose executable is not found -/// exits with code 127 (POSIX convention). -[[nodiscard]] Void::Result::Result - run(const std::filesystem::path& executable, - std::vector args = {}, - std::string_view stdin_data = {}, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + /// Live line callbacks for run_streaming(). Each fires (on the calling + /// thread, as output arrives) with one line of output, newline stripped. + /// Either may be left empty. The full output is still accumulated into the + /// returned Output. + struct StreamCallbacks { + std::function on_stdout; + std::function on_stderr; + }; -/// Run a command through /bin/sh -c "command". -[[nodiscard]] Void::Result::Result - shell(std::string_view command, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + /// Run an executable synchronously, capturing stdout and stderr separately. + /// + /// @param executable Path to the binary (searched via PATH when relative). + /// @param args Additional arguments passed after argv[0]. + /// @param stdin_data Data written to the process's stdin before reading. + /// @param timeout Wall-clock limit; zero means no limit. On expiry the + /// process receives SIGTERM and the call returns. + /// + /// Returns an error only when process creation itself fails (pipe or fork + /// failure). A process that exits non-zero still yields a successful Result + /// with the appropriate exit_code. A process whose executable is not found + /// exits with code 127 (POSIX convention). + [[nodiscard]] Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args = {}, + std::string_view stdin_data = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + + /// Like run(), but invokes `callbacks` line-by-line as stdout/stderr + /// arrive, for progress reporting on long-running or streaming processes. + /// The complete output is still captured into the returned Output. + [[nodiscard]] Void::Result::Result + run_streaming( + const std::filesystem::path& executable, + std::vector args, + const StreamCallbacks& callbacks, + std::string_view stdin_data = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + + /// Run a command through /bin/sh -c "command". + [[nodiscard]] Void::Result::Result + shell(std::string_view command, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); } // namespace Void::Process diff --git a/include/Void/Testing/Annotations.hpp b/include/Void/Testing/Annotations.hpp new file mode 100644 index 0000000..24eb2d6 --- /dev/null +++ b/include/Void/Testing/Annotations.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include + +// Reflection-readable test metadata. Annotate a suite's test methods: +// struct MathTests : Void::Testing::Suite { +// [[= Testing::tag("integration")]] Void::Testing::Test db() { … } +// [[= Testing::skip("flaky #42")]] Void::Testing::Test wip() { … } +// }; +// Multiple `tag(...)` annotations attach multiple tags. A `name(...)` on the +// suite struct overrides its reported suite label (default: the struct name). + +namespace Void::Testing +{ + /// A test tag (repeatable). + struct Tag { + Void::Meta::Str value; + }; + /// Mark a test skipped, with a reason. + struct Skip { + Void::Meta::Str reason; + }; + /// Override a suite's reported label (annotate the suite struct). + struct Name { + Void::Meta::Str value; + }; + + /// Annotation factories so tests read `[[= Testing::tag("x")]]`. + [[nodiscard]] consteval Tag tag(const char* value) { return Tag{value}; } + [[nodiscard]] consteval Skip skip(const char* reason) + { + return Skip{reason}; + } + [[nodiscard]] consteval Name name(const char* value) { return Name{value}; } +} // namespace Void::Testing diff --git a/include/Void/Testing/Suite.hpp b/include/Void/Testing/Suite.hpp new file mode 100644 index 0000000..0cc32bd --- /dev/null +++ b/include/Void/Testing/Suite.hpp @@ -0,0 +1,175 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +#if __has_include() +#include +#define VOID_TESTING_HAS_REFLECTION 1 +#endif + +// ── Reflection-based test registration +// ──────────────────────────────────────── Derive a test suite from +// `Suite` (CRTP). Every public, 0-argument member function returning +// `Test`/`DisabledTest` (i.e. void) — except `setup` and `teardown` — is +// auto-registered as a test by reflecting `Derived`. No CMake scan, no macros, +// no registrar line: a `[[gnu::used]]` static in the base forces registration +// at program start even though the suite is never instantiated for its own +// sake. +// +// struct MathTests : Void::Testing::Suite { +// void setup() { … } // optional, per-test +// Void::Testing::Test addition() { expect_eq(1 + 1, 2); } +// [[= Testing::tag("slow")]] Void::Testing::Test big() { … } +// [[= Testing::skip("wip")]] Void::Testing::Test later() { … } +// }; +// +// The suite label defaults to the struct's name; `[[= Testing::name("Math")]]` +// on the struct overrides it. + +namespace Void::Testing +{ + +#ifdef VOID_TESTING_HAS_REFLECTION + + namespace Detail + { + namespace meta = std::meta; + + /// A reflected member is a test if it is a public, non-special, + /// 0-argument member function returning void, other than the + /// setup/teardown lifecycle hooks. + consteval bool is_test_method(meta::info m) + { + if (!meta::is_function(m) || meta::is_special_member_function(m)) { + return false; + } + if (meta::is_static_member(m)) { + return false; + } + if (meta::parameters_of(m).size() != 0) { + return false; + } + if (meta::dealias(meta::return_type_of(m)) != ^^void) { + return false; + } + const std::string_view id = meta::identifier_of(m); + return id != "setup" && id != "teardown"; + } + } // namespace Detail + + namespace meta = std::meta; + + template class Suite + { + protected: + + Suite() = default; + + private: + + /// Run one reflected test method against a fresh Derived instance, + /// wrapping it in setup()/teardown() when present. + template static void run_method() + { + Derived d{}; + if constexpr (requires { d.setup(); }) { + d.setup(); + } + try { + d.[:M:](); + } catch (...) { + if constexpr (requires { d.teardown(); }) { + d.teardown(); + } + throw; + } + if constexpr (requires { d.teardown(); }) { + d.teardown(); + } + } + + static std::string suite_label() + { + if constexpr (constexpr auto n = + Void::Meta::annotation_of(^^Derived); + n.has_value()) { + return std::string{n->value.view()}; + } else { + return Void::Meta::type_name(); + } + } + + static void register_all() + { + auto& reg = Detail::Registry::instance(); + const std::string suite = suite_label(); + + template for (constexpr auto m : + std::define_static_array(meta::members_of( + ^^Derived, + meta::access_context::unchecked()))) + { + if constexpr (Detail::is_test_method(m)) { + constexpr auto loc = meta::source_location_of(m); + + std::vector tags; + template for (constexpr auto a : + std::define_static_array( + meta::annotations_of_with_type( + m, ^^Tag))) + { + constexpr Tag t = meta::extract(a); + tags.emplace_back(t.value.view()); + } + + bool disabled = false; + std::string skip_reason; + if constexpr (constexpr auto s = + Void::Meta::annotation_of(m); + s.has_value()) { + disabled = true; + skip_reason = std::string{s->reason.view()}; + } + + reg.add(TestCase{ + .run = [] { run_method(); }, + .name = std::string{meta::identifier_of(m)}, + .suite = suite, + .file = loc.file_name(), + .line = static_cast(loc.line()), + .disabled = disabled, + .skip_reason = std::move(skip_reason), + .tags = std::move(tags), + }); + } + } + } + + struct Registrar { + Registrar() { register_all(); } + }; + // Force the static initializer to run even though Derived is never + // instantiated for its own sake (no test object, no registrar + // line). + [[gnu::used]] static inline Registrar _registrar{}; + }; + +#else // no reflection — Suite is unavailable; use the CMake scanner path + + template class Suite + { + protected: + + Suite() = default; + }; + +#endif // VOID_TESTING_HAS_REFLECTION + +} // namespace Void::Testing diff --git a/include/Void/TestingMock/Reflect.hpp b/include/Void/TestingMock/Reflect.hpp new file mode 100644 index 0000000..546a93f --- /dev/null +++ b/include/Void/TestingMock/Reflect.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include + +#include +#include +#include +#include + +#if __has_include() +#include +#define VOID_MOCK_HAS_REFLECTION 1 +#endif + +// ── Reflection helpers for mocking +// ──────────────────────────────────────────── This toolchain's P2996 has rich +// introspection + define_aggregate (it can even generate a MockFunction +// data member per interface virtual), but it has NO code injection, so the +// virtual *override functions* a full auto-mock needs cannot be synthesized. +// These helpers therefore cover the achievable ground: list an interface's +// virtual methods and statically check a hand-written mock implements all of +// them. + +namespace Void::TestingMock +{ + +#ifdef VOID_MOCK_HAS_REFLECTION + + namespace meta = std::meta; + + /// The identifiers of every virtual member function of interface `I` + /// (excluding the destructor), in declaration order. + template [[nodiscard]] std::vector method_names() + { + std::vector out; + template for (constexpr auto m : + std::define_static_array(meta::members_of( + ^^I, meta::access_context::unchecked()))) + { + if constexpr (meta::is_function(m) && meta::is_virtual(m) && + !meta::is_destructor(m)) { + out.emplace_back(meta::identifier_of(m)); + } + } + return out; + } + + /// Number of virtual methods (excluding the destructor) on `I`. + template [[nodiscard]] consteval std::size_t method_count() + { + std::size_t n = 0; + template for (constexpr auto m : + std::define_static_array(meta::members_of( + ^^I, meta::access_context::unchecked()))) + { + if constexpr (meta::is_function(m) && meta::is_virtual(m) && + !meta::is_destructor(m)) { + ++n; + } + } + return n; + } + + /// True if `Mock` is a complete, instantiable implementation of interface + /// `I` — i.e. it derives `I` and overrides every pure-virtual method (so no + /// abstract methods remain). A compile-time completeness check: + /// static_assert(TestingMock::covers()); + template [[nodiscard]] consteval bool covers() + { + return std::derived_from && !std::is_abstract_v; + } + +#endif // VOID_MOCK_HAS_REFLECTION + +} // namespace Void::TestingMock diff --git a/include/Void/Time/Format.hpp b/include/Void/Time/Format.hpp index 6258b44..1bfe73f 100644 --- a/include/Void/Time/Format.hpp +++ b/include/Void/Time/Format.hpp @@ -1,106 +1,201 @@ #pragma once +#include #include #include #include +#include +#include #include +#include +#include namespace Void::Time { -/// Format a duration as a compact human-readable string. -/// -/// Examples: -/// 350ns → "350ns" -/// 4500ns → "4.5µs" -/// 2300µs → "2.3ms" -/// 1500ms → "1.5s" -/// 90s → "1m 30s" -/// 5400s → "1h 30m" -[[nodiscard]] inline std::string - format_duration(std::chrono::nanoseconds d) noexcept -{ - const auto ns = d.count(); - if (ns < 0) { - return "0ns"; - } - if (ns < 1'000) { - return std::format("{}ns", ns); - } - if (ns < 1'000'000) { - const double us = static_cast(ns) / 1'000.0; - if (us < 10.0) { - return std::format("{:.1f}\xc2\xb5s", us); // µs in UTF-8 + /// Format a duration as a compact human-readable string. + /// + /// Examples: + /// 350ns → "350ns" + /// 4500ns → "4.5µs" + /// 2300µs → "2.3ms" + /// 1500ms → "1.5s" + /// 90s → "1m 30s" + /// 5400s → "1h 30m" + [[nodiscard]] inline std::string + format_duration(std::chrono::nanoseconds d) noexcept + { + const auto ns = d.count(); + if (ns < 0) { + return "0ns"; } - return std::format("{:.0f}\xc2\xb5s", us); - } - if (ns < 1'000'000'000LL) { - const double ms = static_cast(ns) / 1'000'000.0; - if (ms < 10.0) { - return std::format("{:.1f}ms", ms); + if (ns < 1'000) { + return std::format("{}ns", ns); } - return std::format("{:.0f}ms", ms); + if (ns < 1'000'000) { + const double us = static_cast(ns) / 1'000.0; + if (us < 10.0) { + return std::format("{:.1f}\xc2\xb5s", us); // µs in UTF-8 + } + return std::format("{:.0f}\xc2\xb5s", us); + } + if (ns < 1'000'000'000LL) { + const double ms = static_cast(ns) / 1'000'000.0; + if (ms < 10.0) { + return std::format("{:.1f}ms", ms); + } + return std::format("{:.0f}ms", ms); + } + const long long total_s = + std::chrono::duration_cast(d).count(); + if (total_s < 60) { + const double s = static_cast(ns) / 1'000'000'000.0; + return std::format("{:.1f}s", s); + } + if (total_s < 3600) { + const long long m = total_s / 60; + const long long s = total_s % 60; + return std::format("{}m {}s", m, s); + } + const long long h = total_s / 3600; + const long long m = (total_s % 3600) / 60; + return std::format("{}h {}m", h, m); } - const long long total_s = - std::chrono::duration_cast(d).count(); - if (total_s < 60) { - const double s = static_cast(ns) / 1'000'000'000.0; - return std::format("{:.1f}s", s); - } - if (total_s < 3600) { - const long long m = total_s / 60; - const long long s = total_s % 60; - return std::format("{}m {}s", m, s); - } - const long long h = total_s / 3600; - const long long m = (total_s % 3600) / 60; - return std::format("{}h {}m", h, m); -} -/// Format any chrono duration via the nanosecond overload. -template -[[nodiscard]] std::string - format_duration(std::chrono::duration d) noexcept -{ - return format_duration( - std::chrono::duration_cast(d)); -} + /// Format any chrono duration via the nanosecond overload. + template + [[nodiscard]] std::string + format_duration(std::chrono::duration d) noexcept + { + return format_duration( + std::chrono::duration_cast(d)); + } -/// Return the current UTC time formatted as ISO 8601 with second precision. -/// Example: "2026-05-14T10:30:00Z" -[[nodiscard]] inline std::string utc_now_iso8601() -{ - const auto now = - std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - std::tm tm{}; + /// Parse a single-unit duration string into nanoseconds. + /// + /// Grammar: a number (integer or floating) followed by one of the suffixes + /// `ns`, `us`, `ms`, `s`, `m`, `h`. An empty suffix is treated as seconds. + /// Returns nullopt on any malformed input. This is the one source of truth + /// for duration parsing — Configuration and Json reflection both route + /// through it. + [[nodiscard]] inline std::optional + parse_duration(std::string_view raw) + { + double number = 0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, number); + if (ec != std::errc{} || ptr == begin) { + return std::nullopt; + } + const std::string_view suffix{ptr, end}; + using namespace std::chrono; + const auto as_ns = [&](auto unit) { + return std::optional{duration_cast( + duration{number})}; + }; + if (suffix == "ns") { + return as_ns(nanoseconds{}); + } + if (suffix == "us") { + return as_ns(microseconds{}); + } + if (suffix == "ms") { + return as_ns(milliseconds{}); + } + if (suffix == "s" || suffix.empty()) { + return as_ns(seconds{}); + } + if (suffix == "m") { + return as_ns(minutes{}); + } + if (suffix == "h") { + return as_ns(hours{}); + } + return std::nullopt; + } + + namespace Detail + { + /// The parse_duration suffix for a duration period, when it maps to a + /// known single unit; nullopt for non-standard periods. + template + [[nodiscard]] constexpr std::optional + duration_suffix() + { + if constexpr (std::is_same_v) { + return "ns"; + } else if constexpr (std::is_same_v) { + return "us"; + } else if constexpr (std::is_same_v) { + return "ms"; + } else if constexpr (std::is_same_v>) { + return "s"; + } else if constexpr (std::is_same_v>) { + return "m"; + } else if constexpr (std::is_same_v>) { + return "h"; + } else { + return std::nullopt; + } + } + } // namespace Detail + + /// Emit a duration as a canonical, round-trippable single-unit string that + /// parse_duration accepts (e.g. milliseconds{250} -> "250ms"). The + /// duration's own period is used when it is one of the standard chrono + /// aliases; any other period falls back to a nanosecond count ("ns"), + /// which is exact for the realistic cases. The inverse of parse_duration + /// for the standard aliases. + template + [[nodiscard]] std::string + duration_to_string(std::chrono::duration d) + { + constexpr auto suffix = Detail::duration_suffix(); + if constexpr (suffix.has_value()) { + return std::format("{}{}", d.count(), *suffix); + } else { + const auto ns = + std::chrono::duration_cast(d); + return std::format("{}ns", ns.count()); + } + } + + /// Return the current UTC time formatted as ISO 8601 with second precision. + /// Example: "2026-05-14T10:30:00Z" + [[nodiscard]] inline std::string utc_now_iso8601() + { + const auto now = std::chrono::system_clock::to_time_t( + std::chrono::system_clock::now()); + std::tm tm{}; #ifdef _WIN32 - gmtime_s(&tm, &now); + gmtime_s(&tm, &now); #else - gmtime_r(&now, &tm); + gmtime_r(&now, &tm); #endif - return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", - tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec); -} + return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); + } -/// Return the current UTC time formatted as ISO 8601 with millisecond precision. -/// Example: "2026-05-14T10:30:00.123Z" -[[nodiscard]] inline std::string utc_now_iso8601_ms() -{ - const auto now_tp = std::chrono::system_clock::now(); - const auto now_t = std::chrono::system_clock::to_time_t(now_tp); - const auto ms = std::chrono::duration_cast( - now_tp.time_since_epoch()) % - 1000; - std::tm tm{}; + /// Return the current UTC time formatted as ISO 8601 with millisecond + /// precision. Example: "2026-05-14T10:30:00.123Z" + [[nodiscard]] inline std::string utc_now_iso8601_ms() + { + const auto now_tp = std::chrono::system_clock::now(); + const auto now_t = std::chrono::system_clock::to_time_t(now_tp); + const auto ms = std::chrono::duration_cast( + now_tp.time_since_epoch()) % + 1000; + std::tm tm{}; #ifdef _WIN32 - gmtime_s(&tm, &now_t); + gmtime_s(&tm, &now_t); #else - gmtime_r(&now_t, &tm); + gmtime_r(&now_t, &tm); #endif - return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", - tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count()); -} + return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count()); + } } // namespace Void::Time diff --git a/src/Configuration/module.cmake b/src/Configuration/module.cmake index bb07eea..4b836f5 100644 --- a/src/Configuration/module.cmake +++ b/src/Configuration/module.cmake @@ -1,3 +1,3 @@ void_add_module(Configuration - INTERNAL_DEPS Functional System Data + INTERNAL_DEPS Functional System Data Time ) diff --git a/src/Data/module.cmake b/src/Data/module.cmake index 9cd619b..9e64f43 100644 --- a/src/Data/module.cmake +++ b/src/Data/module.cmake @@ -1 +1,3 @@ -void_add_module(Data) +void_add_module(Data + INTERNAL_DEPS Time +) diff --git a/src/Log/Field.cpp b/src/Log/Field.cpp index 475259e..e301c5b 100644 --- a/src/Log/Field.cpp +++ b/src/Log/Field.cpp @@ -25,6 +25,15 @@ namespace Void::Logging m_count = fields.size(); } + FieldScope::FieldScope( + std::vector> fields) + { + m_count = fields.size(); + for (auto& [k, v] : fields) { + t_fields.emplace_back(std::move(k), std::move(v)); + } + } + FieldScope::~FieldScope() noexcept { if (!m_active) { diff --git a/src/Log/Formatter.cpp b/src/Log/Formatter.cpp index 0b5790f..e48d9e3 100644 --- a/src/Log/Formatter.cpp +++ b/src/Log/Formatter.cpp @@ -394,9 +394,14 @@ namespace Void::Logging if (!entry.fields.empty()) { auto fobj = Json::object(); for (const auto& [k, v] : entry.fields) { + if (!m_fields.allows(k)) { + continue; + } fobj.as_object().emplace_back(k, Json::Value{v}); } - o.emplace_back("fields", std::move(fobj)); + if (!fobj.as_object().empty()) { + o.emplace_back("fields", std::move(fobj)); + } } o.emplace_back("message", Json::Value{entry.message}); if (auto file = FormatDetail::file_basename(entry); !file.empty()) { @@ -440,6 +445,9 @@ namespace Void::Logging out += crumb; } for (const auto& [k, v] : entry.fields) { + if (!m_fields.allows(k)) { + continue; + } out += ' '; out += k; out += '='; diff --git a/src/Log/FromConfig.cpp b/src/Log/FromConfig.cpp index c773f80..605bf8b 100644 --- a/src/Log/FromConfig.cpp +++ b/src/Log/FromConfig.cpp @@ -101,13 +101,23 @@ namespace Void::Logging return std::nullopt; } + // Field allow/deny lists for the structured (json/logfmt) sinks, from + // the per-sink keys `fields.include` / `fields.exclude` (comma lists). + FieldFilter make_field_filter(const Configuration::Config& cfg) + { + FieldFilter f; + f.include = split_list(cfg.get_or("fields.include", "")); + f.exclude = split_list(cfg.get_or("fields.exclude", "")); + return f; + } + std::shared_ptr make_formatter(const Configuration::Config& cfg) { const auto format = cfg.get_or("format", "default"); if (format == "pattern") { - auto fmt = std::make_shared( - std::string{cfg.get_or( + auto fmt = + std::make_shared(std::string{cfg.get_or( "pattern", "{time} [{level}] {scopes}{message}")}); if (cfg.get_or_as("color", false)) { fmt->set_color_policy(ColorPolicy::defaults()); @@ -115,10 +125,14 @@ namespace Void::Logging return fmt; } if (format == "json") { - return std::make_shared(); + auto fmt = std::make_shared(); + fmt->set_field_filter(make_field_filter(cfg)); + return fmt; } if (format == "logfmt") { - return std::make_shared(); + auto fmt = std::make_shared(); + fmt->set_field_filter(make_field_filter(cfg)); + return fmt; } return nullptr; // "default": per-sink built-in rendering } @@ -214,8 +228,7 @@ namespace Void::Logging "split.dir"); } SplitFileLogger::Options opt; - opt.combined = - sub.get_or_as("split.combined", true); + opt.combined = sub.get_or_as("split.combined", true); opt.max_bytes = sub.get_or_as("split.max_kb", 1024) * 1024; opt.max_files = @@ -223,8 +236,8 @@ namespace Void::Logging opt.mode = dispatch.mode; opt.capacity = dispatch.capacity; opt.policy = dispatch.policy; - auto sink = SplitFileLogger::open( - std::filesystem::path{dir}, opt); + auto sink = + SplitFileLogger::open(std::filesystem::path{dir}, opt); if (!sink.has_value()) { return Void::Result::fail(std::move(sink).error()); } @@ -241,15 +254,14 @@ namespace Void::Logging } HistoryLogger::Options opt; opt.max_bytes = - sub.get_or_as("history.max_kb", 8192) * - 1024; + sub.get_or_as("history.max_kb", 8192) * 1024; opt.max_files = sub.get_or_as("history.max_files", 10); opt.mode = dispatch.mode; opt.capacity = dispatch.capacity; opt.policy = dispatch.policy; - auto sink = HistoryLogger::open( - std::filesystem::path{path}, opt); + auto sink = + HistoryLogger::open(std::filesystem::path{path}, opt); if (!sink.has_value()) { return Void::Result::fail(std::move(sink).error()); } diff --git a/src/Resilience/module.cmake b/src/Resilience/module.cmake new file mode 100644 index 0000000..a106c65 --- /dev/null +++ b/src/Resilience/module.cmake @@ -0,0 +1 @@ +void_add_module(Resilience) diff --git a/src/System/Process.cpp b/src/System/Process.cpp index b19b303..c9c240b 100644 --- a/src/System/Process.cpp +++ b/src/System/Process.cpp @@ -12,16 +12,25 @@ namespace Void::Process std::vector, std::string_view, std::chrono::milliseconds) + { + return Void::Result::fail("Process::run: not implemented on Windows"); + } + + Void::Result::Result + run_streaming(const std::filesystem::path&, + std::vector, + const StreamCallbacks&, + std::string_view, + std::chrono::milliseconds) { return Void::Result::fail( - "Process::run: not implemented on Windows"); + "Process::run_streaming: not implemented on Windows"); } Void::Result::Result shell(std::string_view, std::chrono::milliseconds) { - return Void::Result::fail( - "Process::shell: not implemented on Windows"); + return Void::Result::fail("Process::shell: not implemented on Windows"); } } // namespace Void::Process @@ -40,210 +49,272 @@ namespace Void::Process namespace Void::Process { -namespace -{ - // Read into buf until EAGAIN (no more data right now) or EOF. - // Returns true on EOF, false on EAGAIN. - bool drain(int fd, std::string& buf) + namespace { - char tmp[4096]; - for (;;) { - ssize_t n = ::read(fd, tmp, sizeof(tmp)); - if (n > 0) { - buf.append(tmp, static_cast(n)); - } else if (n == 0) { - return true; // EOF - } else { - if (errno == EINTR) { - continue; + // Read into buf until EAGAIN (no more data right now) or EOF. + // Returns true on EOF, false on EAGAIN. + bool drain(int fd, std::string& buf) + { + char tmp[4096]; + for (;;) { + ssize_t n = ::read(fd, tmp, sizeof(tmp)); + if (n > 0) { + buf.append(tmp, static_cast(n)); + } else if (n == 0) { + return true; // EOF + } else { + if (errno == EINTR) { + continue; + } + // EAGAIN / EWOULDBLOCK: no data right now + return false; } - // EAGAIN / EWOULDBLOCK: no data right now - return false; } } - } - void set_nonblock(int fd) - { - int flags = ::fcntl(fd, F_GETFL, 0); - if (flags >= 0) { - ::fcntl(fd, F_SETFL, flags | O_NONBLOCK); + void set_nonblock(int fd) + { + int flags = ::fcntl(fd, F_GETFL, 0); + if (flags >= 0) { + ::fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } } - } - // Close an fd if it is >= 0, then set it to -1. - void safe_close(int& fd) - { - if (fd >= 0) { - ::close(fd); - fd = -1; + // Close an fd if it is >= 0, then set it to -1. + void safe_close(int& fd) + { + if (fd >= 0) { + ::close(fd); + fd = -1; + } } - } -} // namespace -Void::Result::Result - run(const std::filesystem::path& executable, - std::vector args, - std::string_view stdin_data, + // Emit newly-completed lines from `buf` (from offset `off`), advancing + // `off`. When `flush` is set, any trailing partial line is emitted too. + void emit_lines(const std::string& buf, std::size_t& off, + const std::function& fn, + bool flush) + { + if (!fn) { + off = buf.size(); + return; + } + std::size_t nl; + while ((nl = buf.find('\n', off)) != std::string::npos) { + std::size_t len = nl - off; + if (len > 0 && buf[off + len - 1] == '\r') { + --len; // strip CR of a CRLF + } + fn(std::string_view{buf.data() + off, len}); + off = nl + 1; + } + if (flush && off < buf.size()) { + fn(std::string_view{buf.data() + off, buf.size() - off}); + off = buf.size(); + } + } + } // namespace + + namespace + { + Void::Result::Result + run_impl(const std::filesystem::path& executable, + std::vector args, std::string_view stdin_data, + std::chrono::milliseconds timeout, + const StreamCallbacks* cb) + { + // [0] = read end, [1] = write end + int stdin_pipe[2] = {-1, -1}; + int stdout_pipe[2] = {-1, -1}; + int stderr_pipe[2] = {-1, -1}; + + if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 || + ::pipe(stderr_pipe) != 0) { + safe_close(stdin_pipe[0]); + safe_close(stdin_pipe[1]); + safe_close(stdout_pipe[0]); + safe_close(stdout_pipe[1]); + safe_close(stderr_pipe[0]); + safe_close(stderr_pipe[1]); + return Void::Result::fail(std::format( + "Process::run: pipe() failed: {}", std::strerror(errno))); + } + + Void::Log::debug("Process", "run: '{}'", executable.string()); + + std::vector argv; + argv.push_back(executable.c_str()); + for (const auto& a : args) { + argv.push_back(a.c_str()); + } + argv.push_back(nullptr); + + pid_t pid = ::fork(); + if (pid < 0) { + safe_close(stdin_pipe[0]); + safe_close(stdin_pipe[1]); + safe_close(stdout_pipe[0]); + safe_close(stdout_pipe[1]); + safe_close(stderr_pipe[0]); + safe_close(stderr_pipe[1]); + return Void::Result::fail(std::format( + "Process::run: fork() failed: {}", std::strerror(errno))); + } + + if (pid == 0) { + // Child process + ::dup2(stdin_pipe[0], STDIN_FILENO); + ::dup2(stdout_pipe[1], STDOUT_FILENO); + ::dup2(stderr_pipe[1], STDERR_FILENO); + ::close(stdin_pipe[0]); + ::close(stdin_pipe[1]); + ::close(stdout_pipe[0]); + ::close(stdout_pipe[1]); + ::close(stderr_pipe[0]); + ::close(stderr_pipe[1]); + ::execvp( + executable.c_str(), + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + const_cast(argv.data())); + // execvp only returns on error; 127 is the POSIX convention + ::_exit(127); + } + + // Parent: close child-side ends + safe_close(stdin_pipe[0]); + safe_close(stdout_pipe[1]); + safe_close(stderr_pipe[1]); + + // Write stdin and close immediately so the child sees EOF + if (!stdin_data.empty()) { + const char* p = stdin_data.data(); + std::size_t remaining = stdin_data.size(); + while (remaining > 0) { + ssize_t n = ::write(stdin_pipe[1], p, remaining); + if (n < 0) { + if (errno == EINTR) { + continue; + } + break; // child likely closed stdin; ignore + } + p += static_cast(n); + remaining -= static_cast(n); + } + } + safe_close(stdin_pipe[1]); + + set_nonblock(stdout_pipe[0]); + set_nonblock(stderr_pipe[0]); + + Output output; + bool out_done = false; + bool err_done = false; + std::size_t out_emitted = 0; + std::size_t err_emitted = 0; + + const bool has_timeout = timeout.count() > 0; + const auto deadline = + std::chrono::steady_clock::now() + + (has_timeout ? timeout : std::chrono::milliseconds{30'000}); + + while (!out_done || !err_done) { + struct pollfd pfds[2]; + int nfds = 0; + if (!out_done) { + pfds[nfds++] = {stdout_pipe[0], POLLIN, 0}; + } + if (!err_done) { + pfds[nfds++] = {stderr_pipe[0], POLLIN, 0}; + } + + auto left_ms = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()) + .count(); + if (left_ms <= 0) { + ::kill(pid, SIGTERM); + break; + } + + int ret = ::poll(pfds, static_cast(nfds), + static_cast(left_ms)); + if (ret < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (ret == 0) { + // Wall-clock timeout expired + ::kill(pid, SIGTERM); + break; + } + + for (int i = 0; i < nfds; ++i) { + if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) { + continue; + } + const bool is_out = (pfds[i].fd == stdout_pipe[0]); + bool& done = is_out ? out_done : err_done; + std::string& buf = is_out ? output.out : output.err; + bool eof = drain(pfds[i].fd, buf); + if (cb) { + emit_lines(buf, is_out ? out_emitted : err_emitted, + is_out ? cb->on_stdout : cb->on_stderr, + /*flush=*/false); + } + // POLLHUP means the write end was closed; no more data will + // arrive + if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) { + done = true; + } + } + } + + if (cb) { + emit_lines(output.out, out_emitted, cb->on_stdout, + /*flush=*/true); + emit_lines(output.err, err_emitted, cb->on_stderr, + /*flush=*/true); + } + + safe_close(stdout_pipe[0]); + safe_close(stderr_pipe[0]); + + int status = 0; + ::waitpid(pid, &status, 0); + output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + + Void::Log::debug("Process", "run: '{}' exited {}", + executable.string(), output.exit_code); + + return Void::Result::ok(std::move(output)); + } + } // namespace + + Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args, std::string_view stdin_data, + std::chrono::milliseconds timeout) + { + return run_impl(executable, std::move(args), stdin_data, timeout, + nullptr); + } + + Void::Result::Result run_streaming( + const std::filesystem::path& executable, std::vector args, + const StreamCallbacks& callbacks, std::string_view stdin_data, std::chrono::milliseconds timeout) -{ - // [0] = read end, [1] = write end - int stdin_pipe[2] = {-1, -1}; - int stdout_pipe[2] = {-1, -1}; - int stderr_pipe[2] = {-1, -1}; - - if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 || - ::pipe(stderr_pipe) != 0) { - safe_close(stdin_pipe[0]); - safe_close(stdin_pipe[1]); - safe_close(stdout_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[0]); - safe_close(stderr_pipe[1]); - return Void::Result::fail(std::format("Process::run: pipe() failed: {}", - std::strerror(errno))); + { + return run_impl(executable, std::move(args), stdin_data, timeout, + &callbacks); } - Void::Log::debug("Process", "run: '{}'", executable.string()); - - std::vector argv; - argv.push_back(executable.c_str()); - for (const auto& a : args) { - argv.push_back(a.c_str()); + Void::Result::Result + shell(std::string_view command, std::chrono::milliseconds timeout) + { + return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); } - argv.push_back(nullptr); - - pid_t pid = ::fork(); - if (pid < 0) { - safe_close(stdin_pipe[0]); - safe_close(stdin_pipe[1]); - safe_close(stdout_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[0]); - safe_close(stderr_pipe[1]); - return Void::Result::fail(std::format("Process::run: fork() failed: {}", - std::strerror(errno))); - } - - if (pid == 0) { - // Child process - ::dup2(stdin_pipe[0], STDIN_FILENO); - ::dup2(stdout_pipe[1], STDOUT_FILENO); - ::dup2(stderr_pipe[1], STDERR_FILENO); - ::close(stdin_pipe[0]); - ::close(stdin_pipe[1]); - ::close(stdout_pipe[0]); - ::close(stdout_pipe[1]); - ::close(stderr_pipe[0]); - ::close(stderr_pipe[1]); - ::execvp(executable.c_str(), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - const_cast(argv.data())); - // execvp only returns on error; 127 is the POSIX convention - ::_exit(127); - } - - // Parent: close child-side ends - safe_close(stdin_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[1]); - - // Write stdin and close immediately so the child sees EOF - if (!stdin_data.empty()) { - const char* p = stdin_data.data(); - std::size_t remaining = stdin_data.size(); - while (remaining > 0) { - ssize_t n = ::write(stdin_pipe[1], p, remaining); - if (n < 0) { - if (errno == EINTR) { - continue; - } - break; // child likely closed stdin; ignore - } - p += static_cast(n); - remaining -= static_cast(n); - } - } - safe_close(stdin_pipe[1]); - - set_nonblock(stdout_pipe[0]); - set_nonblock(stderr_pipe[0]); - - Output output; - bool out_done = false; - bool err_done = false; - - const bool has_timeout = timeout.count() > 0; - const auto deadline = - std::chrono::steady_clock::now() + - (has_timeout ? timeout : std::chrono::milliseconds{30'000}); - - while (!out_done || !err_done) { - struct pollfd pfds[2]; - int nfds = 0; - if (!out_done) { - pfds[nfds++] = {stdout_pipe[0], POLLIN, 0}; - } - if (!err_done) { - pfds[nfds++] = {stderr_pipe[0], POLLIN, 0}; - } - - auto left_ms = std::chrono::duration_cast( - deadline - std::chrono::steady_clock::now()) - .count(); - if (left_ms <= 0) { - ::kill(pid, SIGTERM); - break; - } - - int ret = ::poll(pfds, static_cast(nfds), - static_cast(left_ms)); - if (ret < 0) { - if (errno == EINTR) { - continue; - } - break; - } - if (ret == 0) { - // Wall-clock timeout expired - ::kill(pid, SIGTERM); - break; - } - - for (int i = 0; i < nfds; ++i) { - if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) { - continue; - } - bool& done = - (pfds[i].fd == stdout_pipe[0]) ? out_done : err_done; - std::string& buf = - (pfds[i].fd == stdout_pipe[0]) ? output.out : output.err; - bool eof = drain(pfds[i].fd, buf); - // POLLHUP means the write end was closed; no more data will arrive - if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) { - done = true; - } - } - } - - safe_close(stdout_pipe[0]); - safe_close(stderr_pipe[0]); - - int status = 0; - ::waitpid(pid, &status, 0); - output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; - - Void::Log::debug("Process", "run: '{}' exited {}", executable.string(), - output.exit_code); - - return Void::Result::ok(std::move(output)); -} - -Void::Result::Result - shell(std::string_view command, std::chrono::milliseconds timeout) -{ - return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); -} } // namespace Void::Process diff --git a/tests/internal/FsmServiceHotReload.cpp b/tests/internal/FsmServiceHotReload.cpp index 0de0471..ee88c51 100644 --- a/tests/internal/FsmServiceHotReload.cpp +++ b/tests/internal/FsmServiceHotReload.cpp @@ -17,7 +17,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; #if defined(VOID_SERVICE_V1_PATH) && defined(VOID_SERVICE_V2_PATH) && \ __has_include() @@ -44,7 +45,7 @@ namespace using Success = int; struct Work : State { - Task run() + Task run() { auto& svc = service(); const int total = svc.accumulate(1); diff --git a/tests/standalone/Async/EventBusAsync.cpp b/tests/standalone/Async/EventBusAsync.cpp new file mode 100644 index 0000000..a73e7d4 --- /dev/null +++ b/tests/standalone/Async/EventBusAsync.cpp @@ -0,0 +1,71 @@ +#include +#include +#include + +#include +#include + +namespace +{ + using Void::EventBus::EventBus; + using Void::EventBus::Mode; + using Void::Testing::Test; + + struct Tick { + int n = 0; + }; + + struct EventBusAsync : Void::Testing::Suite { + // Async handlers run on the bus worker, not the publisher thread. + Test handler_runs_off_publisher_thread() + { + EventBus bus{Mode::Async}; + std::atomic handler_thread{}; + bus.subscribe([&](const Tick&) { + handler_thread.store(std::this_thread::get_id()); + }); + bus.publish(Tick{1}); + bus.flush(); + Void::Testing::expect(handler_thread.load() != + std::this_thread::get_id()); + } + + // flush() guarantees every published event has been delivered. + Test flush_delivers_all_events() + { + EventBus bus{Mode::Async}; + std::atomic total{0}; + bus.subscribe([&](const Tick& t) { + total.fetch_add(t.n, std::memory_order_relaxed); + }); + for (int i = 1; i <= 50; ++i) { + bus.publish(Tick{i}); + } + bus.flush(); + Void::Testing::expect_eq(total.load(), 50 * 51 / 2); + } + + // Unsubscribing before publish means the handler never fires. + Test unsubscribe_before_publish_not_called() + { + EventBus bus{Mode::Async}; + std::atomic count{0}; + const auto id = bus.subscribe( + [&](const Tick&) { count.fetch_add(1); }); + bus.unsubscribe(id); + bus.publish(Tick{1}); + bus.flush(); + Void::Testing::expect_eq(count.load(), 0); + } + + // Sync mode (the default) still delivers inline within publish(). + Test sync_mode_delivers_inline() + { + EventBus bus; // Mode::Sync + int seen = 0; + bus.subscribe([&](const Tick& t) { seen = t.n; }); + bus.publish(Tick{7}); + Void::Testing::expect_eq(seen, 7); // no flush needed + } + }; +} // namespace diff --git a/tests/standalone/Async/ThreadPoolBackpressure.cpp b/tests/standalone/Async/ThreadPoolBackpressure.cpp new file mode 100644 index 0000000..07ac57f --- /dev/null +++ b/tests/standalone/Async/ThreadPoolBackpressure.cpp @@ -0,0 +1,70 @@ +#include +#include +#include + +#include +#include + +namespace +{ + using Void::Concurrency::ThreadPool; + using Void::Testing::Test; + + struct ThreadPoolBackpressure + : Void::Testing::Suite { + // Unbounded pool (the default) accepts everything and never + // rejects. + Test unbounded_default_accepts_all() + { + ThreadPool pool{2}; + std::atomic sum{0}; + for (int i = 0; i < 100; ++i) { + auto f = pool.try_submit([&sum] { + sum.fetch_add(1, std::memory_order_relaxed); + }); + Void::Testing::expect(f.has_value()); + f->wait(); + } + const auto s = pool.stats(); + Void::Testing::expect_eq(s.submitted, std::uint64_t{100}); + Void::Testing::expect_eq(s.completed, std::uint64_t{100}); + Void::Testing::expect_eq(s.rejected, std::uint64_t{0}); + Void::Testing::expect_eq(sum.load(), 100); + } + + // A bounded pool rejects try_submit once the queue is full. + Test bounded_pool_rejects_when_full() + { + ThreadPool pool{1, /*max_queue=*/2}; + std::atomic started{false}; + std::atomic release{false}; + + // Occupy the single worker so the queue can fill up. + auto blocker = pool.submit([&] { + started.store(true, std::memory_order_release); + while (!release.load(std::memory_order_acquire)) { + std::this_thread::yield(); + } + }); + while (!started.load(std::memory_order_acquire)) { + std::this_thread::yield(); + } + + auto a = pool.try_submit([] {}); // queue size 1 + auto b = pool.try_submit([] {}); // queue size 2 (== max) + auto c = pool.try_submit([] {}); // full -> rejected + Void::Testing::expect(a.has_value()); + Void::Testing::expect(b.has_value()); + Void::Testing::expect(!c.has_value()); + + release.store(true, std::memory_order_release); + blocker.wait(); + a->wait(); + b->wait(); + + const auto s = pool.stats(); + Void::Testing::expect(s.rejected >= 1); + Void::Testing::expect_eq(s.submitted, std::uint64_t{3}); + } + }; +} // namespace diff --git a/tests/standalone/Configuration/ArgparseReflect.cpp b/tests/standalone/Configuration/ArgparseReflect.cpp new file mode 100644 index 0000000..f7684f4 --- /dev/null +++ b/tests/standalone/Configuration/ArgparseReflect.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +#include +#include + +namespace arg = Void::Argparse; + +namespace +{ + struct Opts { + [[= arg::Short{ + 'v'}]][[= arg::Help{"verbose output"}]] bool verbose = false; + [[= arg::Help{"output path"}]] std::string out = "a.out"; + std::optional config; + [[= arg::Positional{}]] std::string input = ""; + }; +} // namespace + +// @tag reflection +Void::Testing::Test argparse_reflective_parse() +{ + const char* argv[] = {"prog", "-v", "--out=x.bin", "foo.txt"}; + const auto o = arg::parse(4, argv, "prog"); + Void::Testing::expect(o.has_value()); + Void::Testing::expect_eq(o->verbose, true); + Void::Testing::expect_eq(o->out, std::string{"x.bin"}); + Void::Testing::expect_eq(o->input, std::string{"foo.txt"}); + Void::Testing::expect(!o->config.has_value()); +} + +// @tag reflection +Void::Testing::Test argparse_reflective_defaults() +{ + const char* argv[] = {"prog", "bar.txt"}; + const auto o = arg::parse(2, argv, "prog"); + Void::Testing::expect(o.has_value()); + Void::Testing::expect_eq(o->verbose, false); // flag default + Void::Testing::expect_eq(o->out, std::string{"a.out"}); // option default + Void::Testing::expect_eq(o->input, std::string{"bar.txt"}); +} diff --git a/tests/standalone/Configuration/BindAnnotations.cpp b/tests/standalone/Configuration/BindAnnotations.cpp new file mode 100644 index 0000000..46714bc --- /dev/null +++ b/tests/standalone/Configuration/BindAnnotations.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include + +#include + +namespace C = Void::Configuration; + +namespace +{ + struct Settings { + [[= C::Key{"log_level"}]] std::string level = "info"; + [[= C::Required{}]] std::string host = ""; + int port = 8080; + }; +} // namespace + +// @tag reflection +Void::Testing::Test bind_key_override_and_values() +{ + C::Config cfg; + cfg.set("log_level", "debug"); // bound via Key override + cfg.set("host", "localhost"); + cfg.set("port", "9090"); + const auto r = C::bind(cfg); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->level, std::string{"debug"}); + Void::Testing::expect_eq(r->host, std::string{"localhost"}); + Void::Testing::expect_eq(r->port, 9090); +} + +// @tag reflection +Void::Testing::Test bind_keeps_defaults_when_absent() +{ + C::Config cfg; + cfg.set("host", "h"); // only the required key + const auto r = C::bind(cfg); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->level, std::string{"info"}); // default + Void::Testing::expect_eq(r->port, 8080); // default +} + +// @tag reflection +Void::Testing::Test bind_required_missing_fails() +{ + C::Config cfg; + cfg.set("log_level", "x"); // host (required) missing + const auto r = C::bind(cfg); + Void::Testing::expect(!r.has_value()); +} diff --git a/tests/standalone/Configuration/ByteSize.cpp b/tests/standalone/Configuration/ByteSize.cpp new file mode 100644 index 0000000..60e3d3f --- /dev/null +++ b/tests/standalone/Configuration/ByteSize.cpp @@ -0,0 +1,60 @@ +#include +#include +#include + +#include + +namespace +{ + using Void::Configuration::Config; + using Void::Testing::Test; + + struct ByteSize : Void::Testing::Suite { + Test si_units() + { + Config cfg; + cfg.set("a", "10KB"); + cfg.set("b", "2MB"); + cfg.set("c", "1GB"); + Void::Testing::expect_eq(cfg.get_as("a").value(), + std::uint64_t{10'000}); + Void::Testing::expect_eq(cfg.get_as("b").value(), + std::uint64_t{2'000'000}); + Void::Testing::expect_eq(cfg.get_as("c").value(), + std::uint64_t{1'000'000'000}); + } + + Test binary_units() + { + Config cfg; + cfg.set("a", "1KiB"); + cfg.set("b", "1GiB"); + Void::Testing::expect_eq(cfg.get_as("a").value(), + std::uint64_t{1024}); + Void::Testing::expect_eq(cfg.get_as("b").value(), + std::uint64_t{1024ull * 1024 * 1024}); + } + + Test bare_and_fractional() + { + Config cfg; + cfg.set("plain", "512"); + cfg.set("half", "1.5KB"); + cfg.set("bytes", "64B"); + Void::Testing::expect_eq( + cfg.get_as("plain").value(), std::size_t{512}); + Void::Testing::expect_eq( + cfg.get_as("half").value(), std::size_t{1500}); + Void::Testing::expect_eq( + cfg.get_as("bytes").value(), std::size_t{64}); + } + + Test invalid_unit_is_error() + { + Config cfg; + cfg.set("bad", "10ZZ"); + Void::Testing::expect( + !cfg.get_as("bad").has_value()); + } + }; +} // namespace diff --git a/tests/standalone/Containers/BufferPool.cpp b/tests/standalone/Containers/BufferPool.cpp new file mode 100644 index 0000000..d3a86e1 --- /dev/null +++ b/tests/standalone/Containers/BufferPool.cpp @@ -0,0 +1,86 @@ +#include +#include +#include + +#include + +namespace +{ + using Void::BufferPool::BufferPool; + using Void::Testing::Test; + + struct BufferPoolTests : Void::Testing::Suite { + // Logical size is the request; capacity rounds up to a power of + // two. + Test acquire_rounds_capacity_to_size_class() + { + BufferPool pool; + auto buf = pool.acquire(500); + Void::Testing::expect_eq(buf.size(), std::size_t{500}); + Void::Testing::expect_eq(buf.capacity(), std::size_t{512}); + } + + // A fresh request allocates; a same-class request after drop + // reuses. + Test reuses_storage_of_same_size_class() + { + BufferPool pool; + std::int16_t* first = nullptr; + { + auto buf = pool.acquire(500); + first = buf.data(); + } // returned to the pool here + Void::Testing::expect_eq(pool.stats().allocations, + std::uint64_t{1}); + Void::Testing::expect_eq(pool.stats().pooled, std::size_t{1}); + + auto buf2 = pool.acquire(300); // also class 512 + Void::Testing::expect_eq(pool.stats().reuses, std::uint64_t{1}); + Void::Testing::expect_eq(pool.stats().allocations, + std::uint64_t{1}); + // Same backing storage -> no reallocation. + Void::Testing::expect(buf2.data() == first); + Void::Testing::expect_eq(buf2.capacity(), std::size_t{512}); + } + + Test distinct_size_classes_use_distinct_buckets() + { + BufferPool pool; + { + auto a = pool.acquire(500); // class 512 + auto b = pool.acquire(1000); // class 1024 + Void::Testing::expect_eq(a.capacity(), std::size_t{512}); + Void::Testing::expect_eq(b.capacity(), std::size_t{1024}); + } + Void::Testing::expect_eq(pool.stats().allocations, + std::uint64_t{2}); + Void::Testing::expect_eq(pool.stats().pooled, std::size_t{2}); + } + + Test buffer_is_writable_and_iterable() + { + BufferPool pool; + auto buf = pool.acquire(4); + for (std::size_t i = 0; i < buf.size(); ++i) { + buf[i] = static_cast(i * i); + } + int sum = 0; + for (int v : buf) { + sum += v; + } + Void::Testing::expect_eq(sum, 0 + 1 + 4 + 9); + Void::Testing::expect_eq(buf.span().size(), std::size_t{4}); + } + + Test shrink_drops_pooled_storage() + { + BufferPool pool; + { + auto a = pool.acquire(10); + } + Void::Testing::expect_eq(pool.stats().pooled, std::size_t{1}); + pool.shrink(); + Void::Testing::expect_eq(pool.stats().pooled, std::size_t{0}); + } + }; +} // namespace diff --git a/tests/standalone/Containers/Cache.cpp b/tests/standalone/Containers/Cache.cpp new file mode 100644 index 0000000..7b74a1c --- /dev/null +++ b/tests/standalone/Containers/Cache.cpp @@ -0,0 +1,123 @@ +#include +#include +#include + +#include +#include +#include + +namespace +{ + using Void::Cache::Cache; + using Void::Cache::Policy; + using Void::Testing::Test; + using namespace std::chrono_literals; + using TP = std::chrono::steady_clock::time_point; + + // A manually-advanced clock for deterministic TTL tests. + struct ManualClock { + std::shared_ptr now = + std::make_shared(std::chrono::steady_clock::now()); + auto fn() const + { + auto p = now; + return [p] { return *p; }; + } + void advance(std::chrono::nanoseconds d) const { *now += d; } + }; + + struct CacheTests : Void::Testing::Suite { + // ── TTL ─────────────────────────────────────────────────── + Test ttl_expires_lazily() + { + ManualClock clk; + Cache c{4, Policy::LRU, 100ms, clk.fn()}; + c.put(1, "a"); + clk.advance(50ms); + Void::Testing::expect(c.get(1).has_value()); + clk.advance(60ms); // now 110ms > 100ms TTL + Void::Testing::expect(!c.get(1).has_value()); + Void::Testing::expect_eq(c.stats().expirations, + std::uint64_t{1}); + } + + Test per_entry_ttl_overrides_default() + { + ManualClock clk; + Cache c{4, Policy::LRU, 100ms, clk.fn()}; + c.put(1, 10, 10ms); // shorter than default + clk.advance(20ms); + Void::Testing::expect(!c.get(1).has_value()); + } + + Test sweep_purges_expired() + { + ManualClock clk; + Cache c{8, Policy::LRU, 10ms, clk.fn()}; + c.put(1, 1); + c.put(2, 2); + clk.advance(20ms); + Void::Testing::expect_eq(c.sweep(), std::size_t{2}); + Void::Testing::expect_eq(c.size(), std::size_t{0}); + } + + // ── eviction policies ───────────────────────────────────── + Test lru_evicts_least_recently_used() + { + Cache c{2, Policy::LRU}; + c.put(1, 1); + c.put(2, 2); + (void)c.get(1); // promote 1 + c.put(3, 3); // evicts 2 + Void::Testing::expect(c.contains(1)); + Void::Testing::expect(!c.contains(2)); + Void::Testing::expect(c.contains(3)); + } + + Test fifo_evicts_oldest_inserted() + { + Cache c{2, Policy::FIFO}; + c.put(1, 1); + c.put(2, 2); + (void)c.get(1); // does NOT promote under FIFO + c.put(3, 3); // evicts 1 (oldest inserted) + Void::Testing::expect(!c.contains(1)); + Void::Testing::expect(c.contains(2)); + Void::Testing::expect(c.contains(3)); + } + + Test lfu_evicts_least_frequently_used() + { + Cache c{2, Policy::LFU}; + c.put(1, 1); + c.put(2, 2); + (void)c.get(1); + (void)c.get(1); // 1 is hot + c.put(3, 3); // evicts 2 (lower frequency) + Void::Testing::expect(c.contains(1)); + Void::Testing::expect(!c.contains(2)); + Void::Testing::expect(c.contains(3)); + } + + // ── stats ───────────────────────────────────────────────── + Test stats_track_hits_and_misses() + { + Cache c{4}; + c.put(1, 1); + (void)c.get(1); // hit + (void)c.get(2); // miss + (void)c.get(1); // hit + const auto s = c.stats(); + Void::Testing::expect_eq(s.hits, std::uint64_t{2}); + Void::Testing::expect_eq(s.misses, std::uint64_t{1}); + } + + Test stats_track_evictions() + { + Cache c{1, Policy::LRU}; + c.put(1, 1); + c.put(2, 2); // evicts 1 + Void::Testing::expect_eq(c.stats().evictions, std::uint64_t{1}); + } + }; +} // namespace diff --git a/tests/standalone/Containers/Debug.cpp b/tests/standalone/Containers/Debug.cpp new file mode 100644 index 0000000..77aeba8 --- /dev/null +++ b/tests/standalone/Containers/Debug.cpp @@ -0,0 +1,33 @@ +#include +#include +#include + +#include +#include + +namespace +{ + struct P { + int x; + int y; + }; +} // namespace + +// @tag reflection +Void::Testing::Test debug_dump_reflects_struct_elements() +{ + std::vector

v{{1, 2}, {3, 4}}; + Void::Testing::expect_eq(Void::Containers::debug_dump(v), + std::string{"[P{x: 1, y: 2}, P{x: 3, y: 4}]"}); +} + +// @tag reflection +Void::Testing::Test debug_dump_handles_scalars() +{ + std::vector n{1, 2, 3}; + Void::Testing::expect_eq(Void::Containers::debug_dump(n), + std::string{"[1, 2, 3]"}); + std::vector empty; + Void::Testing::expect_eq(Void::Containers::debug_dump(empty), + std::string{"[]"}); +} diff --git a/tests/standalone/Core/Bits.cpp b/tests/standalone/Core/Bits.cpp index 2991bb9..e9a9190 100644 --- a/tests/standalone/Core/Bits.cpp +++ b/tests/standalone/Core/Bits.cpp @@ -1,138 +1,135 @@ #include #include -#include +#include #include -// ── popcount ────────────────────────────────────────────────────────────────── - -Void::Testing::Test popcount_zero() +namespace { - Void::Testing::expect_eq(Void::Bits::popcount(0u), 0); -} + using Void::Testing::Test; -Void::Testing::Test popcount_all_ones_u8() -{ - Void::Testing::expect_eq(Void::Bits::popcount(std::uint8_t{0xFF}), 8); -} + struct Bits : Void::Testing::Suite { + // ── popcount ────────────────────────────────────────────── + Test popcount_zero() + { + Void::Testing::expect_eq(Void::Bits::popcount(0u), 0); + } + Test popcount_all_ones_u8() + { + Void::Testing::expect_eq( + Void::Bits::popcount(std::uint8_t{0xFF}), 8); + } + Test popcount_u32() + { + Void::Testing::expect_eq( + Void::Bits::popcount(std::uint32_t{0x0F0F0F0F}), 16); + } -Void::Testing::Test popcount_u32() -{ - Void::Testing::expect_eq(Void::Bits::popcount(std::uint32_t{0x0F0F0F0F}), 16); -} + // ── test/set/clear/toggle ───────────────────────────────── + Test test_bit_set() + { + Void::Testing::expect( + Void::Bits::test_bit(std::uint8_t{0b00000100u}, 2)); + } + Test test_bit_clear() + { + Void::Testing::expect( + !Void::Bits::test_bit(std::uint8_t{0b00000100u}, 0)); + } + Test set_bit_works() + { + Void::Testing::expect_eq( + Void::Bits::set_bit(std::uint8_t{0u}, 3), + std::uint8_t{0b00001000u}); + } + Test clear_bit_works() + { + Void::Testing::expect_eq( + Void::Bits::clear_bit(std::uint8_t{0xFF}, 3), + std::uint8_t{0b11110111u}); + } + Test toggle_bit_works() + { + Void::Testing::expect_eq( + Void::Bits::toggle_bit(std::uint8_t{0u}, 5), + std::uint8_t{0b00100000u}); + } -// ── test/set/clear/toggle ──────────────────────────────────────────────────── + // ── extract / deposit ───────────────────────────────────── + Test extract_bits_works() + { + Void::Testing::expect_eq( + Void::Bits::extract_bits(std::uint8_t{0b10110100u}, 4, 4), + std::uint8_t{0b1011u}); + } + Test deposit_bits_works() + { + Void::Testing::expect_eq( + Void::Bits::deposit_bits(std::uint8_t{0u}, + std::uint8_t{0b1010u}, 4, 4), + std::uint8_t{0b10100000u}); + } -Void::Testing::Test test_bit_set() -{ - Void::Testing::expect(Void::Bits::test_bit(std::uint8_t{0b00000100u}, 2)); -} + // ── rotation ────────────────────────────────────────────── + Test rotl_8() + { + Void::Testing::expect_eq( + Void::Bits::rotl(std::uint8_t{0b10000001u}, 1), + std::uint8_t{0b00000011u}); + } + Test rotr_8() + { + Void::Testing::expect_eq( + Void::Bits::rotr(std::uint8_t{0b10000001u}, 1), + std::uint8_t{0b11000000u}); + } -Void::Testing::Test test_bit_clear() -{ - Void::Testing::expect(!Void::Bits::test_bit(std::uint8_t{0b00000100u}, 0)); -} + // ── pow2 helpers ────────────────────────────────────────── + Test has_single_bit() + { + Void::Testing::expect(Void::Bits::has_single_bit(64u)); + Void::Testing::expect(!Void::Bits::has_single_bit(63u)); + } + Test ceil_pow2_works() + { + Void::Testing::expect_eq(Void::Bits::ceil_pow2(5u), 8u); + Void::Testing::expect_eq(Void::Bits::ceil_pow2(8u), 8u); + } + Test floor_pow2_works() + { + Void::Testing::expect_eq(Void::Bits::floor_pow2(5u), 4u); + } -Void::Testing::Test set_bit_works() -{ - Void::Testing::expect_eq(Void::Bits::set_bit(std::uint8_t{0u}, 3), - std::uint8_t{0b00001000u}); -} + // ── align ───────────────────────────────────────────────── + Test align_up_works() + { + Void::Testing::expect_eq(Void::Bits::align_up(13u, 8u), 16u); + Void::Testing::expect_eq(Void::Bits::align_up(8u, 8u), 8u); + } + Test align_down_works() + { + Void::Testing::expect_eq(Void::Bits::align_down(13u, 8u), 8u); + } -Void::Testing::Test clear_bit_works() -{ - Void::Testing::expect_eq(Void::Bits::clear_bit(std::uint8_t{0xFF}, 3), - std::uint8_t{0b11110111u}); -} + // ── masks ───────────────────────────────────────────────── + Test low_mask_works() + { + Void::Testing::expect_eq(Void::Bits::low_mask(4), + std::uint8_t{0x0F}); + } + Test range_mask_works() + { + Void::Testing::expect_eq( + Void::Bits::range_mask(2, 5), + std::uint8_t{0b00111100u}); + } -Void::Testing::Test toggle_bit_works() -{ - Void::Testing::expect_eq(Void::Bits::toggle_bit(std::uint8_t{0u}, 5), - std::uint8_t{0b00100000u}); -} - -// ── extract / deposit ───────────────────────────────────────────────────────── - -Void::Testing::Test extract_bits_works() -{ - // bits 4-7 of 0b10110100 = 0b1011 - Void::Testing::expect_eq( - Void::Bits::extract_bits(std::uint8_t{0b10110100u}, 4, 4), - std::uint8_t{0b1011u}); -} - -Void::Testing::Test deposit_bits_works() -{ - // deposit 0b1010 into bits 4-7 of 0x00 - Void::Testing::expect_eq( - Void::Bits::deposit_bits(std::uint8_t{0u}, std::uint8_t{0b1010u}, 4, 4), - std::uint8_t{0b10100000u}); -} - -// ── rotation ───────────────────────────────────────────────────────────────── - -Void::Testing::Test rotl_8() -{ - Void::Testing::expect_eq(Void::Bits::rotl(std::uint8_t{0b10000001u}, 1), - std::uint8_t{0b00000011u}); -} - -Void::Testing::Test rotr_8() -{ - Void::Testing::expect_eq(Void::Bits::rotr(std::uint8_t{0b10000001u}, 1), - std::uint8_t{0b11000000u}); -} - -// ── pow2 helpers ────────────────────────────────────────────────────────────── - -Void::Testing::Test has_single_bit() -{ - Void::Testing::expect(Void::Bits::has_single_bit(64u)); - Void::Testing::expect(!Void::Bits::has_single_bit(63u)); -} - -Void::Testing::Test ceil_pow2_works() -{ - Void::Testing::expect_eq(Void::Bits::ceil_pow2(5u), 8u); - Void::Testing::expect_eq(Void::Bits::ceil_pow2(8u), 8u); -} - -Void::Testing::Test floor_pow2_works() -{ - Void::Testing::expect_eq(Void::Bits::floor_pow2(5u), 4u); -} - -// ── align ──────────────────────────────────────────────────────────────────── - -Void::Testing::Test align_up_works() -{ - Void::Testing::expect_eq(Void::Bits::align_up(13u, 8u), 16u); - Void::Testing::expect_eq(Void::Bits::align_up(8u, 8u), 8u); -} - -Void::Testing::Test align_down_works() -{ - Void::Testing::expect_eq(Void::Bits::align_down(13u, 8u), 8u); -} - -// ── masks ──────────────────────────────────────────────────────────────────── - -Void::Testing::Test low_mask_works() -{ - Void::Testing::expect_eq(Void::Bits::low_mask(4), - std::uint8_t{0x0F}); -} - -Void::Testing::Test range_mask_works() -{ - Void::Testing::expect_eq(Void::Bits::range_mask(2, 5), - std::uint8_t{0b00111100u}); -} - -// ── byteswap / endian ──────────────────────────────────────────────────────── - -Void::Testing::Test byteswap_u32() -{ - Void::Testing::expect_eq(Void::Bits::byteswap(std::uint32_t{0x12345678u}), - std::uint32_t{0x78563412u}); -} + // ── byteswap / endian ───────────────────────────────────── + Test byteswap_u32() + { + Void::Testing::expect_eq( + Void::Bits::byteswap(std::uint32_t{0x12345678u}), + std::uint32_t{0x78563412u}); + } + }; +} // namespace diff --git a/tests/standalone/Core/FlagsReflect.cpp b/tests/standalone/Core/FlagsReflect.cpp new file mode 100644 index 0000000..810270d --- /dev/null +++ b/tests/standalone/Core/FlagsReflect.cpp @@ -0,0 +1,32 @@ +#include +#include +#include + +#include + +namespace +{ + enum class Perm : unsigned { Read = 1, Write = 2, Exec = 4 }; +} // namespace + +// @tag reflection +Void::Testing::Test flags_to_string_lists_set_names() +{ + const auto f = Void::Flags::Flags{Perm::Read} | Perm::Exec; + Void::Testing::expect_eq(Void::Flags::to_string(f), + std::string{"Read|Exec"}); + Void::Testing::expect_eq(Void::Flags::to_string(Void::Flags::Flags{}), + std::string{}); +} + +// @tag reflection +Void::Testing::Test flags_parse_names() +{ + const auto f = Void::Flags::parse("Read|Write"); + Void::Testing::expect(f.test(Perm::Read)); + Void::Testing::expect(f.test(Perm::Write)); + Void::Testing::expect(!f.test(Perm::Exec)); + // unknown names ignored + const auto g = Void::Flags::parse("Exec|Nope"); + Void::Testing::expect(g.test(Perm::Exec) && !g.test(Perm::Read)); +} diff --git a/tests/standalone/Core/Meta.cpp b/tests/standalone/Core/Meta.cpp new file mode 100644 index 0000000..239320b --- /dev/null +++ b/tests/standalone/Core/Meta.cpp @@ -0,0 +1,98 @@ +#include +#include +#include + +#include + +namespace M = Void::Meta; + +namespace +{ + struct Point { + int x = 1; + int y = 2; + }; + struct Nest { + Point p; + std::string tag = "z"; + }; + enum class Color { Red, Green, Blue }; +} // namespace + +Void::Testing::Test meta_field_walk() +{ + Void::Testing::expect_eq(M::field_count(), std::size_t{2}); + const auto names = M::field_names(); + Void::Testing::expect_eq(names.size(), std::size_t{2}); + Void::Testing::expect(names[0] == "x" && names[1] == "y"); + + Point p{3, 4}; + int sum = 0; + M::for_each_field(p, [&](std::string_view, auto& f) { sum += f; }); + Void::Testing::expect_eq(sum, 7); + + // mutate through for_each_field + M::for_each_field(p, [](std::string_view, auto& f) { f += 1; }); + Void::Testing::expect(p.x == 4 && p.y == 5); +} + +Void::Testing::Test meta_equal_compare_hash() +{ + Point a{3, 4}; + Point b{3, 4}; + Point c{3, 5}; + Void::Testing::expect(M::equal(a, b)); + Void::Testing::expect(!M::equal(a, c)); + Void::Testing::expect(M::compare(a, c) == std::strong_ordering::less); + Void::Testing::expect(M::compare(a, b) == std::strong_ordering::equal); + Void::Testing::expect_eq(M::hash(a), M::hash(b)); + Void::Testing::expect(M::hash(a) != M::hash(c)); +} + +Void::Testing::Test meta_repr_nested() +{ + Point p{5, 6}; + Void::Testing::expect_eq(M::repr(p), std::string{"Point{x: 5, y: 6}"}); + Nest n{Point{1, 2}, "hi"}; + Void::Testing::expect_eq( + M::repr(n), std::string{"Nest{p: Point{x: 1, y: 2}, tag: hi}"}); +} + +Void::Testing::Test meta_enum_utilities() +{ + Void::Testing::expect_eq(M::enum_count, std::size_t{3}); + constexpr auto vals = M::enum_values(); + Void::Testing::expect(vals[0] == Color::Red && vals[2] == Color::Blue); + const auto entries = M::enum_entries(); + Void::Testing::expect(entries[1].first == Color::Green && + entries[1].second == "Green"); + Void::Testing::expect(M::enum_name(Color::Blue) == "Blue"); + Void::Testing::expect(M::enum_parse("Green").value() == + Color::Green); + Void::Testing::expect(!M::enum_parse("Nope").has_value()); +} + +namespace +{ + struct Marker { + }; + struct Annotated { + [[= Marker{}]] int tagged = 0; + int plain = 0; + }; +} // namespace + +Void::Testing::Test meta_member_annotations() +{ + static constexpr auto members = M::members_v; + static_assert(M::has_annotation(members[0])); + static_assert(!M::has_annotation(members[1])); + Void::Testing::expect(M::has_annotation(members[0])); + Void::Testing::expect(!M::has_annotation(members[1])); +} + +Void::Testing::Test meta_type_name() +{ + Void::Testing::expect_eq(M::type_name(), std::string{"Point"}); + Void::Testing::expect_eq(M::type_name(), std::string{"Nest"}); +} diff --git a/tests/standalone/Data/CsvReflect.cpp b/tests/standalone/Data/CsvReflect.cpp new file mode 100644 index 0000000..2121e79 --- /dev/null +++ b/tests/standalone/Data/CsvReflect.cpp @@ -0,0 +1,40 @@ +#include +#include +#include + +#include + +namespace +{ + struct Rec { + std::string name = ""; + int age = 0; + double score = 0; + bool ok = false; + }; +} // namespace + +// @tag reflection +Void::Testing::Test csv_header_and_to_row() +{ + const auto h = Void::Csv::header_row(); + Void::Testing::expect_eq(h.size(), std::size_t{4}); + Void::Testing::expect(h[0] == "name" && h[1] == "age" && h[3] == "ok"); + + Rec r{"neo", 30, 9.5, true}; + const auto row = Void::Csv::to_row(r); + Void::Testing::expect(row[0] == "neo" && row[1] == "30" && + row[3] == "true"); +} + +// @tag reflection +Void::Testing::Test csv_from_row_round_trip() +{ + Rec r{"trin", 28, 7.25, false}; + const auto back = Void::Csv::from_row(Void::Csv::to_row(r)); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->name, std::string{"trin"}); + Void::Testing::expect_eq(back->age, 28); + Void::Testing::expect(back->score > 7.2 && back->score < 7.3); + Void::Testing::expect_eq(back->ok, false); +} diff --git a/tests/standalone/Data/JsonQuery.cpp b/tests/standalone/Data/JsonQuery.cpp new file mode 100644 index 0000000..b9294b8 --- /dev/null +++ b/tests/standalone/Data/JsonQuery.cpp @@ -0,0 +1,92 @@ +#include +#include +#include + +#include +#include + +namespace +{ + using Void::Testing::Test; + + const char* kDoc = R"({ + "name": "root", + "nested": { "a": { "b": [10, 20, 30] } }, + "weird/key": 7, + "flag": true + })"; + + struct JsonQuery : Void::Testing::Suite { + // ── JSON Pointer (at) ───────────────────────────────────── + Test pointer_walks_objects_and_arrays() + { + auto doc = Void::Json::parse(kDoc); + Void::Testing::expect(doc.has_value()); + const auto* v = doc->at("/nested/a/b/1"); + Void::Testing::expect(v != nullptr); + Void::Testing::expect_eq(v->as_number(), 20.0); + } + + Test empty_pointer_is_whole_document() + { + auto doc = Void::Json::parse(kDoc); + const auto* v = doc->at(""); + Void::Testing::expect(v == &*doc); + } + + Test missing_path_returns_null() + { + auto doc = Void::Json::parse(kDoc); + Void::Testing::expect(doc->at("/nested/missing") == nullptr); + Void::Testing::expect(doc->at("/nested/a/b/9") == nullptr); + Void::Testing::expect(doc->at("/flag/x") == nullptr); + } + + Test escaped_token() + { + auto doc = Void::Json::parse(kDoc); + const auto* v = doc->at("/weird~1key"); // ~1 -> '/' + Void::Testing::expect(v != nullptr); + Void::Testing::expect_eq(v->as_number(), 7.0); + } + + // ── SAX streaming parse ─────────────────────────────────── + Test sax_fires_events_in_order() + { + std::vector events; + Void::Json::SaxHandler h; + h.on_object_begin = [&] { events.push_back("{"); }; + h.on_object_end = [&] { events.push_back("}"); }; + h.on_array_begin = [&] { events.push_back("["); }; + h.on_array_end = [&] { events.push_back("]"); }; + h.on_key = [&](std::string_view k) { + events.push_back("key:" + std::string{k}); + }; + h.on_number = [&](double d) { + events.push_back("num:" + std::to_string((int)d)); + }; + h.on_bool = [&](bool b) { + events.push_back(b ? "true" : "false"); + }; + h.on_string = [&](std::string_view s) { + events.push_back("str:" + std::string{s}); + }; + + auto err = + Void::Json::parse_sax(R"({"a":[1,2],"b":"x","c":true})", h); + Void::Testing::expect(!err.has_value()); + + const std::vector expected{ + "{", "key:a", "[", "num:1", "num:2", "]", + "key:b", "str:x", "key:c", "true", "}"}; + Void::Testing::expect(events == expected); + } + + Test sax_reports_malformed_input() + { + Void::Json::SaxHandler h; + auto err = Void::Json::parse_sax(R"({"a": })", h); + Void::Testing::expect(err.has_value()); + } + }; +} // namespace diff --git a/tests/standalone/Data/ReflectAnnotations.cpp b/tests/standalone/Data/ReflectAnnotations.cpp new file mode 100644 index 0000000..dde314c --- /dev/null +++ b/tests/standalone/Data/ReflectAnnotations.cpp @@ -0,0 +1,61 @@ +#include +#include +#include + +#include + +namespace J = Void::Json; + +namespace +{ + struct Address { + std::string city = "?"; + int zip = 0; + }; + struct User { + [[= J::Rename{"user_id"}]] int id = 0; + [[= J::Skip{}]] int cache = 99; + [[= J::Required{}]] std::string name = ""; + [[= J::Flatten{}]] Address addr{}; + }; +} // namespace + +// @tag reflection +Void::Testing::Test json_annotations_to_json() +{ + User u{7, 99, "neo", Address{"zion", 100}}; + const auto j = J::to_json(u); + Void::Testing::expect(j.find("user_id") != nullptr); // Rename + Void::Testing::expect_eq(j.find("user_id")->as_int(), std::int64_t{7}); + Void::Testing::expect(j.find("cache") == nullptr); // Skip + Void::Testing::expect(j.find("name") != nullptr); + // Flatten: Address keys appear at top level, "addr" does not. + Void::Testing::expect(j.find("city") != nullptr); + Void::Testing::expect_eq(j.find("city")->as_string(), std::string{"zion"}); + Void::Testing::expect(j.find("zip") != nullptr); + Void::Testing::expect(j.find("addr") == nullptr); +} + +// @tag reflection +Void::Testing::Test json_annotations_round_trip() +{ + User u{7, 99, "neo", Address{"zion", 100}}; + const auto j = J::to_json(u); + const auto back = J::from_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->id, 7); + Void::Testing::expect_eq(back->name, std::string{"neo"}); + Void::Testing::expect_eq(back->addr.city, std::string{"zion"}); + Void::Testing::expect_eq(back->addr.zip, 100); + Void::Testing::expect_eq(back->cache, 99); // Skip keeps default +} + +// @tag reflection +Void::Testing::Test json_required_missing_is_error() +{ + const auto j = J::parse(R"({"user_id":1,"city":"x","zip":2})"); + Void::Testing::expect(j.has_value()); + const auto r = J::from_json(*j); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect_eq(r.error().field, std::string{"name"}); +} diff --git a/tests/standalone/Data/ReflectChrono.cpp b/tests/standalone/Data/ReflectChrono.cpp new file mode 100644 index 0000000..0e55ff6 --- /dev/null +++ b/tests/standalone/Data/ReflectChrono.cpp @@ -0,0 +1,192 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef VOID_HAS_JSON_REFLECTION + +namespace +{ + using namespace std::chrono_literals; + using Void::Json::from_json; + using Void::Json::to_json; + using Void::Testing::Test; + + struct Circle { + double radius = 0; + }; + struct Square { + double side = 0; + }; + using Shape = std::variant; + + struct Sample { + std::string name; + std::chrono::milliseconds latency{0}; + std::chrono::seconds ttl{0}; + std::array rgb{0, 0, 0}; + std::map by_id; + std::optional deadline; + std::chrono::system_clock::time_point created{}; + }; + + struct ReflectChrono : Void::Testing::Suite { + // ── duration as a unit-suffixed string ──────────────────── + Test duration_emits_unit_string() + { + const Sample s{.latency = 250ms, .ttl = 30s}; + const auto j = to_json(s); + Void::Testing::expect_eq(j["latency"].as_string(), + std::string{"250ms"}); + Void::Testing::expect_eq(j["ttl"].as_string(), + std::string{"30s"}); + } + + Test duration_round_trips() + { + const Sample s{.name = "n", + .latency = 1500ms, + .ttl = 5s, + .rgb = {1, 2, 3}}; + const auto back = from_json(to_json(s)); + Void::Testing::expect(back.has_value()); + Void::Testing::expect(back->latency == 1500ms); + Void::Testing::expect(back->ttl == 5s); + } + + Test optional_duration_round_trips() + { + Sample s; + s.deadline = 750ms; + auto back = from_json(to_json(s)); + Void::Testing::expect(back.has_value()); + Void::Testing::expect(back->deadline.has_value()); + Void::Testing::expect(*back->deadline == 750ms); + + s.deadline.reset(); + back = from_json(to_json(s)); + Void::Testing::expect(back.has_value()); + Void::Testing::expect(!back->deadline.has_value()); + } + + Test invalid_duration_is_error() + { + auto j = Void::Json::object(); + j.as_object().emplace_back( + "latency", Void::Json::Value{std::string{"nonsense"}}); + const auto back = from_json(j); + Void::Testing::expect(!back.has_value()); + } + + // ── time_point as ms-since-epoch string ─────────────────── + Test time_point_emits_ms_string() + { + Sample s; + s.created = std::chrono::system_clock::time_point{ + std::chrono::milliseconds{1750000000123}}; + const auto j = to_json(s); + Void::Testing::expect_eq(j["created"].as_string(), + std::string{"1750000000123ms"}); + } + + Test time_point_round_trips() + { + Sample s; + s.created = std::chrono::system_clock::time_point{ + std::chrono::milliseconds{1750000000123}}; + const auto back = from_json(to_json(s)); + Void::Testing::expect(back.has_value()); + const auto ms = + std::chrono::duration_cast( + back->created.time_since_epoch()) + .count(); + Void::Testing::expect_eq(ms, + static_cast(1750000000123)); + } + + Test invalid_time_point_is_error() + { + auto j = Void::Json::object(); + j.as_object().emplace_back( + "created", Void::Json::Value{std::string{"nope"}}); + const auto back = from_json(j); + Void::Testing::expect(!back.has_value()); + } + + // ── std::array ──────────────────────────────────────────── + Test array_round_trips() + { + const Sample s{.rgb = {10, 20, 30}}; + const auto j = to_json(s); + Void::Testing::expect(j["rgb"].is_array()); + Void::Testing::expect_eq(j["rgb"].as_array().size(), + std::size_t{3}); + const auto back = from_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->rgb[2], 30); + } + + Test array_wrong_length_is_error() + { + auto arr = Void::Json::array(); + arr.as_array().push_back(Void::Json::Value{1.0}); + arr.as_array().push_back(Void::Json::Value{2.0}); + auto j = Void::Json::object(); + j.as_object().emplace_back("rgb", std::move(arr)); + const auto back = from_json(j); + Void::Testing::expect(!back.has_value()); + } + + // ── non-string-keyed map ────────────────────────────────── + Test int_keyed_map_round_trips() + { + Sample s; + s.by_id = {{1, "one"}, {2, "two"}}; + const auto j = to_json(s); + Void::Testing::expect(j["by_id"].is_array()); + const auto back = from_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->by_id.size(), std::size_t{2}); + Void::Testing::expect_eq(back->by_id.at(1), std::string{"one"}); + Void::Testing::expect_eq(back->by_id.at(2), std::string{"two"}); + } + + // ── std::variant (type-name tagged) ─────────────────────── + Test variant_round_trips_each_alternative() + { + const Shape c = Circle{2.0}; + const auto jc = to_json(c); + Void::Testing::expect_eq(jc["type"].as_string(), + std::string{"Circle"}); + const auto bc = from_json(jc); + Void::Testing::expect(bc.has_value()); + Void::Testing::expect(std::holds_alternative(*bc)); + Void::Testing::expect_eq(std::get(*bc).radius, 2.0); + + const Shape sq = Square{3.0}; + const auto bs = from_json(to_json(sq)); + Void::Testing::expect(bs.has_value()); + Void::Testing::expect(std::holds_alternative(*bs)); + Void::Testing::expect_eq(std::get(*bs).side, 3.0); + } + + Test variant_unknown_tag_is_error() + { + auto j = Void::Json::object(); + j.as_object().emplace_back( + "type", Void::Json::Value{std::string{"Triangle"}}); + j.as_object().emplace_back("value", Void::Json::object()); + const auto back = from_json(j); + Void::Testing::expect(!back.has_value()); + } + }; +} // namespace + +#endif // VOID_HAS_JSON_REFLECTION diff --git a/tests/standalone/Fsm/Basic.cpp b/tests/standalone/Fsm/Basic.cpp index 11e5f47..d6c6d15 100644 --- a/tests/standalone/Fsm/Basic.cpp +++ b/tests/standalone/Fsm/Basic.cpp @@ -7,7 +7,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace { @@ -21,33 +22,34 @@ namespace int count = 0; std::vector* log = nullptr; - struct Start : State { - Task run() - { - if (self().log) { - self().log->push_back("start"); - } - co_return next(); - } - }; + struct States { + struct Start : State { + Task start() + { + if (self().log) { + self().log->push_back("start"); + } + co_return next(); + } + }; - struct Work : State { - Task run() - { - auto& m = self(); - ++m.count; - if (m.log) { - m.log->push_back("work" + std::to_string(m.count)); - } - if (m.count >= 3) { - co_return succeed(m.count); - } - co_return next(); - } + struct Work : State { + Task run() + { + auto& m = self(); + ++m.count; + if (m.log) { + m.log->push_back("work" + + std::to_string(m.count)); + } + if (m.count >= 3) { + co_return succeed(m.count); + } + co_return next(); + } + }; }; - using States = Void::Fsm::States; - Counter() : Void::Fsm::Machine( MachineOptions{.own_worker = false}) @@ -62,12 +64,12 @@ namespace using Success = int; using Failure = Void::Fsm::FsmError; - struct Boom : State { - Task run() { co_return fail("kaboom"); } + struct States { + struct Boom : State { + Task run() { co_return fail("kaboom"); } + }; }; - using States = Void::Fsm::States; - Failing() : Void::Fsm::Machine( MachineOptions{.own_worker = false}) @@ -113,10 +115,11 @@ Void::Testing::Test fsm_pump_drives_to_completion() Void::Testing::Test fsm_void_result_succeeds() { struct Trivial : Void::Fsm::Machine { - struct Done : State { - Task run() { co_return succeed(); } + struct States { + struct Done : State { + Task run() { co_return succeed(); } + }; }; - using States = Void::Fsm::States; Trivial() : Void::Fsm::Machine( MachineOptions{.own_worker = false}) @@ -137,13 +140,13 @@ Void::Testing::Test fsm_dynamic_state_registration() bool express; struct Express : State { - Task run() { co_return succeed(99); } + Task run() { co_return succeed(99); } }; struct Normal : State { - Task run() { co_return succeed(1); } + Task run() { co_return succeed(1); } }; struct Start : State { - Task run() + Task run() { if (self().has_state()) { co_return next_dynamic(); diff --git a/tests/standalone/Fsm/Concurrency.cpp b/tests/standalone/Fsm/Concurrency.cpp index 94434af..d26d4f8 100644 --- a/tests/standalone/Fsm/Concurrency.cpp +++ b/tests/standalone/Fsm/Concurrency.cpp @@ -11,7 +11,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace { @@ -32,7 +33,7 @@ namespace long long target; struct Run : State { - Task run() + Task run() { auto& m = self(); while (m.total < m.target) { @@ -138,7 +139,7 @@ Void::Testing::Test fsm_resolves_service_through_context() using Success = int; struct Go : State { - Task run() + Task run() { co_return succeed(service().twice(21)); } diff --git a/tests/standalone/Fsm/Defer.cpp b/tests/standalone/Fsm/Defer.cpp index ab53edc..94ad2c5 100644 --- a/tests/standalone/Fsm/Defer.cpp +++ b/tests/standalone/Fsm/Defer.cpp @@ -3,15 +3,20 @@ #include #include +#include #include using Void::Coro::Task; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace Fsm = Void::Fsm; -// Phase-6 reactive DSL: deferred events (held + replayed after a transition), -// entry/exit actions (on.enter/on.exit), and internal transitions (handle an -// event without leaving the state). +// Imperative equivalents of the old reactive extras: +// - deferred events : an event a state does not await stays buffered in the +// typed mailbox and is consumed by a later state — defer +// is automatic, no declaration needed. +// - entry/exit actions: the first/last lines of run(). +// - internal transition: handle an event in a loop without leaving the state. namespace { @@ -20,8 +25,8 @@ namespace struct Done { }; - // Busy defers Click (held, not dropped) and runs enter/exit actions; on - // Done it transitions to Idle, which then handles the replayed Click. + // Busy awaits only Done; a Click posted meanwhile stays buffered (deferred) + // and is handled by Idle. enter/exit are the first/last lines of run(). class Flow : public Fsm::Machine { public: @@ -29,29 +34,29 @@ namespace using Success = int; std::vector log; - struct Busy : State { - void transitions(TransitionBuilder& on) - { - on.enter([](Flow& m) { m.log.push_back("enter"); }); - on.exit([](Flow& m) { m.log.push_back("exit"); }); - on.template defer(); - on.template event().template to(); - } + struct States { + struct Busy : State { + Task run() + { + auto& m = self(); + m.log.push_back("enter"); + co_await await_event(); // Click buffered + m.log.push_back("exit"); + co_return next(); + } + }; + struct Idle : State { + Task run() + { + co_await await_event(); // buffered Click + self().log.push_back("click"); + co_return next(); + } + }; + struct End : State { + Task run() { co_return succeed(1); } + }; }; - struct Idle : State { - void transitions(TransitionBuilder& on) - { - on.template event() - .action([](Flow& m, const Click&) { - m.log.push_back("click"); - }) - .template to(); - } - }; - struct End : State { - Task run() { co_return succeed(1); } - }; - using States = Fsm::States; }; } // namespace @@ -60,12 +65,12 @@ Void::Testing::Test deferred_event_replays_after_transition() { Flow fsm; fsm.start(); - fsm.send(Click{}); // deferred while in Busy (not dropped) - fsm.send(Done{}); // Busy -> Idle; the held Click is replayed -> End + fsm.send(Click{}); // not awaited in Busy → stays buffered (not dropped) + fsm.send(Done{}); // Busy -> Idle; Idle consumes the buffered Click -> End const auto outcome = fsm.wait(); Void::Testing::expect(outcome.has_value()); Void::Testing::expect_eq(*outcome, 1); - // enter/exit actions fired around Busy; the deferred Click was handled. + // enter/exit ran around Busy; the buffered Click was handled in Idle. const std::vector expected{"enter", "exit", "click"}; Void::Testing::expect(fsm.log == expected); } @@ -79,8 +84,8 @@ namespace struct Stop { }; - // Counter handles Tick internally (no exit/enter, no transition); Stop - // leaves with the accumulated count. + // Counter handles Tick internally (loop, no re-entry); Stop leaves with the + // accumulated count. class Counter : public Fsm::Machine { public: @@ -89,19 +94,28 @@ namespace int ticks = 0; int enters = 0; - struct Run : State { - void transitions(TransitionBuilder& on) - { - on.enter([](Counter& m) { ++m.enters; }); - on.template event().internal( - [](Counter& m, const Tick&) { ++m.ticks; }); - on.template event().template to(); - } + struct States { + struct Run : State { + Task run() + { + auto& m = self(); + ++m.enters; // entered exactly once + for (;;) { + auto ev = co_await await_any(); + if (std::holds_alternative(ev)) { + co_return next(); + } + ++m.ticks; // internal: handled, stay here + } + } + }; + struct Done : State { + Task run() + { + co_return succeed(self().ticks); + } + }; }; - struct Done : State { - Task run() { co_return succeed(self().ticks); } - }; - using States = Fsm::States; }; } // namespace diff --git a/tests/standalone/Fsm/Direct.cpp b/tests/standalone/Fsm/Direct.cpp index 8925a16..0f8664e 100644 --- a/tests/standalone/Fsm/Direct.cpp +++ b/tests/standalone/Fsm/Direct.cpp @@ -7,7 +7,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace Fsm = Void::Fsm; using namespace std::chrono_literals; @@ -28,17 +29,18 @@ namespace int total = 0; - struct Take : State { - Task run() - { - auto a = co_await await_event(); - self().total += a.n; - auto b = co_await await_event(); - self().total += b.n; - co_return succeed(self().total); - } + struct States { + struct Take : State { + Task run() + { + auto a = co_await await_event(); + self().total += a.n; + auto b = co_await await_event(); + self().total += b.n; + co_return succeed(self().total); + } + }; }; - using States = Fsm::States; }; } // namespace @@ -63,16 +65,17 @@ namespace using Success = int; - struct A : State { - Task run() { co_return goto_state(); } + struct States { + struct A : State { + Task run() { co_return goto_state(); } + }; + struct B : State { + Task run() { co_return succeed(1); } + }; + struct C : State { + Task run() { co_return succeed(3); } + }; }; - struct B : State { - Task run() { co_return succeed(1); } - }; - struct C : State { - Task run() { co_return succeed(3); } - }; - using States = Fsm::States; }; } // namespace @@ -98,17 +101,18 @@ namespace using Success = int; - struct Loop : State { - Task run() - { - co_await await_event(); - co_return next(); - } + struct States { + struct Loop : State { + Task run() + { + co_await await_event(); + co_return next(); + } + }; + struct Done : State { + Task run() { co_return succeed(99); } + }; }; - struct Done : State { - Task run() { co_return succeed(99); } - }; - using States = Fsm::States; explicit Jumper(MachineOptions o = {}) : Fsm::Machine(o) {} }; @@ -124,7 +128,7 @@ Void::Testing::Test jump_redirects_at_next_boundary() while (fsm.pump() > 0) { } // Loop -> next -> park again - fsm.jump(); // request a jump + fsm.jump(); // request a jump fsm.send(Tick{}); while (fsm.pump() > 0) { } // Loop finishes -> boundary applies the jump -> Done @@ -147,10 +151,14 @@ namespace int runs = 0; - struct Once : State { - Task run() { co_return succeed(++self().runs); } + struct States { + struct Once : State { + Task run() + { + co_return succeed(++self().runs); + } + }; }; - using States = Fsm::States; }; } // namespace @@ -173,13 +181,14 @@ namespace using Success = int; - struct A : State { - Task run() { co_return succeed(1); } - }; - struct B : State { - Task run() { co_return succeed(2); } - }; - using States = Fsm::States; // initial = A + struct States { + struct A : State { + Task run() { co_return succeed(1); } + }; + struct B : State { + Task run() { co_return succeed(2); } + }; + }; // initial = A }; } // namespace @@ -189,7 +198,7 @@ Void::Testing::Test restart_at_changes_initial_state() Pick fsm; const auto first = fsm.run_blocking(); Void::Testing::expect_eq(*first, 1); // A - fsm.restart_at(); + fsm.restart_at(); const auto second = fsm.wait(); Void::Testing::expect_eq(*second, 2); // B } @@ -204,32 +213,33 @@ namespace using Success = int; - struct A : State { - Task run() { co_return succeed(1); } + struct States { + struct A : State { + Task run() { co_return succeed(1); } + }; + struct B : State { + Task run() { co_return succeed(2); } + }; + struct C : State { + Task run() { co_return succeed(3); } + }; }; - struct B : State { - Task run() { co_return succeed(2); } - }; - struct C : State { - Task run() { co_return succeed(3); } - }; - // Not in States<> — added via replace<>. + // Not in States — added via replace<>. struct Extra : State { - Task run() { co_return succeed(7); } + Task run() { co_return succeed(7); } }; - using States = Fsm::States; }; } // namespace Void::Testing::Test remove_and_set_initial_before_start() { Mut fsm; - Void::Testing::expect(fsm.has_state()); - fsm.remove(); - Void::Testing::expect(!fsm.has_state()); + Void::Testing::expect(fsm.has_state()); + fsm.remove(); + Void::Testing::expect(!fsm.has_state()); Void::Testing::expect_eq(fsm.describe().size(), std::size_t{2}); - fsm.set_initial(); + fsm.set_initial(); const auto outcome = fsm.run_blocking(); Void::Testing::expect_eq(*outcome, 2); } @@ -237,8 +247,9 @@ Void::Testing::Test remove_and_set_initial_before_start() Void::Testing::Test replace_swaps_a_state_and_keeps_initial() { Mut fsm; - fsm.replace(); // A was initial -> Extra becomes initial - Void::Testing::expect(!fsm.has_state()); + // A was initial -> Extra becomes initial. + fsm.replace(); + Void::Testing::expect(!fsm.has_state()); Void::Testing::expect(fsm.has_state()); const auto outcome = fsm.run_blocking(); Void::Testing::expect_eq(*outcome, 7); @@ -257,14 +268,15 @@ namespace using Success = int; - struct W : State { - Task run() - { - co_await await_event(); - co_return succeed(5); - } + struct States { + struct W : State { + Task run() + { + co_await await_event(); + co_return succeed(5); + } + }; }; - using States = Fsm::States; }; } // namespace diff --git a/tests/standalone/Fsm/Entry.cpp b/tests/standalone/Fsm/Entry.cpp new file mode 100644 index 0000000..40e0f93 --- /dev/null +++ b/tests/standalone/Fsm/Entry.cpp @@ -0,0 +1,136 @@ +#include +#include +#include + +using Void::Coro::Task; +using Void::Fsm::ChildSuccess; +using Void::Fsm::State; +using Void::Fsm::StateKey; +namespace Fsm = Void::Fsm; + +// A state's entry is inferred by signature (a 0-arg member returning StateKey / +// Task). When several members match, one annotated +// `[[= Void::Fsm::entry]]` is preferred; otherwise the first-declared wins. A +// startup-data overload run(Cfg) is selected when the machine is launched with +// data, and the nullary entry otherwise. + +namespace +{ + // Two nullary entry candidates; the annotated one is chosen even though it + // is not declared first. + class Annotated : public Fsm::Machine + { + public: + + using Success = int; + struct States { + struct Pick : State { + Task first() // declared first + { + co_return succeed(1); + } + [[= Fsm::entry]] Task chosen() + { + co_return succeed(2); + } + }; + }; + }; + + // Two nullary entry candidates, none annotated → first-declared wins. + class FirstWins : public Fsm::Machine + { + public: + + using Success = int; + struct States { + struct Pick : State { + Task first() { co_return succeed(1); } + Task second() { co_return succeed(2); } + }; + }; + }; +} // namespace + +// @tag integration +Void::Testing::Test annotated_entry_beats_first_declared() +{ + Annotated fsm; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 2); // the [[= Fsm::entry]] member ran +} + +// @tag integration +Void::Testing::Test first_declared_entry_wins_without_annotation() +{ + FirstWins fsm; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 1); // first-declared ran +} + +// ── startup-data overload selection ───────────────────────────────────────── + +namespace +{ + // Begin has both a nullary entry and a startup-data overload. The right one + // is picked by whether the machine was launched with data. + class Seeded : public Fsm::Machine + { + public: + + using Success = int; + struct States { + struct Begin : State { + Task run() // no startup data + { + co_return succeed(0); + } + Task run(int seed) // with startup data + { + co_return succeed(seed); + } + }; + }; + }; + + class Launcher : public Fsm::Machine + { + public: + + using Success = int; + struct States { + struct Go : State { + Task run() + { + co_return startMachine(7); + } + }; + struct After : State { + Task ok(ChildSuccess s) + { + co_return succeed(s.as()); + } + }; + }; + }; +} // namespace + +// @tag integration +Void::Testing::Test startup_entry_used_when_launched_with_data() +{ + Launcher fsm; // Seeded launched via startMachine(7) + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 7); // run(int) selected +} + +// @tag integration +Void::Testing::Test nullary_entry_used_without_startup_data() +{ + Seeded fsm; // started normally, no startup data + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 0); // run() selected +} diff --git a/tests/standalone/Fsm/Events.cpp b/tests/standalone/Fsm/Events.cpp index 70185f5..83a96d7 100644 --- a/tests/standalone/Fsm/Events.cpp +++ b/tests/standalone/Fsm/Events.cpp @@ -9,7 +9,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace { @@ -30,7 +31,7 @@ namespace std::vector* order = nullptr; struct Waiting : State { - Task run() + Task run() { auto& m = self(); // Two typed mailboxes: pull whichever arrives. diff --git a/tests/standalone/Fsm/Hierarchy.cpp b/tests/standalone/Fsm/Hierarchy.cpp index 71eac19..ee15a5b 100644 --- a/tests/standalone/Fsm/Hierarchy.cpp +++ b/tests/standalone/Fsm/Hierarchy.cpp @@ -8,7 +8,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; // Composite sub-states: a parent state runs a child region (run_region) that // shares the parent's executor, event mailbox and services. The child's @@ -31,17 +32,18 @@ namespace using Success = std::string; using Failure = Void::Fsm::FsmError; - struct Waiting : State { - Task run() - { - auto ev = co_await await_any(); - if (std::holds_alternative(ev)) { - co_return fail("cancelled"); - } - co_return succeed(std::string{"ticked"}); - } + struct States { + struct Waiting : State { + Task run() + { + auto ev = co_await await_any(); + if (std::holds_alternative(ev)) { + co_return fail("cancelled"); + } + co_return succeed(std::string{"ticked"}); + } + }; }; - using States = Void::Fsm::States; explicit Work(MachineOptions opts = {}) : Void::Fsm::Machine(opts) @@ -57,23 +59,24 @@ namespace using Success = std::string; - struct Running : State { - Task run() - { - auto r = co_await run_region(); - if (r.has_value()) { - co_return succeed(*r); - } - co_return next(); - } + struct States { + struct Running : State { + Task run() + { + auto r = co_await run_region(); + if (r.has_value()) { + co_return succeed(*r); + } + co_return next(); + } + }; + struct Aborted : State { + Task run() + { + co_return succeed(std::string{"aborted"}); + } + }; }; - struct Aborted : State { - Task run() - { - co_return succeed(std::string{"aborted"}); - } - }; - using States = Void::Fsm::States; explicit Job(MachineOptions opts = {}) : Void::Fsm::Machine(opts) diff --git a/tests/standalone/Fsm/History.cpp b/tests/standalone/Fsm/History.cpp index ab38188..b489935 100644 --- a/tests/standalone/Fsm/History.cpp +++ b/tests/standalone/Fsm/History.cpp @@ -4,7 +4,8 @@ using Void::Coro::Task; using Void::Fsm::Resume; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace Fsm = Void::Fsm; // run_region(Resume::History) re-enters a region at the sub-state it last @@ -23,17 +24,18 @@ namespace using Success = int; - struct A : State { - Task run() - { - ++g_a_runs; - co_return next(); - } + struct States { + struct A : State { + Task run() + { + ++g_a_runs; + co_return next(); + } + }; + struct B : State { + Task run() { co_return succeed(2); } + }; }; - struct B : State { - Task run() { co_return succeed(2); } - }; - using States = Fsm::States; }; class Host : public Fsm::Machine @@ -42,16 +44,18 @@ namespace using Success = int; - struct Run : State { - Task run() - { - co_await run_region(); // Initial: A then B - co_await run_region( - Resume::History); // History: B only - co_return succeed(g_a_runs); - } + struct States { + struct Run : State { + Task run() + { + co_await run_region(); // Initial: A + // then B + co_await run_region( + Resume::History); // History: B only + co_return succeed(g_a_runs); + } + }; }; - using States = Fsm::States; }; } // namespace @@ -73,15 +77,16 @@ Void::Testing::Test initial_reentry_restarts_from_the_top() // Two plain (Initial) entries run A both times. struct H2 : Fsm::Machine

{ using Success = int; - struct Run : State { - Task run() - { - co_await run_region(); - co_await run_region(); // Initial again - co_return succeed(g_a_runs); - } + struct States { + struct Run : State { + Task run() + { + co_await run_region(); + co_await run_region(); // Initial again + co_return succeed(g_a_runs); + } + }; }; - using States = Fsm::States; }; H2 fsm; const auto outcome = fsm.run_blocking(); diff --git a/tests/standalone/Fsm/Lifecycle.cpp b/tests/standalone/Fsm/Lifecycle.cpp index d0a9921..fc3f6db 100644 --- a/tests/standalone/Fsm/Lifecycle.cpp +++ b/tests/standalone/Fsm/Lifecycle.cpp @@ -7,7 +7,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; using Void::Fsm::Transition; namespace @@ -21,44 +22,44 @@ namespace std::vector log; - struct A : State { - Task on_enter() override - { - self().log.push_back("enter A"); - co_return; - } - Task run() - { - self().log.push_back("run A"); - co_return next(); - } - Task on_exit() override - { - self().log.push_back("exit A"); - co_return; - } - }; + struct States { + struct A : State { + Task on_enter() override + { + self().log.push_back("enter A"); + co_return; + } + Task run() + { + self().log.push_back("run A"); + co_return next(); + } + Task on_exit() override + { + self().log.push_back("exit A"); + co_return; + } + }; - struct B : State { - Task on_enter() override - { - self().log.push_back("enter B"); - co_return; - } - Task run() - { - self().log.push_back("run B"); - co_return succeed(1); - } - Task on_exit() override - { - self().log.push_back("exit B"); - co_return; - } + struct B : State { + Task on_enter() override + { + self().log.push_back("enter B"); + co_return; + } + Task run() + { + self().log.push_back("run B"); + co_return succeed(1); + } + Task on_exit() override + { + self().log.push_back("exit B"); + co_return; + } + }; }; - using States = Void::Fsm::States; - Lifecycle() : Void::Fsm::Machine( MachineOptions{.own_worker = false}) @@ -109,11 +110,12 @@ Void::Testing::Test fsm_state_names_and_path() Void::Testing::Test fsm_state_without_run_fails() { struct NoRun : Void::Fsm::Machine { - struct Stuck : State { - Task on_enter() override { co_return; } - // no run() override + struct States { + struct Stuck : State { + Task on_enter() override { co_return; } + // no run() override + }; }; - using States = Void::Fsm::States; NoRun() : Void::Fsm::Machine(MachineOptions{.own_worker = false}) { diff --git a/tests/standalone/Fsm/Nesting.cpp b/tests/standalone/Fsm/Nesting.cpp index 731326b..9f7b4e5 100644 --- a/tests/standalone/Fsm/Nesting.cpp +++ b/tests/standalone/Fsm/Nesting.cpp @@ -6,7 +6,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace { @@ -20,7 +21,7 @@ namespace int seed; struct Compute : State { - Task run() + Task run() { auto& m = self(); co_return succeed(m.seed * 10); @@ -45,7 +46,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Boom : State { - Task run() { co_return fail("child boom"); } + Task run() { co_return fail("child boom"); } }; FailingChild() : Void::Fsm::Machine( @@ -64,7 +65,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Start : State { - Task run() + Task run() { auto a = co_await run_child(3); // 30 auto b = co_await run_child(4); // 40 @@ -91,7 +92,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Start : State { - Task run() + Task run() { auto r = co_await run_child(); if (!r.has_value()) { @@ -136,7 +137,7 @@ Void::Testing::Test fsm_nesting_with_worker_thread() using Success = int; struct Start : State { - Task run() + Task run() { auto a = co_await run_child(5); // 50 co_return succeed(a.value_or(-1)); diff --git a/tests/standalone/Fsm/Parallel.cpp b/tests/standalone/Fsm/Parallel.cpp index a492987..d0a5a1f 100644 --- a/tests/standalone/Fsm/Parallel.cpp +++ b/tests/standalone/Fsm/Parallel.cpp @@ -3,7 +3,8 @@ #include using Void::Coro::Task; -using Void::Fsm::Step; +using Void::Fsm::StateKey; +using Void::Fsm::State; namespace Fsm = Void::Fsm; // Orthogonal regions: run_parallel() runs both sub-machines concurrently @@ -22,14 +23,15 @@ namespace public: using Success = int; - struct W : State { - Task run() - { - co_await await_event(); - co_return succeed(1); - } + struct States { + struct W : State { + Task run() + { + co_await await_event(); + co_return succeed(1); + } + }; }; - using States = Fsm::States; }; class Right : public Fsm::Machine @@ -37,14 +39,15 @@ namespace public: using Success = int; - struct W : State { - Task run() - { - co_await await_event(); - co_return succeed(2); - } + struct States { + struct W : State { + Task run() + { + co_await await_event(); + co_return succeed(2); + } + }; }; - using States = Fsm::States; }; // Joins both children: their results sum to 3. @@ -53,15 +56,17 @@ namespace public: using Success = int; - struct Run : State { - Task run() - { - auto [a, b] = co_await run_parallel(); - co_return succeed((a.has_value() ? *a : 0) + - (b.has_value() ? *b : 0)); - } + struct States { + struct Run : State { + Task run() + { + auto [a, b] = + co_await run_parallel(); + co_return succeed((a.has_value() ? *a : 0) + + (b.has_value() ? *b : 0)); + } + }; }; - using States = Fsm::States; explicit Both(Fsm::MachineOptions o = {}) : Fsm::Machine(o) {} }; @@ -107,21 +112,25 @@ namespace public: using Success = int; - struct Run : State { - Task run() - { - auto v = co_await run_parallel_any(); - // index 1 == Right (value 2); index 0 == Left (value 1) - if (v.index() == 1 && std::get<1>(v).has_value()) { - co_return succeed(100 + *std::get<1>(v)); - } - if (v.index() == 0 && std::get<0>(v).has_value()) { - co_return succeed(*std::get<0>(v)); - } - co_return succeed(-1); - } + struct States { + struct Run : State { + Task run() + { + auto v = + co_await run_parallel_any(); + // index 1 == Right (2); index 0 == Left (1) + if (v.index() == 1 && + std::get<1>(v).has_value()) { + co_return succeed(100 + *std::get<1>(v)); + } + if (v.index() == 0 && + std::get<0>(v).has_value()) { + co_return succeed(*std::get<0>(v)); + } + co_return succeed(-1); + } + }; }; - using States = Fsm::States; explicit Race(Fsm::MachineOptions o = {}) : Fsm::Machine(o) {} }; diff --git a/tests/standalone/Fsm/Policies.cpp b/tests/standalone/Fsm/Policies.cpp index 51439cb..08251ef 100644 --- a/tests/standalone/Fsm/Policies.cpp +++ b/tests/standalone/Fsm/Policies.cpp @@ -4,11 +4,14 @@ #include #include +#include #include +#include using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; using Void::Fsm::Transition; using namespace std::chrono_literals; @@ -30,30 +33,30 @@ namespace int attempts = 0; int retries; // how many tries with_retry gets - struct Try : State { - Task run() - { - auto& m = self(); - const bool ok = co_await with_retry( - m.retries, 1ms, [&m]() -> Task { - ++m.attempts; - co_return m.attempts > m.fail_n; - }); - co_return next_or( - ok ? succeed(std::string{"ok"}) - : fail("exhausted")); - } - }; + struct States { + struct Try : State { + Task run() + { + auto& m = self(); + const bool ok = co_await with_retry( + m.retries, 1ms, [&m]() -> Task { + ++m.attempts; + co_return m.attempts > m.fail_n; + }); + co_return next_or( + ok ? succeed(std::string{"ok"}) + : fail("exhausted")); + } + }; - struct Fallback : State { - Task run() - { - co_return succeed(std::string{"fallback"}); - } + struct Fallback : State { + Task run() + { + co_return succeed(std::string{"fallback"}); + } + }; }; - using States = Void::Fsm::States; - explicit Flaky(int fails, int tries) : fail_n(fails), retries(tries) { } // own worker @@ -91,13 +94,14 @@ namespace using Success = int; - struct A : State { - Task run() { co_return next(); } + struct States { + struct A : State { + Task run() { co_return next(); } + }; + struct B : State { + Task run() { co_return succeed(1); } + }; }; - struct B : State { - Task run() { co_return succeed(1); } - }; - using States = Void::Fsm::States; Pipe() : Void::Fsm::Machine(MachineOptions{.own_worker = false}) { @@ -149,63 +153,59 @@ namespace struct Cancel { }; + // Imperative event handling: Idle awaits Go or Cancel and routes. class Flow : public Void::Fsm::Machine { public: using Success = int; - struct Idle : State { - void transitions(TransitionBuilder& on) - { - on.event() - .guard([](Flow&, const Go&) { return true; }) - .template to(); - on.event().template to(); - on.after(1h).template to(); - } + struct States { + struct Idle : State { + Task run() + { + auto ev = co_await await_any(); + co_return std::holds_alternative(ev) + ? next() + : next(); + } + }; + struct Active : State { + Task run() { co_return next(); } + }; + struct Done : State { + Task run() { co_return succeed(0); } + }; }; - struct Active : State { - Task run() { co_return next(); } - }; - struct Done : State { - Task run() { co_return succeed(0); } - }; - using States = Void::Fsm::States; Flow() {} }; } // namespace -Void::Testing::Test describe_lists_states_and_reactive_edges() +// describe() is node-level: behaviour (and therefore transitions) is chosen +// imperatively inside each state's entry, so edges are not statically knowable. +Void::Testing::Test describe_lists_states_node_level() { Flow fsm; const auto states = fsm.describe(); Void::Testing::expect_eq(states.size(), std::size_t{3}); - // Idle is reactive + initial, with Go/Cancel/timeout edges. - const auto& idle = states[0]; - Void::Testing::expect_eq(idle.name, std::string{"Idle"}); - Void::Testing::expect(idle.reactive); - Void::Testing::expect(idle.initial); - Void::Testing::expect_eq(idle.edges.size(), std::size_t{3}); - Void::Testing::expect_eq(idle.edges[0].event, std::string{"Go"}); - Void::Testing::expect_eq(idle.edges[0].target, std::string{"Active"}); - Void::Testing::expect(idle.edges[0].guarded); - Void::Testing::expect_eq(idle.edges[2].event, std::string{"(timeout)"}); - - // Active is imperative → no declarable edges. - Void::Testing::expect(!states[1].reactive); - Void::Testing::expect(states[1].edges.empty()); + // Registration order; Idle is the initial state. + Void::Testing::expect_eq(states[0].name, std::string{"Idle"}); + Void::Testing::expect(states[0].initial); + Void::Testing::expect_eq(states[1].name, std::string{"Active"}); + Void::Testing::expect(!states[1].initial); + Void::Testing::expect_eq(states[2].name, std::string{"Done"}); } -Void::Testing::Test to_mermaid_contains_edges() +Void::Testing::Test to_mermaid_lists_nodes_and_initial() { Flow fsm; const auto diagram = fsm.to_mermaid(); + std::cout << diagram << std::endl; Void::Testing::expect(diagram.find("stateDiagram-v2") != std::string::npos); Void::Testing::expect(diagram.find("[*] --> Idle") != std::string::npos); - Void::Testing::expect(diagram.find("Idle --> Active : Go [guard]") != - std::string::npos); - Void::Testing::expect(diagram.find("Idle --> Done : Cancel") != - std::string::npos); + // One node per registered state. + Void::Testing::expect(diagram.find("\n Idle\n") != std::string::npos); + Void::Testing::expect(diagram.find("\n Active\n") != std::string::npos); + Void::Testing::expect(diagram.find("\n Done\n") != std::string::npos); } diff --git a/tests/standalone/Fsm/Reactive.cpp b/tests/standalone/Fsm/Reactive.cpp index 014778e..af32c54 100644 --- a/tests/standalone/Fsm/Reactive.cpp +++ b/tests/standalone/Fsm/Reactive.cpp @@ -5,11 +5,13 @@ #include #include #include +#include #include using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; using namespace std::chrono_literals; namespace @@ -20,8 +22,9 @@ namespace struct Stop { }; - // A declarative machine: Idle reacts to events with guards/actions; on - // timeout it bails out. + // Imperative event handling: Idle loops, awaiting either Go or Stop. A Go + // only advances when positive (the guard, now a plain `if`); Stop leaves to + // Done. Internal handling = stay in the loop (no transition). class Gate : public Void::Fsm::Machine { public: @@ -32,42 +35,46 @@ namespace int total = 0; std::vector trace; - struct Idle : State { - void transitions(TransitionBuilder& on) - { - // Guarded: only positive amounts advance. - on.event() - .guard( - [](Gate&, const Go& g) { return g.amount > 0; }) - .action([](Gate& m, const Go& g) { - m.total += g.amount; - m.trace.push_back("go" + - std::to_string(g.amount)); - }) - .template to(); - on.event().template to(); - on.after(10s).fail("idle timeout"); - } - }; + struct States { + struct Idle : State { + Task run() + { + auto& m = self(); + for (;;) { + auto ev = co_await await_any(); + if (std::holds_alternative(ev)) { + co_return next(); + } + const Go g = std::get(ev); + if (g.amount > 0) { // guard + m.total += g.amount; + m.trace.push_back( + "go" + std::to_string(g.amount)); + } + } + } + }; - // Imperative terminal state: reports the accumulated total. - struct Done : State { - Task run() { co_return succeed(self().total); } + // Imperative terminal state: reports the accumulated total. + struct Done : State { + Task run() + { + co_return succeed(self().total); + } + }; }; - using States = Void::Fsm::States; - Gate() {} // own worker }; } // namespace -// Mixes a reactive (declarative, guarded) state with an imperative one. +// Imperative event loop with a guard and an accumulating action. Void::Testing::Test reactive_guard_and_action() { Gate fsm; fsm.start(); fsm.post(Go{5}); - fsm.post(Go{-1}); // blocked by guard, dropped + fsm.post(Go{-1}); // blocked by the guard, ignored fsm.post(Go{3}); fsm.post(Stop{}); // -> Done -> succeed(total) @@ -93,17 +100,18 @@ namespace using Success = std::string; - struct Waiting : State { - Task run() - { - auto w = co_await await_event_for(15ms); - if (w.has_value()) { - co_return succeed(std::string{"woken"}); - } - co_return succeed(std::string{"timed_out"}); - } + struct States { + struct Waiting : State { + Task run() + { + auto w = co_await await_event_for(15ms); + if (w.has_value()) { + co_return succeed(std::string{"woken"}); + } + co_return succeed(std::string{"timed_out"}); + } + }; }; - using States = Void::Fsm::States; Sleeper() {} // own worker }; } // namespace @@ -130,27 +138,29 @@ Void::Testing::Test await_event_for_receives_event() namespace { - // Reactive timeout transition (on.after().to<>). + // Timeout transition expressed imperatively (await_event_for → branch). class Deadline : public Void::Fsm::Machine { public: using Success = int; - struct Pending : State { - void transitions(TransitionBuilder& on) - { - on.event().template to(); - on.after(15ms).template to(); - } + struct States { + struct Pending : State { + Task run() + { + auto w = co_await await_event_for(15ms); + co_return w.has_value() ? next() + : next(); + } + }; + struct Resolved : State { + Task run() { co_return succeed(1); } + }; + struct Expired : State { + Task run() { co_return succeed(2); } + }; }; - struct Resolved : State { - Task run() { co_return succeed(1); } - }; - struct Expired : State { - Task run() { co_return succeed(2); } - }; - using States = Void::Fsm::States; Deadline() {} }; } // namespace diff --git a/tests/standalone/Fsm/Serialize.cpp b/tests/standalone/Fsm/Serialize.cpp index 84f77c1..e13ff06 100644 --- a/tests/standalone/Fsm/Serialize.cpp +++ b/tests/standalone/Fsm/Serialize.cpp @@ -7,7 +7,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace { @@ -26,14 +27,14 @@ namespace Data data; struct Ingest : State { - Task run() + Task run() { co_await await_event(); // park here co_return next(); } }; struct Process : State { - Task run() + Task run() { auto& m = self(); m.data.processed += 1; diff --git a/tests/standalone/Fsm/Split.cpp b/tests/standalone/Fsm/Split.cpp new file mode 100644 index 0000000..c6e47f5 --- /dev/null +++ b/tests/standalone/Fsm/Split.cpp @@ -0,0 +1,99 @@ +#include +#include +#include + +#include +#include + +using Void::Coro::Task; +using Void::Fsm::State; +using Void::Fsm::StateKey; +namespace Fsm = Void::Fsm; + +// Demonstrates the header/source split the module is designed for: the machine +// declares its states as forward declarations inside `struct States { … };` +// (this block is what would live in a header), and the states are *realised* +// out-of-line at namespace scope (this is what would live in a .cpp). The base +// auto-registers them by reflecting `States`; no behaviour is written outside a +// state. The constructor is also defined out-of-line, after the realisations, +// so the states are complete when the base registers them. + +namespace +{ + struct Charge { + int amount; + }; + struct Dispense { + }; + + // ── "header" part ────────────────────────────────────────────────────── + class Vending : public Fsm::Machine + { + public: + + using Success = int; // dispensed credit + + int credit = 0; + + struct States { + struct Idle; // first => initial + struct Collecting; + struct Done; + }; + + Vending(); // realised below, after the states + }; +} // namespace + +// ── "source" part: state realisations (namespace scope) ───────────────────── +struct Vending::States::Idle : Vending::State { + Task run() + { + co_await await_event(); // first coin -> start collecting + co_return next(); + } +}; + +struct Vending::States::Collecting : Vending::State { + Task run() + { + auto& m = self(); + for (;;) { + auto ev = co_await await_any(); + if (std::holds_alternative(ev)) { + co_return next(); + } + m.credit += std::get(ev).amount; + } + } +}; + +struct Vending::States::Done : Vending::State { + Task run() { co_return succeed(self().credit); } +}; + +Vending::Vending() = default; // base registers Idle/Collecting/Done from States + +// @tag integration +Void::Testing::Test split_machine_runs_with_out_of_line_states() +{ + Vending fsm; + fsm.start(); + fsm.send(Charge{10}); // Idle -> Collecting (first coin counted there too?) + fsm.send(Charge{5}, Charge{10}); + fsm.send(Dispense{}); + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + // Idle consumes the first Charge to leave; Collecting sums 5 + 10 = 15. + Void::Testing::expect_eq(*outcome, 15); +} + +Void::Testing::Test split_machine_auto_registers_states_in_order() +{ + Vending fsm; + const auto& names = fsm.state_names(); + Void::Testing::expect_eq(names.size(), std::size_t{3}); + Void::Testing::expect_eq(names[0], std::string{"Idle"}); // initial + Void::Testing::expect_eq(names[1], std::string{"Collecting"}); + Void::Testing::expect_eq(names[2], std::string{"Done"}); +} diff --git a/tests/standalone/Fsm/SubMachine.cpp b/tests/standalone/Fsm/SubMachine.cpp index 6b23334..0be756f 100644 --- a/tests/standalone/Fsm/SubMachine.cpp +++ b/tests/standalone/Fsm/SubMachine.cpp @@ -8,15 +8,16 @@ using Void::Coro::Task; using Void::Fsm::ChildFailure; using Void::Fsm::ChildSuccess; using Void::Fsm::FsmError; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace Fsm = Void::Fsm; // startMachine(data) launches a full sub-FSM on the parent's shared // executor/events/services (startup data routed to Sub's initial-state // startup-entry), then enters Next. The engine dispatches the sub's typed -// outcome to Next's signature-matched handler — a member taking -// `ChildSuccess auto` (success) or `ChildFailure auto` (failure). No override, -// no fixed names. +// outcome to Next's signature-matched handler — a member taking `ChildSuccess` +// (success) or `ChildFailure` (failure); the typed value is read with +// `.as()`. No override, no fixed names. namespace { @@ -29,16 +30,17 @@ namespace using Success = int; using Failure = Void::Fsm::FsmError; - struct Run : State { - Task run(int seed) - { - if (seed < 0) { - co_return fail("negative"); - } - co_return succeed(seed * 2); - } + struct States { + struct Run : State { + Task run(int seed) + { + if (seed < 0) { + co_return fail("negative"); + } + co_return succeed(seed * 2); + } + }; }; - using States = Fsm::States; }; class Calc : public Fsm::Machine @@ -49,24 +51,27 @@ namespace int input = 0; - struct Start : State { - Task run() - { - co_return startMachine( - self().input); - } + struct States { + struct Start : State { + Task run() + { + co_return startMachine( + self().input); + } + }; + struct AfterDouble : State { + Task ok(ChildSuccess s) + { + co_return succeed("doubled:" + + std::to_string(s.as())); + } + Task no(ChildFailure f) + { + co_return succeed("failed:" + + f.as().message); + } + }; }; - struct AfterDouble : State { - Task ok(ChildSuccess auto s) - { - co_return succeed("doubled:" + std::to_string(s.value)); - } - Task no(ChildFailure auto f) - { - co_return succeed("failed:" + f.value.message); - } - }; - using States = Fsm::States; explicit Calc(int in) : input(in) {} }; @@ -98,10 +103,11 @@ namespace { public: - struct Ping : State { - Task run() { co_return succeed(); } + struct States { + struct Ping : State { + Task run() { co_return succeed(); } + }; }; - using States = Fsm::States; }; class Host : public Fsm::Machine @@ -110,14 +116,21 @@ namespace using Success = int; - struct Go : State { - Task run() { co_return startMachine(); } + struct States { + struct Go : State { + Task run() + { + co_return startMachine(); + } + }; + struct Done : State { + // void-result sub: ChildSuccess box has no value. + Task ok(ChildSuccess) + { + co_return succeed(42); + } + }; }; - struct Done : State { - // void-result sub: ChildSuccess box has no value. - Task ok(ChildSuccess auto) { co_return succeed(42); } - }; - using States = Fsm::States; }; } // namespace @@ -140,25 +153,27 @@ namespace using Success = int; - struct A : State { - Task run() - { - co_return startMachine(3); // 3 -> 6 - } + struct States { + struct A : State { + Task run() + { + co_return startMachine(3); // 3 -> 6 + } + }; + struct B : State { + Task ok(ChildSuccess s) + { + // 6 -> 12 + co_return startMachine(s.as()); + } + }; + struct C : State { + Task ok(ChildSuccess s) + { + co_return succeed(s.as()); + } + }; }; - struct B : State { - Task ok(ChildSuccess auto s) - { - co_return startMachine(s.value); // 6 -> 12 - } - }; - struct C : State { - Task ok(ChildSuccess auto s) - { - co_return succeed(s.value); - } - }; - using States = Fsm::States; }; } // namespace @@ -184,14 +199,15 @@ namespace using Success = int; - struct W : State { - Task run() - { - co_await await_event(); - co_return succeed(7); - } + struct States { + struct W : State { + Task run() + { + co_await await_event(); + co_return succeed(7); + } + }; }; - using States = Fsm::States; }; class Outer : public Fsm::Machine @@ -200,16 +216,20 @@ namespace using Success = int; - struct Begin : State { - Task run() { co_return startMachine(); } + struct States { + struct Begin : State { + Task run() + { + co_return startMachine(); + } + }; + struct Fin : State { + Task ok(ChildSuccess s) + { + co_return succeed(s.as()); + } + }; }; - struct Fin : State { - Task ok(ChildSuccess auto s) - { - co_return succeed(s.value); - } - }; - using States = Fsm::States; }; } // namespace diff --git a/tests/standalone/Functional/RetryJitter.cpp b/tests/standalone/Functional/RetryJitter.cpp new file mode 100644 index 0000000..36efdad --- /dev/null +++ b/tests/standalone/Functional/RetryJitter.cpp @@ -0,0 +1,77 @@ +#include +#include +#include + +#include +#include + +namespace +{ + using Void::Testing::Test; + using namespace std::chrono_literals; + namespace R = Void::Retry; + + struct RetryJitter : Void::Testing::Suite { + Test full_jitter_stays_within_bounds() + { + R::Jittered j{R::ConstantDelay{100ms}, + R::JitterMode::Full}; + for (int i = 0; i < 100; ++i) { + const auto d = j.delay(0); + Void::Testing::expect(d >= 0ms); + Void::Testing::expect(d <= 100ms); + } + } + + Test equal_jitter_keeps_floor() + { + R::Jittered j{R::ConstantDelay{100ms}, + R::JitterMode::Equal}; + for (int i = 0; i < 100; ++i) { + const auto d = j.delay(0); + Void::Testing::expect(d >= 50ms); + Void::Testing::expect(d <= 100ms); + } + } + + Test budget_stops_retries_early() + { + R::Policy policy; + policy.max_attempts = 5; + policy.backoff = R::ConstantDelay{0ms}; + policy.max_elapsed = 5ms; + + int calls = 0; + auto result = + R::retry(policy, [&]() -> std::expected { + ++calls; + std::this_thread::sleep_for( + 10ms); // overruns the budget + return std::unexpected{-1}; + }); + Void::Testing::expect(!result.has_value()); + // Budget (5ms) is blown after the first 10ms attempt, so we + // stop well short of max_attempts. + Void::Testing::expect(calls < 5); + } + + Test jittered_retry_still_succeeds() + { + R::Policy> policy; + policy.max_attempts = 3; + policy.backoff = {R::ConstantDelay{1ms}, R::JitterMode::Full}; + + int calls = 0; + auto result = + R::retry(policy, [&]() -> std::expected { + if (++calls < 2) { + return std::unexpected{-1}; + } + return 42; + }); + Void::Testing::expect(result.has_value()); + Void::Testing::expect_eq(result.value(), 42); + Void::Testing::expect_eq(calls, 2); + } + }; +} // namespace diff --git a/tests/standalone/Log/FieldReflect.cpp b/tests/standalone/Log/FieldReflect.cpp new file mode 100644 index 0000000..d439753 --- /dev/null +++ b/tests/standalone/Log/FieldReflect.cpp @@ -0,0 +1,45 @@ +#include +#include +#include + +#include + +namespace +{ + struct Request { + std::string id = "abc"; + int retries = 0; + }; +} // namespace + +// @tag reflection +Void::Testing::Test field_scope_from_reflects_struct() +{ + Request r{"xyz", 42}; + auto scope = Void::Logging::FieldScope::from(r); + + bool has_id = false; + bool has_retries = false; + for (const auto& [k, v] : Void::Logging::current_fields()) { + if (k == "id" && v == "xyz") { + has_id = true; + } + if (k == "retries" && v == "42") { + has_retries = true; + } + } + Void::Testing::expect(has_id); + Void::Testing::expect(has_retries); +} + +Void::Testing::Test field_scope_from_pops_on_exit() +{ + const auto before = Void::Logging::current_fields().size(); + { + Request r{}; + auto scope = Void::Logging::FieldScope::from(r); + Void::Testing::expect_eq(Void::Logging::current_fields().size(), + before + 2); + } + Void::Testing::expect_eq(Void::Logging::current_fields().size(), before); +} diff --git a/tests/standalone/Log/StructuredFields.cpp b/tests/standalone/Log/StructuredFields.cpp new file mode 100644 index 0000000..b475822 --- /dev/null +++ b/tests/standalone/Log/StructuredFields.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +#include + +namespace +{ + using Void::Logging::Entry; + using Void::Logging::FieldFilter; + using Void::Logging::JsonLinesFormatter; + using Void::Logging::Level; + using Void::Logging::LogfmtFormatter; + using Void::Testing::Test; + + Entry make_entry() + { + Entry e; + e.level = Level::Info; + e.message = "served"; + e.fields = {{"service", "ingest"}, + {"request_id", "abc123"}, + {"secret", "hunter2"}}; + return e; + } + + bool contains(const std::string& hay, std::string_view needle) + { + return hay.find(needle) != std::string::npos; + } + + struct StructuredFields : Void::Testing::Suite { + Test exclude_drops_named_fields() + { + JsonLinesFormatter fmt; + fmt.set_field_filter(FieldFilter{.exclude = {"secret"}}); + const auto out = fmt.format(make_entry()); + Void::Testing::expect(contains(out, "service")); + Void::Testing::expect(contains(out, "request_id")); + Void::Testing::expect(!contains(out, "secret")); + Void::Testing::expect(!contains(out, "hunter2")); + } + + Test include_admits_only_listed_fields() + { + LogfmtFormatter fmt; + fmt.set_field_filter(FieldFilter{.include = {"service"}}); + const auto out = fmt.format(make_entry()); + Void::Testing::expect(contains(out, "service=\"ingest\"")); + Void::Testing::expect(!contains(out, "request_id")); + Void::Testing::expect(!contains(out, "secret")); + } + + Test no_filter_keeps_all_fields() + { + JsonLinesFormatter fmt; + const auto out = fmt.format(make_entry()); + Void::Testing::expect(contains(out, "service")); + Void::Testing::expect(contains(out, "request_id")); + Void::Testing::expect(contains(out, "secret")); + } + }; +} // namespace diff --git a/tests/standalone/Resilience/CircuitBreaker.cpp b/tests/standalone/Resilience/CircuitBreaker.cpp new file mode 100644 index 0000000..2416912 --- /dev/null +++ b/tests/standalone/Resilience/CircuitBreaker.cpp @@ -0,0 +1,89 @@ +#include +#include +#include + +#include +#include +#include + +namespace +{ + using Void::Resilience::CircuitBreaker; + using Void::Testing::Test; + using State = CircuitBreaker::State; + using namespace std::chrono_literals; + using TP = std::chrono::steady_clock::time_point; + + struct ManualClock { + std::shared_ptr now = + std::make_shared(std::chrono::steady_clock::now()); + auto fn() const + { + auto p = now; + return [p] { return *p; }; + } + void advance(std::chrono::nanoseconds d) const { *now += d; } + }; + + struct CircuitBreakerTests : Void::Testing::Suite { + Test trips_open_after_threshold_failures() + { + ManualClock clk; + CircuitBreaker cb{3, 1s, 1, clk.fn()}; + cb.record_failure(); + cb.record_failure(); + Void::Testing::expect(cb.state() == State::Closed); + cb.record_failure(); // third -> open + Void::Testing::expect(cb.state() == State::Open); + Void::Testing::expect(!cb.allow()); + } + + Test half_opens_after_cooldown_then_closes() + { + ManualClock clk; + CircuitBreaker cb{2, 1s, 1, clk.fn()}; + cb.record_failure(); + cb.record_failure(); // open + Void::Testing::expect(!cb.allow()); + clk.advance(1s); + Void::Testing::expect(cb.allow()); // probe admitted (half-open) + Void::Testing::expect(cb.state() == State::HalfOpen); + cb.record_success(); // closes + Void::Testing::expect(cb.state() == State::Closed); + } + + Test half_open_failure_reopens() + { + ManualClock clk; + CircuitBreaker cb{2, 1s, 1, clk.fn()}; + cb.record_failure(); + cb.record_failure(); + clk.advance(1s); + (void)cb.allow(); // -> half-open + cb.record_failure(); + Void::Testing::expect(cb.state() == State::Open); + } + + Test execute_gates_and_records() + { + ManualClock clk; + CircuitBreaker cb{2, 1s, 1, clk.fn()}; + const auto ok = [] { return std::expected{42}; }; + const auto bad = [] { + return std::expected{std::unexpect, -1}; + }; + + auto r = cb.execute(ok); + Void::Testing::expect(r.has_value()); + Void::Testing::expect(r->has_value()); + Void::Testing::expect_eq(r->value(), 42); + + (void)cb.execute(bad); + (void)cb.execute(bad); // open now + Void::Testing::expect(cb.state() == State::Open); + + auto rejected = cb.execute(ok); + Void::Testing::expect(!rejected.has_value()); // circuit refused + } + }; +} // namespace diff --git a/tests/standalone/Resilience/KeyedRateLimiter.cpp b/tests/standalone/Resilience/KeyedRateLimiter.cpp new file mode 100644 index 0000000..451578d --- /dev/null +++ b/tests/standalone/Resilience/KeyedRateLimiter.cpp @@ -0,0 +1,75 @@ +#include +#include +#include + +#include +#include +#include +#include + +namespace +{ + using Void::Resilience::KeyedRateLimiter; + using Void::Testing::Test; + using namespace std::chrono_literals; + using TP = std::chrono::steady_clock::time_point; + + struct ManualClock { + std::shared_ptr now = + std::make_shared(std::chrono::steady_clock::now()); + auto fn() const + { + auto p = now; + return [p] { return *p; }; + } + void advance(std::chrono::nanoseconds d) const { *now += d; } + }; + + struct KeyedRateLimiterTests : Void::Testing::Suite { + // Each key drains its own bucket independently. + Test keys_are_independent() + { + ManualClock clk; + KeyedRateLimiter rl{3.0, 1.0, clk.fn()}; + Void::Testing::expect(rl.allow(1)); + Void::Testing::expect(rl.allow(1)); + Void::Testing::expect(rl.allow(1)); + Void::Testing::expect(!rl.allow(1)); // key 1 exhausted + Void::Testing::expect(rl.allow(2)); // key 2 still full + } + + Test refills_per_key_over_time() + { + ManualClock clk; + KeyedRateLimiter rl{2.0, 2.0, clk.fn()}; + Void::Testing::expect(rl.allow("a", 2.0)); + Void::Testing::expect(!rl.allow("a")); + clk.advance(1s); // +2 tokens + Void::Testing::expect(rl.allow("a")); + } + + Test reset_forgets_a_key() + { + ManualClock clk; + KeyedRateLimiter rl{1.0, 0.0, clk.fn()}; + Void::Testing::expect(rl.allow(7)); + Void::Testing::expect(!rl.allow(7)); + rl.reset(7); // next use starts full again + Void::Testing::expect(rl.allow(7)); + } + + Test cleanup_drops_stale_keys() + { + KeyedRateLimiter rl{1.0, 1.0}; + (void)rl.allow(1); + (void)rl.allow(2); + Void::Testing::expect_eq(rl.tracked(), std::size_t{2}); + // Nothing is older than an hour yet. + Void::Testing::expect_eq(rl.cleanup(1h), std::size_t{0}); + Void::Testing::expect_eq(rl.tracked(), std::size_t{2}); + // Everything is older than 0ns. + Void::Testing::expect_eq(rl.cleanup(0ns), std::size_t{2}); + Void::Testing::expect_eq(rl.tracked(), std::size_t{0}); + } + }; +} // namespace diff --git a/tests/standalone/Resilience/RateLimiter.cpp b/tests/standalone/Resilience/RateLimiter.cpp new file mode 100644 index 0000000..e4f8383 --- /dev/null +++ b/tests/standalone/Resilience/RateLimiter.cpp @@ -0,0 +1,55 @@ +#include +#include +#include + +#include +#include + +namespace +{ + using Void::Resilience::TokenBucket; + using Void::Testing::Test; + using namespace std::chrono_literals; + using TP = std::chrono::steady_clock::time_point; + + struct ManualClock { + std::shared_ptr now = + std::make_shared(std::chrono::steady_clock::now()); + auto fn() const + { + auto p = now; + return [p] { return *p; }; + } + void advance(std::chrono::nanoseconds d) const { *now += d; } + }; + + struct RateLimiterTests : Void::Testing::Suite { + Test starts_full_and_drains() + { + ManualClock clk; + TokenBucket b{10.0, 5.0, clk.fn()}; + Void::Testing::expect(b.try_acquire(10.0)); // drains the bucket + Void::Testing::expect(!b.try_acquire(1.0)); // now empty + } + + Test refills_over_time() + { + ManualClock clk; + TokenBucket b{10.0, 5.0, clk.fn()}; + Void::Testing::expect(b.try_acquire(10.0)); + clk.advance(1s); // +5 tokens + Void::Testing::expect(b.try_acquire(5.0)); + Void::Testing::expect(!b.try_acquire(0.5)); + } + + Test refill_is_clamped_to_capacity() + { + ManualClock clk; + TokenBucket b{10.0, 5.0, clk.fn()}; + Void::Testing::expect(b.try_acquire(10.0)); + clk.advance(100s); // would be 500 tokens, clamps to 10 + Void::Testing::expect(b.available() <= 10.0); + Void::Testing::expect(b.available() >= 9.99); + } + }; +} // namespace diff --git a/tests/standalone/Resilience/ResourceMonitor.cpp b/tests/standalone/Resilience/ResourceMonitor.cpp new file mode 100644 index 0000000..1b957d7 --- /dev/null +++ b/tests/standalone/Resilience/ResourceMonitor.cpp @@ -0,0 +1,51 @@ +#include +#include +#include + +namespace +{ + using Void::Resilience::ResourceMonitor; + using Void::Testing::Test; + + struct ResourceMonitorTests : Void::Testing::Suite { + Test acquire_refuses_to_exceed_limit() + { + ResourceMonitor m{100}; + Void::Testing::expect(m.try_acquire(80)); + Void::Testing::expect(!m.try_acquire(30)); // would be 110 > 100 + Void::Testing::expect_eq(m.usage(), std::uint64_t{80}); + } + + Test high_watermark_fires_once_on_crossing() + { + ResourceMonitor m{100, 0.9, 0.7}; + int highs = 0; + m.on_high_watermark([&](std::uint64_t) { ++highs; }); + Void::Testing::expect(m.try_acquire(80)); // 80 < 90, no fire + Void::Testing::expect_eq(highs, 0); + Void::Testing::expect(m.try_acquire(15)); // 95 >= 90, fire + Void::Testing::expect_eq(highs, 1); + Void::Testing::expect(m.try_acquire(3)); // 98, still alarmed + Void::Testing::expect_eq(highs, 1); // no re-fire + } + + Test low_watermark_fires_on_drop() + { + ResourceMonitor m{100, 0.9, 0.7}; + int lows = 0; + m.on_low_watermark([&](std::uint64_t) { ++lows; }); + Void::Testing::expect(m.try_acquire(95)); // alarmed + m.release(30); // 65 <= 70 -> fire + Void::Testing::expect_eq(lows, 1); + Void::Testing::expect_eq(m.usage(), std::uint64_t{65}); + } + + Test release_clamps_at_zero() + { + ResourceMonitor m{100}; + Void::Testing::expect(m.try_acquire(10)); + m.release(50); // more than held + Void::Testing::expect_eq(m.usage(), std::uint64_t{0}); + } + }; +} // namespace diff --git a/tests/standalone/Service/InterfaceName.cpp b/tests/standalone/Service/InterfaceName.cpp new file mode 100644 index 0000000..d823bd4 --- /dev/null +++ b/tests/standalone/Service/InterfaceName.cpp @@ -0,0 +1,19 @@ +#include +#include +#include + +#include + +namespace +{ + struct IClock { + virtual ~IClock() = default; + }; +} // namespace + +// @tag reflection +Void::Testing::Test service_interface_name_is_reflected() +{ + Void::Testing::expect_eq(Void::Service::interface_name(), + std::string{"IClock"}); +} diff --git a/tests/standalone/Service/Orchestrator.cpp b/tests/standalone/Service/Orchestrator.cpp index 7c7d7f8..e4b966e 100644 --- a/tests/standalone/Service/Orchestrator.cpp +++ b/tests/standalone/Service/Orchestrator.cpp @@ -15,7 +15,8 @@ using Void::Coro::Task; using Void::Fsm::MachineOptions; using Void::Fsm::Orchestrator; using Void::Fsm::Status; -using Void::Fsm::Step; +using Void::Fsm::State; +using Void::Fsm::StateKey; namespace { @@ -75,7 +76,7 @@ namespace int times; struct Run : State { - Task run() + Task run() { auto& m = self(); int last = 0; @@ -116,7 +117,7 @@ Void::Testing::Test orchestrator_launches_and_supervises() using Success = int; struct Run : State { - Task run() + Task run() { int last = 0; for (int i = 0; i < 5; ++i) { diff --git a/tests/standalone/Service/ScopedRegistry.cpp b/tests/standalone/Service/ScopedRegistry.cpp new file mode 100644 index 0000000..936e702 --- /dev/null +++ b/tests/standalone/Service/ScopedRegistry.cpp @@ -0,0 +1,70 @@ +#include +#include +#include + +#include + +namespace +{ + using Void::Service::ServiceRegistry; + using Void::Testing::Test; + + struct IGreeter { + virtual ~IGreeter() = default; + virtual int id() const = 0; + }; + struct Greeter : IGreeter { + int v; + explicit Greeter(int x) : v{x} {} + int id() const override { return v; } + }; + + struct IOther { + virtual ~IOther() = default; + }; + struct Other : IOther { + }; + + struct ScopedRegistry : Void::Testing::Suite { + Test child_falls_through_to_parent() + { + ServiceRegistry parent; + parent.provide(std::make_shared(1)); + + ServiceRegistry child{&parent}; + Void::Testing::expect(child.has()); + Void::Testing::expect_eq(child.require().id(), 1); + } + + Test child_shadows_parent() + { + ServiceRegistry parent; + parent.provide(std::make_shared(1)); + + ServiceRegistry child{&parent}; + child.provide(std::make_shared(2)); + + Void::Testing::expect_eq(child.require().id(), 2); + // Parent is untouched. + Void::Testing::expect_eq(parent.require().id(), 1); + } + + Test child_local_provide_invisible_to_parent() + { + ServiceRegistry parent; + ServiceRegistry child{&parent}; + child.provide(std::make_shared()); + + Void::Testing::expect(child.has()); + Void::Testing::expect(!parent.has()); + } + + Test miss_in_both_returns_nullptr() + { + ServiceRegistry parent; + ServiceRegistry child{&parent}; + Void::Testing::expect(child.get() == nullptr); + Void::Testing::expect(!child.has()); + } + }; +} // namespace diff --git a/tests/standalone/System/Metrics.cpp b/tests/standalone/System/Metrics.cpp new file mode 100644 index 0000000..010b2f7 --- /dev/null +++ b/tests/standalone/System/Metrics.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include + +namespace +{ + using Void::Testing::Test; + + struct MetricsTests : Void::Testing::Suite { + // On Linux these return real values; elsewhere nullopt (skip). + Test process_memory_is_plausible() + { + const auto rss = Void::SystemInfo::process_memory_bytes(); + if (rss.has_value()) { + Void::Testing::expect(*rss > 0); + } + } + + Test system_memory_total_positive() + { + const auto mem = Void::SystemInfo::system_memory(); + if (mem.has_value()) { + Void::Testing::expect(mem->total > 0); + Void::Testing::expect(mem->available <= mem->total); + } + } + + Test cpu_sampler_is_non_negative() + { + Void::SystemInfo::CpuSampler sampler; + // Burn a little CPU so a second sample has something to report. + volatile double sink = 0.0; + for (int i = 0; i < 1'000'000; ++i) { + sink += static_cast(i) * 0.5; + } + (void)sink; + const double usage = sampler.usage(); + Void::Testing::expect(usage >= 0.0); + } + }; +} // namespace diff --git a/tests/standalone/System/ProcessStream.cpp b/tests/standalone/System/ProcessStream.cpp new file mode 100644 index 0000000..2a8e355 --- /dev/null +++ b/tests/standalone/System/ProcessStream.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + +#include +#include + +namespace +{ + using Void::Testing::Test; + + struct ProcessStream : Void::Testing::Suite { + // stdout lines are delivered to the callback as they arrive, and + // the full output is still captured. + Test streams_stdout_lines() + { + std::vector lines; + Void::Process::StreamCallbacks cb; + cb.on_stdout = [&](std::string_view l) { + lines.emplace_back(l); + }; + + auto r = Void::Process::run_streaming( + "/bin/sh", {"-c", "printf 'a\\nb\\nc\\n'"}, cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 0); + + const std::vector expected{"a", "b", "c"}; + Void::Testing::expect(lines == expected); + Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"}); + } + + // A trailing partial line (no newline) is flushed at EOF. + Test flushes_trailing_partial_line() + { + std::vector lines; + Void::Process::StreamCallbacks cb; + cb.on_stdout = [&](std::string_view l) { + lines.emplace_back(l); + }; + + auto r = Void::Process::run_streaming( + "/bin/sh", {"-c", "printf 'no-newline'"}, cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(lines.size(), std::size_t{1}); + Void::Testing::expect_eq(lines.at(0), + std::string{"no-newline"}); + } + + // stderr is routed to its own callback. + Test streams_stderr_separately() + { + std::vector errs; + Void::Process::StreamCallbacks cb; + cb.on_stderr = [&](std::string_view l) { + errs.emplace_back(l); + }; + + auto r = Void::Process::run_streaming( + "/bin/sh", {"-c", "printf 'oops\\n' 1>&2"}, cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(errs.size(), std::size_t{1}); + Void::Testing::expect_eq(errs.at(0), std::string{"oops"}); + } + }; +} // namespace diff --git a/tests/standalone/Testing/ContainerFixture.cpp b/tests/standalone/Testing/ContainerFixture.cpp index b93d469..9ec695d 100644 --- a/tests/standalone/Testing/ContainerFixture.cpp +++ b/tests/standalone/Testing/ContainerFixture.cpp @@ -1,28 +1,27 @@ #include -#include -#include +#include #include -class VectorFixture : public Void::Testing::Fixture +namespace { - public: + using Void::Testing::Test; - std::vector vec; + // setup()/teardown() run around each test method (a fresh instance per + // test), exactly like the old Fixture base — but discovered by reflection. + struct ContainerFixture : Void::Testing::Suite { + std::vector vec; - void setup() override { vec = {1, 2, 3}; } - void teardown() override { vec.clear(); } + void setup() { vec = {1, 2, 3}; } + void teardown() { vec.clear(); } - Void::Testing::Test size() - { - Void::Testing::expect_eq(vec.size(), 3u); - } + Test size() { Void::Testing::expect_eq(vec.size(), 3u); } - // @tag slow - Void::Testing::Test push_back() - { - vec.push_back(4); - Void::Testing::expect_eq(vec.size(), 4u); - Void::Testing::expect_eq(vec.back(), 4); - } -}; + [[= Void::Testing::tag("slow")]] Test push_back() + { + vec.push_back(4); + Void::Testing::expect_eq(vec.size(), 4u); + Void::Testing::expect_eq(vec.back(), 4); + } + }; +} // namespace diff --git a/tests/standalone/TestingMock/Reflect.cpp b/tests/standalone/TestingMock/Reflect.cpp new file mode 100644 index 0000000..77640ea --- /dev/null +++ b/tests/standalone/TestingMock/Reflect.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +#include + +namespace +{ + struct IDb { + virtual ~IDb() = default; + virtual int query(std::string_view s) = 0; + virtual void close() = 0; + int helper() { return 0; } // non-virtual — ignored + }; + struct GoodMock : IDb { + int query(std::string_view) override { return 0; } + void close() override {} + }; + struct BadMock : IDb { + int query(std::string_view) override { return 0; } + // missing close() → still abstract + }; + + using Void::Testing::Test; + + struct MockReflect : Void::Testing::Suite { + Test lists_virtual_methods() + { + const auto names = Void::TestingMock::method_names(); + Void::Testing::expect_eq(names.size(), std::size_t{2}); + Void::Testing::expect(names[0] == "query" && + names[1] == "close"); + static_assert(Void::TestingMock::method_count() == 2); + } + + Test covers_detects_completeness() + { + static_assert(Void::TestingMock::covers()); + static_assert(!Void::TestingMock::covers()); + Void::Testing::expect( + Void::TestingMock::covers()); + Void::Testing::expect( + !Void::TestingMock::covers()); + } + }; +} // namespace