Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection based, no app coupling), verified by the test suite (1103 passing): Data reflection: - Reflect.hpp now (de)serializes chrono::duration, chrono::time_point, std::variant (tagged), std::array, and non-string-keyed std::map; Meta.hpp gains is_time_point_v et al. Async: - EventBus gains Mode::Async (worker-thread dispatch + flush()). - ThreadPool gains a bounded queue, try_submit(), and rejection stats. New modules / containers: - Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker, ResourceMonitor. - Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V> (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats). - System: process/CPU/memory metrics (Metrics.hpp) and a streaming Process API. Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions, history states, deferred events), Configuration/Logging reflection helpers, and the accompanying test suites. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
43b5a81504
commit
80293ee56f
93 files changed
+8500
-3312
No files matched your search
@@ -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<T>` (the one `nonstatic_data_members_of` + `define_static_array`), `field_count<T>()`, `field_names<T>()`, `for_each_field(obj, fn)`, `type_name<T>()`.
|
||||
- **Annotations:** `Str` (a *value-based fixed-capacity string* — annotation payloads can't be `std::string_view`/`const char*`, which aren't structural), `has_annotation<Tag>(member)`, `annotation_of<Tag>(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<E>`, `enum_values<E>()`, `enum_entries<E>()`.
|
||||
|
||||
**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<T>()`, `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<I>()` 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<YourSuite>` (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 <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
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<MathTests> {
|
||||
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 <reason>` — 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(<target>)`.
|
||||
**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 `<meta>` 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<I>()` lists an
|
||||
interface's virtual methods; `covers<Mock, I>()` 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 — `<meta>` has `define_aggregate` (it can
|
||||
generate a `MockFunction<Sig>` member per virtual) but no code injection for the
|
||||
override bodies, so `MockFunction<Sig>` 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<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(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<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(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<Opts>(argc, argv)` — define an options struct, annotate fields (`arg::Short`/`Help`/`Name`/`Positional`), parse straight into it (bool→flag, string→option w/ default, optional<string>→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<Derived>` (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<Derived>` (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<StateKey>> 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<Step>` with no params (`Task<Step> run()`); a **startup-entry** overload takes the launch data (`Task<Step> 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<StateKey>>` with no params (`Task<State> run()`); a **startup-entry** overload takes the launch data (`Task<State> run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor). Events are awaited imperatively in the entry (`co_await await_event<E>()`). 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<T>()`/`f.as<T>()` (`ChildSuccess`/`ChildFailure` are concrete types, no `auto`). The engine picks by the launched sub's outcome.
|
||||
|
||||
Mechanics: at `add<S>()` a `Detail::make_driver<S>()` reflection thunk is stored (reactive table vs entry, chosen by whether `S` has a `TransitionBuilder&` member); `drive()` calls the thunk. `startMachine<Sub, Next>(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<Next, Sub>`) 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<Step>` (wrapping plain `Step` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**.
|
||||
Mechanics: at `add<S>()` a `Detail::make_driver<S>()` 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<S>()` / `startMachine<,Next>` compile-time target check). `startMachine<Sub, Next>(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<Next, Sub>`) that wraps the sub's outcome in a type-erased `ChildSuccess`/`ChildFailure` (value in a `std::any`, read via `.as<T>()`) 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<State>` (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<Success, Failure>` (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<Derived>` resolve the nested types by plain name lookup (`Detail/Result.hpp`).
|
||||
|
||||
Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp` (the `Machine<Derived>` 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<Derived>`); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable<Derived>` 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<T>()`).
|
||||
Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp` (the `Machine<Derived>` 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<Derived>`); `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<T>()`).
|
||||
|
||||
- **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<E>()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post<E>(e)` is lock-free from any thread.
|
||||
- **Nesting**: `co_await run_child<Sub>(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected<R, FsmError>`) — the imperative form, branch on it yourself.
|
||||
- **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(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<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (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<R>`) dispatches — a plain state entered with a pending result just `run()`s.
|
||||
- **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(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<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (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<A, B, …>()` 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<A::Outcome, …>`. `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<Sub>()` 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<Done>() : next<Recover>()`). Parent-level multi-event handling via `co_await await_any<E1, E2, …>()` → `std::variant<Es...>` (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<S>()` / `add_if<S>(cond)`; `next<unregistered>` fails; `has_state<S>()` lets a state branch.
|
||||
- **Direct control**: fluent `send(e1, e2, …)` (variadic `post`); free in-state jumps via `goto_state<S>()` (any registered state, no declared transition); external `jump<S>()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at<S>()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove<S>()` / `set_initial<S>()` / `replace<S, T>()`.
|
||||
- **Services**: `set_services(registry)`; `state.service<I>()` 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<E>()` 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<E>().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<bool>` sub-step), `next_or<Fallback>(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<E>(d)` (→ `optional`, `nullopt` on timeout) or `delay(d)`; multi-event — `co_await await_any<A, B>()` → `std::variant<A,B>`; guard — a plain `if` after the await; internal/self transition — a `for(;;)` loop in the entry that handles events without returning (or `next<Self>()`); **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<bool>` sub-step), `next_or<Fallback>(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<I>()` call without being patched.
|
||||
|
||||
|
||||
@@ -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 "")
|
||||
|
||||
+193
-58
@@ -1,8 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <any>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -10,72 +15,202 @@
|
||||
namespace Void::EventBus
|
||||
{
|
||||
|
||||
// ── EventBus ──────────────────────────────────────────────────────────────────
|
||||
// Synchronous publish/subscribe bus keyed by event type.
|
||||
// Handlers are invoked on the caller's thread inside publish().
|
||||
// Not thread-safe; use external locking if shared across threads.
|
||||
// ── EventBus
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Publish/subscribe bus keyed by event type.
|
||||
//
|
||||
// Mode::Sync (default) handlers run inline on the publisher's thread
|
||||
// inside
|
||||
// publish() — the original zero-overhead behavior.
|
||||
// Mode::Async publish() snapshots the handlers and a copy of
|
||||
// the
|
||||
// event onto an owned worker thread, so slow
|
||||
// handlers (network / DB I/O) never block the
|
||||
// publisher. flush() waits for everything submitted
|
||||
// before the call.
|
||||
//
|
||||
// In Sync mode the bus is not thread-safe (use external locking if shared).
|
||||
// In Async mode publish/subscribe/flush are safe to call from any thread.
|
||||
|
||||
class EventBus
|
||||
{
|
||||
public:
|
||||
using HandlerId = std::size_t;
|
||||
enum class Mode { Sync, Async };
|
||||
|
||||
// Subscribe to events of type Event. Returns a HandlerId for unsubscription.
|
||||
template <typename Event>
|
||||
HandlerId subscribe(std::function<void(const Event&)> handler)
|
||||
{
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
const HandlerId id = next_id_++;
|
||||
handlers_[key].push_back(Entry{id, [h = std::move(handler)](const std::any& ev) {
|
||||
h(std::any_cast<const Event&>(ev));
|
||||
}});
|
||||
return id;
|
||||
}
|
||||
class EventBus
|
||||
{
|
||||
public:
|
||||
|
||||
// Publish an event to all subscribers of its type.
|
||||
template <typename Event>
|
||||
void publish(const Event& event)
|
||||
{
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) return;
|
||||
for (const auto& e : it->second) e.fn(event);
|
||||
}
|
||||
using HandlerId = std::size_t;
|
||||
|
||||
// Unsubscribe by id. O(n) per event type — acceptable for small handler counts.
|
||||
void unsubscribe(HandlerId id)
|
||||
{
|
||||
for (auto& [key, list] : handlers_) {
|
||||
const auto before = list.size();
|
||||
std::erase_if(list, [id](const Entry& e) { return e.id == id; });
|
||||
if (list.size() != before) return;
|
||||
}
|
||||
}
|
||||
explicit EventBus(Mode mode = Mode::Sync) : mode_(mode)
|
||||
{
|
||||
if (mode_ == Mode::Async) {
|
||||
worker_ = std::thread([this] { run(); });
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all handlers for a given event type.
|
||||
template <typename Event>
|
||||
void clear()
|
||||
{
|
||||
handlers_.erase(std::type_index{typeid(Event)});
|
||||
}
|
||||
~EventBus()
|
||||
{
|
||||
if (mode_ == Mode::Async) {
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
stop_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
worker_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void clear_all() { handlers_.clear(); }
|
||||
EventBus(const EventBus&) = delete;
|
||||
EventBus& operator=(const EventBus&) = delete;
|
||||
EventBus(EventBus&&) = delete;
|
||||
EventBus& operator=(EventBus&&) = delete;
|
||||
|
||||
template <typename Event>
|
||||
[[nodiscard]] std::size_t subscriber_count() const
|
||||
{
|
||||
const auto it = handlers_.find(std::type_index{typeid(Event)});
|
||||
return it == handlers_.end() ? 0 : it->second.size();
|
||||
}
|
||||
// Subscribe to events of type Event. Returns a HandlerId for
|
||||
// unsubscription.
|
||||
template <typename Event>
|
||||
HandlerId subscribe(std::function<void(const Event&)> handler)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
const HandlerId id = next_id_++;
|
||||
handlers_[key].push_back(
|
||||
Entry{id, [h = std::move(handler)](const std::any& ev) {
|
||||
h(std::any_cast<const Event&>(ev));
|
||||
}});
|
||||
return id;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
HandlerId id;
|
||||
std::function<void(const std::any&)> fn;
|
||||
};
|
||||
// Publish an event to all subscribers of its type.
|
||||
template <typename Event> void publish(const Event& event)
|
||||
{
|
||||
const auto key = std::type_index{typeid(Event)};
|
||||
if (mode_ == Mode::Sync) {
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) {
|
||||
return;
|
||||
}
|
||||
for (const auto& e : it->second) {
|
||||
e.fn(event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
|
||||
HandlerId next_id_{1};
|
||||
};
|
||||
// Async: snapshot the current handlers and queue a dispatch
|
||||
// carrying a copy of the event, so later unsubscribe()s don't
|
||||
// affect this publish.
|
||||
std::unique_lock lock{mu_};
|
||||
const auto it = handlers_.find(key);
|
||||
if (it == handlers_.end()) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::function<void(const std::any&)>> snapshot;
|
||||
snapshot.reserve(it->second.size());
|
||||
for (const auto& e : it->second) {
|
||||
snapshot.push_back(e.fn);
|
||||
}
|
||||
tasks_.push([snap = std::move(snapshot), ev = std::any{event}] {
|
||||
for (const auto& fn : snap) {
|
||||
fn(ev);
|
||||
}
|
||||
});
|
||||
++enqueued_;
|
||||
lock.unlock();
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
// Async only: block until every event published before this call
|
||||
// has been dispatched. A no-op in Sync mode (delivery already
|
||||
// happened in publish()).
|
||||
void flush()
|
||||
{
|
||||
if (mode_ != Mode::Async) {
|
||||
return;
|
||||
}
|
||||
std::unique_lock lock{mu_};
|
||||
const auto target = enqueued_;
|
||||
done_cv_.wait(lock, [&] { return processed_ >= target; });
|
||||
}
|
||||
|
||||
// Unsubscribe by id. O(n) per event type — acceptable for small
|
||||
// handler counts.
|
||||
void unsubscribe(HandlerId id)
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
for (auto& [key, list] : handlers_) {
|
||||
const auto before = list.size();
|
||||
std::erase_if(list,
|
||||
[id](const Entry& e) { return e.id == id; });
|
||||
if (list.size() != before) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all handlers for a given event type.
|
||||
template <typename Event> void clear()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
handlers_.erase(std::type_index{typeid(Event)});
|
||||
}
|
||||
|
||||
void clear_all()
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
handlers_.clear();
|
||||
}
|
||||
|
||||
template <typename Event>
|
||||
[[nodiscard]] std::size_t subscriber_count() const
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
const auto it = handlers_.find(std::type_index{typeid(Event)});
|
||||
return it == handlers_.end() ? 0 : it->second.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] Mode mode() const noexcept { return mode_; }
|
||||
|
||||
private:
|
||||
|
||||
struct Entry {
|
||||
HandlerId id;
|
||||
std::function<void(const std::any&)> fn;
|
||||
};
|
||||
|
||||
void run()
|
||||
{
|
||||
for (;;) {
|
||||
std::function<void()> task;
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
cv_.wait(lock,
|
||||
[this] { return stop_ || !tasks_.empty(); });
|
||||
if (stop_ && tasks_.empty()) {
|
||||
return;
|
||||
}
|
||||
task = std::move(tasks_.front());
|
||||
tasks_.pop();
|
||||
}
|
||||
task();
|
||||
{
|
||||
std::unique_lock lock{mu_};
|
||||
++processed_;
|
||||
}
|
||||
done_cv_.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
Mode mode_;
|
||||
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
|
||||
HandlerId next_id_{1};
|
||||
|
||||
mutable std::mutex mu_;
|
||||
// Async machinery (unused in Sync mode).
|
||||
std::thread worker_;
|
||||
std::queue<std::function<void()>> tasks_;
|
||||
std::condition_variable cv_;
|
||||
std::condition_variable done_cv_;
|
||||
std::uint64_t enqueued_{0};
|
||||
std::uint64_t processed_{0};
|
||||
bool stop_{false};
|
||||
};
|
||||
|
||||
} // namespace Void::EventBus
|
||||
@@ -1,11 +1,14 @@
|
||||
#pragma once
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
@@ -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 <std::invocable F>
|
||||
auto submit(F&& f) -> std::future<std::invoke_result_t<F>>
|
||||
{
|
||||
@@ -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 <std::invocable F>
|
||||
auto try_submit(F&& f)
|
||||
-> std::optional<std::future<std::invoke_result_t<F>>>
|
||||
{
|
||||
using R = std::invoke_result_t<F>;
|
||||
auto task = std::make_shared<std::packaged_task<R()>>(
|
||||
std::forward<F>(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 <typename R>
|
||||
void push_locked(std::shared_ptr<std::packaged_task<R()>> 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<std::thread> workers_;
|
||||
std::queue<std::function<void()>> queue_;
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
std::condition_variable not_full_;
|
||||
std::atomic<std::uint64_t> submitted_{0};
|
||||
std::atomic<std::uint64_t> completed_{0};
|
||||
std::atomic<std::uint64_t> rejected_{0};
|
||||
bool stop_{false};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@@ -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<std::string>& 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<std::string>& 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<void, std::string>
|
||||
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<void, std::string>
|
||||
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<std::string>* 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<FlagEntry> flags_;
|
||||
std::vector<OptionEntry> options_;
|
||||
std::vector<PosEntry> positionals_;
|
||||
};
|
||||
private:
|
||||
|
||||
struct FlagEntry {
|
||||
std::string lng, sht, desc;
|
||||
bool* out;
|
||||
};
|
||||
struct OptionEntry {
|
||||
std::string lng, sht, desc, def;
|
||||
std::optional<std::string>* out_opt;
|
||||
std::string* out_str;
|
||||
};
|
||||
struct PosEntry {
|
||||
std::string name, desc;
|
||||
std::string* out;
|
||||
};
|
||||
|
||||
std::string program_, description_;
|
||||
std::vector<FlagEntry> flags_;
|
||||
std::vector<OptionEntry> options_;
|
||||
std::vector<PosEntry> 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<std::string> config; // --config
|
||||
// <v>
|
||||
// [[= arg::Positional{}]] std::string input;
|
||||
// };
|
||||
// auto o = Argparse::parse<Opts>(argc, argv); // std::expected<Opts,
|
||||
// string>
|
||||
//
|
||||
// Field → argument: bool → flag, std::string → option with default (the
|
||||
// field's initializer), std::optional<std::string> → 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 <typename Opts>
|
||||
[[nodiscard]] std::expected<Opts, std::string>
|
||||
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<Opts>)
|
||||
{
|
||||
using MT = [:std::meta::type_of(m):];
|
||||
constexpr auto nm = Void::Meta::annotation_of<Name>(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<Short>(m);
|
||||
const std::string sht =
|
||||
sh.has_value() ? (std::string{"-"} + sh->c) : std::string{};
|
||||
constexpr auto hp = Void::Meta::annotation_of<Help>(m);
|
||||
const std::string desc =
|
||||
hp.has_value() ? std::string{hp->text.view()} : std::string{};
|
||||
|
||||
if constexpr (Void::Meta::has_annotation<Positional>(m)) {
|
||||
parser.positional(std::meta::identifier_of(m), desc, out.[:m:]);
|
||||
} else if constexpr (std::same_as<MT, bool>) {
|
||||
parser.flag(lng, sht, desc, out.[:m:]);
|
||||
} else if constexpr (Void::Meta::is_optional_v<MT>) {
|
||||
parser.option(lng, sht, desc, out.[:m:]);
|
||||
} else if constexpr (std::same_as<MT, std::string>) {
|
||||
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
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
@@ -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 <typename T> struct IsOptional : std::false_type {
|
||||
};
|
||||
template <typename U>
|
||||
struct IsOptional<std::optional<U>> : std::true_type {
|
||||
};
|
||||
|
||||
template <typename T> struct IsVector : std::false_type {
|
||||
};
|
||||
template <typename U> struct IsVector<std::vector<U>> : std::true_type {
|
||||
};
|
||||
|
||||
template <typename T> struct IsDuration : std::false_type {
|
||||
};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>> : std::true_type {
|
||||
};
|
||||
|
||||
// Leaf / container shape detection comes from Void::Meta (single
|
||||
// source); Config additionally treats chrono durations as leaves.
|
||||
template <typename T>
|
||||
concept Leaf = std::is_same_v<T, std::string> ||
|
||||
std::is_same_v<T, bool> || std::is_arithmetic_v<T> ||
|
||||
std::is_enum_v<T> || IsDuration<T>::value;
|
||||
std::is_enum_v<T> || Void::Meta::is_duration_v<T>;
|
||||
|
||||
template <typename T>
|
||||
concept BindableAggregate =
|
||||
@@ -86,16 +84,20 @@ namespace Void::Configuration
|
||||
T out{};
|
||||
std::optional<Void::Result::Error> 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<T>)
|
||||
{
|
||||
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<Key>(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<Required>(m);
|
||||
|
||||
if constexpr (BindableAggregate<MT> && !Leaf<MT>) {
|
||||
auto nested = bind_into<MT>(cfg, key);
|
||||
@@ -104,7 +106,7 @@ namespace Void::Configuration
|
||||
} else {
|
||||
out.[:m:] = std::move(*nested);
|
||||
}
|
||||
} else if constexpr (IsOptional<MT>::value) {
|
||||
} else if constexpr (Void::Meta::is_optional_v<MT>) {
|
||||
using U = typename MT::value_type;
|
||||
if (cfg.contains(key)) {
|
||||
auto v = cfg.get_as<U>(key);
|
||||
@@ -114,7 +116,7 @@ namespace Void::Configuration
|
||||
out.[:m:] = std::move(*v);
|
||||
}
|
||||
}
|
||||
} else if constexpr (IsVector<MT>::value) {
|
||||
} else if constexpr (Void::Meta::is_vector_v<MT>) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,15 +4,17 @@
|
||||
#include <Void/Data/Ini.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/Time/Format.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <initializer_list>
|
||||
@@ -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<T>(). 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<int>("net.retries"); // Result<int>
|
||||
///
|
||||
/// 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<T>(). 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<int>("net.retries"); // Result<int>
|
||||
///
|
||||
/// 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<std::string_view> 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<std::string_view> 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<Config,
|
||||
Void::Result::Error>
|
||||
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<Config, Void::Result::Error>
|
||||
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<std::string_view,
|
||||
Void::Result::Error>
|
||||
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<std::string_view, Void::Result::Error>
|
||||
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<char>(std::tolower(
|
||||
static_cast<unsigned char>(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<Config,
|
||||
Void::Result::Error>
|
||||
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<Config,
|
||||
Void::Result::Error>
|
||||
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<Config,
|
||||
Void::Result::Error>
|
||||
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<Config,
|
||||
Void::Result::Error>
|
||||
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 <typename T>
|
||||
[[nodiscard]] Void::Result::Result<T, Void::Result::Error>
|
||||
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<T>(key, it->second);
|
||||
}
|
||||
|
||||
/// Typed lookup with fallback for missing keys. Conversion errors
|
||||
/// on a *present* key still surface the fallback but are logged.
|
||||
template <typename T>
|
||||
[[nodiscard]] T get_or_as(std::string_view key, T fallback) const
|
||||
{
|
||||
auto r = get_as<T>(key);
|
||||
if (r.has_value()) {
|
||||
return std::move(*r);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Key enumeration / subtrees
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// All keys, sorted.
|
||||
[[nodiscard]] std::vector<std::string> keys() const
|
||||
{
|
||||
std::vector<std::string> 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<char>(std::tolower(
|
||||
static_cast<unsigned char>(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<double>(static_cast<long long>(d))) {
|
||||
cfg.values_.insert_or_assign(
|
||||
prefix, std::to_string(static_cast<long long>(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<Config, Void::Result::Error>
|
||||
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<Config, Void::Result::Error>
|
||||
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<Config, Void::Result::Error>
|
||||
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<Config, Void::Result::Error>
|
||||
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 <typename T>
|
||||
[[nodiscard]] Void::Result::Result<T, Void::Result::Error>
|
||||
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<T>(key, it->second);
|
||||
}
|
||||
|
||||
/// Typed lookup with fallback for missing keys. Conversion errors
|
||||
/// on a *present* key still surface the fallback but are logged.
|
||||
template <typename T>
|
||||
[[nodiscard]] T get_or_as(std::string_view key, T fallback) const
|
||||
{
|
||||
auto r = get_as<T>(key);
|
||||
if (r.has_value()) {
|
||||
return std::move(*r);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Key enumeration / subtrees
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// All keys, sorted.
|
||||
[[nodiscard]] std::vector<std::string> keys() const
|
||||
{
|
||||
std::vector<std::string> 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<double>(static_cast<long long>(d))) {
|
||||
cfg.values_.insert_or_assign(
|
||||
prefix,
|
||||
std::to_string(static_cast<long long>(d)));
|
||||
}
|
||||
else {
|
||||
cfg.values_.insert_or_assign(prefix,
|
||||
std::format("{}", d));
|
||||
}
|
||||
}
|
||||
// null: key omitted
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct IsDuration : std::false_type {};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>>
|
||||
: std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
static Void::Result::Result<T, Void::Result::Error>
|
||||
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 <typename T> struct IsDuration : std::false_type {
|
||||
};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>>
|
||||
: std::true_type {
|
||||
};
|
||||
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
return Void::Result::ok(raw);
|
||||
}
|
||||
else if constexpr (std::is_same_v<T, bool>) {
|
||||
std::string lower;
|
||||
lower.reserve(raw.size());
|
||||
for (const char c : raw) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(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<T>) {
|
||||
template <typename T>
|
||||
static Void::Result::Result<T, Void::Result::Error>
|
||||
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<T, std::string>) {
|
||||
return Void::Result::ok(raw);
|
||||
} else if constexpr (std::is_same_v<T, bool>) {
|
||||
std::string lower;
|
||||
lower.reserve(raw.size());
|
||||
for (const char c : raw) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(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<T>) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
if (auto e = Void::Detail::enum_parse<T>(raw);
|
||||
e.has_value()) {
|
||||
return Void::Result::ok(*e);
|
||||
}
|
||||
return fail("no such enumerator");
|
||||
if (auto e = Void::Detail::enum_parse<T>(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<T>::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<T>(*parsed));
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
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<T>::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<T>(*parsed));
|
||||
} else if constexpr (std::is_arithmetic_v<T>) {
|
||||
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<T>) {
|
||||
if (auto bytes = parse_bytes(raw); bytes.has_value()) {
|
||||
return Void::Result::ok(static_cast<T>(*bytes));
|
||||
}
|
||||
return fail("not a number or byte size");
|
||||
}
|
||||
return fail("not a number");
|
||||
} else {
|
||||
static_assert(std::is_same_v<T, std::string>,
|
||||
"unsupported get_as<T> type");
|
||||
}
|
||||
return Void::Result::ok(value);
|
||||
}
|
||||
else {
|
||||
static_assert(std::is_same_v<T, std::string>,
|
||||
"unsupported get_as<T> type");
|
||||
}
|
||||
}
|
||||
|
||||
static std::optional<std::chrono::nanoseconds>
|
||||
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<std::chrono::nanoseconds>
|
||||
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<nanoseconds>(
|
||||
duration<double, typename decltype(unit)::period>{
|
||||
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<std::string, std::string> 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<std::uint64_t>
|
||||
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<std::uint64_t>(number * mult);
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, std::string> values_;
|
||||
};
|
||||
|
||||
} // namespace Void::Configuration
|
||||
@@ -0,0 +1,203 @@
|
||||
#pragma once
|
||||
|
||||
#include <bit>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::BufferPool
|
||||
{
|
||||
|
||||
// ── BufferPool<T>
|
||||
// ───────────────────────────────────────────────────────────── 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 <typename T> 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<T> span() noexcept
|
||||
{
|
||||
return {data(), size_};
|
||||
}
|
||||
[[nodiscard]] std::span<const T> span() const noexcept
|
||||
{
|
||||
return {data(), size_};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
friend class BufferPool;
|
||||
|
||||
Buffer(BufferPool* pool, std::vector<T> 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<T> 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<T> 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<T> storage)
|
||||
{
|
||||
if (storage.empty()) {
|
||||
return;
|
||||
}
|
||||
free_[storage.size()].push_back(std::move(storage));
|
||||
}
|
||||
|
||||
std::unordered_map<std::size_t, std::vector<std::vector<T>>> free_;
|
||||
std::uint64_t allocations_ = 0;
|
||||
std::uint64_t reuses_ = 0;
|
||||
};
|
||||
|
||||
} // namespace Void::BufferPool
|
||||
@@ -0,0 +1,268 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Cache
|
||||
{
|
||||
|
||||
// ── Cache<K, V>
|
||||
// ─────────────────────────────────────────────────────────────── 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 <typename K, typename V> class Cache
|
||||
{
|
||||
public:
|
||||
|
||||
using Clock =
|
||||
std::function<std::chrono::steady_clock::time_point()>;
|
||||
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<Duration> 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<V> 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<Duration> 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<Node>;
|
||||
using Map = std::unordered_map<K, typename List::iterator>;
|
||||
|
||||
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<Duration> 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<Duration> 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
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
|
||||
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 <std::ranges::input_range R>
|
||||
[[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
|
||||
+200
-81
@@ -1,114 +1,233 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <initializer_list>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Void::Flags
|
||||
{
|
||||
|
||||
// ── Flags<E> ─────────────────────────────────────────────────────────────────
|
||||
// Type-safe bitmask wrapper over a scoped enum class E.
|
||||
// E's enumerators must be distinct single-bit values (1, 2, 4, 8, …).
|
||||
// ── Flags<E>
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
// Type-safe bitmask wrapper over a scoped enum class E.
|
||||
// E's enumerators must be distinct single-bit values (1, 2, 4, 8, …).
|
||||
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
class Flags
|
||||
{
|
||||
public:
|
||||
using underlying = std::underlying_type_t<E>;
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
class Flags
|
||||
{
|
||||
public:
|
||||
|
||||
constexpr Flags() noexcept = default;
|
||||
constexpr Flags(E bit) noexcept : bits_{static_cast<underlying>(bit)} {}
|
||||
constexpr explicit Flags(underlying raw) noexcept : bits_{raw} {}
|
||||
constexpr Flags(std::initializer_list<E> list) noexcept
|
||||
{
|
||||
for (const E e : list) bits_ |= static_cast<underlying>(e);
|
||||
}
|
||||
using underlying = std::underlying_type_t<E>;
|
||||
|
||||
// ── query ─────────────────────────────────────────────────────────────────
|
||||
constexpr Flags() noexcept = default;
|
||||
constexpr Flags(E bit) noexcept
|
||||
: bits_{static_cast<underlying>(bit)}
|
||||
{
|
||||
}
|
||||
constexpr explicit Flags(underlying raw) noexcept : bits_{raw} {}
|
||||
constexpr Flags(std::initializer_list<E> list) noexcept
|
||||
{
|
||||
for (const E e : list) {
|
||||
bits_ |= static_cast<underlying>(e);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool test(E bit) const noexcept
|
||||
{
|
||||
return (bits_ & static_cast<underlying>(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<underlying>(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<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
// ── mutation
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
|
||||
constexpr Flags& unset(E bit) noexcept
|
||||
{
|
||||
bits_ &= ~static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
constexpr Flags& set(E bit) noexcept
|
||||
{
|
||||
bits_ |= static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr Flags& toggle(E bit) noexcept
|
||||
{
|
||||
bits_ ^= static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
constexpr Flags& unset(E bit) noexcept
|
||||
{
|
||||
bits_ &= ~static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr void clear() noexcept { bits_ = 0; }
|
||||
constexpr Flags& toggle(E bit) noexcept
|
||||
{
|
||||
bits_ ^= static_cast<underlying>(bit);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// ── operators ─────────────────────────────────────────────────────────────
|
||||
constexpr void clear() noexcept { bits_ = 0; }
|
||||
|
||||
[[nodiscard]] constexpr Flags operator|(Flags o) const noexcept { return Flags{static_cast<underlying>(bits_ | o.bits_)}; }
|
||||
[[nodiscard]] constexpr Flags operator&(Flags o) const noexcept { return Flags{static_cast<underlying>(bits_ & o.bits_)}; }
|
||||
[[nodiscard]] constexpr Flags operator^(Flags o) const noexcept { return Flags{static_cast<underlying>(bits_ ^ o.bits_)}; }
|
||||
[[nodiscard]] constexpr Flags operator~() const noexcept { return Flags{static_cast<underlying>(~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<underlying>(bits_ | o.bits_)};
|
||||
}
|
||||
[[nodiscard]] constexpr Flags operator&(Flags o) const noexcept
|
||||
{
|
||||
return Flags{static_cast<underlying>(bits_ & o.bits_)};
|
||||
}
|
||||
[[nodiscard]] constexpr Flags operator^(Flags o) const noexcept
|
||||
{
|
||||
return Flags{static_cast<underlying>(bits_ ^ o.bits_)};
|
||||
}
|
||||
[[nodiscard]] constexpr Flags operator~() const noexcept
|
||||
{
|
||||
return Flags{static_cast<underlying>(~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<underlying>(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<underlying>(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 <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] constexpr Flags<E> make_flags(std::initializer_list<E> list) noexcept
|
||||
{
|
||||
return Flags<E>{list};
|
||||
}
|
||||
underlying bits_{0};
|
||||
};
|
||||
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] constexpr Flags<E> operator|(E a, E b) noexcept
|
||||
{
|
||||
return Flags<E>{a} | Flags<E>{b};
|
||||
}
|
||||
// ── make_flags — convenience factory
|
||||
// ─────────────────────────────────────────
|
||||
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] constexpr Flags<E>
|
||||
make_flags(std::initializer_list<E> list) noexcept
|
||||
{
|
||||
return Flags<E>{list};
|
||||
}
|
||||
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] constexpr Flags<E> operator|(E a, E b) noexcept
|
||||
{
|
||||
return Flags<E>{a} | Flags<E>{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 <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] std::string to_string(Flags<E> f, std::string_view sep = "|")
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& [value, name] : Void::Meta::enum_entries<E>()) {
|
||||
if (f.test(value)) {
|
||||
if (!out.empty()) {
|
||||
out += sep;
|
||||
}
|
||||
out += name;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Parse a `sep`-separated list of enumerator names into a Flags<E>.
|
||||
/// Unknown names are ignored.
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] Flags<E> parse(std::string_view text, char sep = '|')
|
||||
{
|
||||
Flags<E> 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<E>(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
|
||||
@@ -0,0 +1,351 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#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 <class> inline constexpr bool is_optional_v = false;
|
||||
template <class U>
|
||||
inline constexpr bool is_optional_v<std::optional<U>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_vector_v = false;
|
||||
template <class U> inline constexpr bool is_vector_v<std::vector<U>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_string_map_v = false;
|
||||
template <class U>
|
||||
inline constexpr bool is_string_map_v<std::map<std::string, U>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_duration_v = false;
|
||||
template <class R, class P>
|
||||
inline constexpr bool is_duration_v<std::chrono::duration<R, P>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_time_point_v = false;
|
||||
template <class C, class D>
|
||||
inline constexpr bool is_time_point_v<std::chrono::time_point<C, D>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_variant_v = false;
|
||||
template <class... Ts>
|
||||
inline constexpr bool is_variant_v<std::variant<Ts...>> = true;
|
||||
|
||||
template <class> inline constexpr bool is_std_array_v = false;
|
||||
template <class U, std::size_t N>
|
||||
inline constexpr bool is_std_array_v<std::array<U, N>> = 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 <class> inline constexpr bool is_map_v = false;
|
||||
template <class K, class V, class C, class A>
|
||||
inline constexpr bool is_map_v<std::map<K, V, C, A>> =
|
||||
!std::same_as<K, std::string>;
|
||||
template <class K, class V, class H, class E, class A>
|
||||
inline constexpr bool is_map_v<std::unordered_map<K, V, H, E, A>> =
|
||||
!std::same_as<K, std::string>;
|
||||
|
||||
template <class T>
|
||||
concept Leaf = std::same_as<T, bool> || std::is_arithmetic_v<T> ||
|
||||
std::is_enum_v<T> || std::same_as<T, std::string>;
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
|
||||
namespace meta = std::meta;
|
||||
|
||||
// ── member walk (the single reflection of a struct's data members) ────
|
||||
template <typename T>
|
||||
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 <typename T> [[nodiscard]] consteval std::size_t field_count()
|
||||
{
|
||||
return members_v<T>.size();
|
||||
}
|
||||
|
||||
/// A class type with at least one reflectable data member.
|
||||
template <class T>
|
||||
concept Struct =
|
||||
(std::is_class_v<T> || std::is_union_v<T>) && (field_count<T>() > 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 <typename T>
|
||||
[[nodiscard]] std::vector<std::string_view> field_names()
|
||||
{
|
||||
std::vector<std::string_view> out;
|
||||
out.reserve(field_count<T>());
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
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 <typename T, typename Fn> void for_each_field(T&& obj, Fn&& fn)
|
||||
{
|
||||
using U = std::remove_reference_t<T>;
|
||||
template for (constexpr auto m : members_v<U>)
|
||||
{
|
||||
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 <typename Tag>
|
||||
[[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 <typename Tag>
|
||||
[[nodiscard]] consteval std::optional<Tag> annotation_of(meta::info m)
|
||||
{
|
||||
for (meta::info a : meta::annotations_of_with_type(m, ^^Tag)) {
|
||||
return meta::extract<Tag>(a);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
/// The (unqualified) name of a type, e.g. type_name<Foo>() == "Foo".
|
||||
template <typename T> [[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 <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
inline constexpr std::size_t enum_count = meta::enumerators_of(^^E).size();
|
||||
|
||||
/// The enumerator values of E (declaration order).
|
||||
template <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] consteval std::array<E, enum_count<E>> enum_values()
|
||||
{
|
||||
std::array<E, enum_count<E>> 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 <typename E>
|
||||
requires std::is_enum_v<E>
|
||||
[[nodiscard]] std::array<std::pair<E, std::string_view>, enum_count<E>>
|
||||
enum_entries()
|
||||
{
|
||||
std::array<std::pair<E, std::string_view>, enum_count<E>> 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 <class T>
|
||||
concept Struct = false;
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
// ── repr (diagnostic rendering) ───────────────────────────────────────
|
||||
// 1. std::formatter<T> → std::format. 2. a .format() method. 3. reflect
|
||||
// the data members as `Type{a: 1, b: 2}`. 4. "<unrepresentable>".
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value);
|
||||
|
||||
template <typename T>
|
||||
concept Formattable = std::formattable<T, char>;
|
||||
|
||||
template <typename T>
|
||||
concept HasFormatMethod = requires(const T& v) {
|
||||
{ v.format() } -> std::convertible_to<std::string>;
|
||||
};
|
||||
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
template <typename T> [[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<T>)
|
||||
{
|
||||
if (!first) {
|
||||
out += ", ";
|
||||
}
|
||||
out += meta::identifier_of(m);
|
||||
out += ": ";
|
||||
out += repr(obj.[:m:]);
|
||||
first = false;
|
||||
}
|
||||
out += '}';
|
||||
return out;
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value)
|
||||
{
|
||||
if constexpr (Formattable<T>) {
|
||||
return std::format("{}", value);
|
||||
} else if constexpr (HasFormatMethod<T>) {
|
||||
return std::string{value.format()};
|
||||
}
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
else if constexpr (std::is_class_v<T> || std::is_union_v<T>) {
|
||||
return reflect_struct(value);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return "<unrepresentable>";
|
||||
}
|
||||
}
|
||||
|
||||
// ── generic algorithms over data members ──────────────────────────────
|
||||
#ifdef VOID_HAS_META_REFLECTION
|
||||
|
||||
/// Member-wise equality for reflectable structs (recurses on members).
|
||||
template <typename T> [[nodiscard]] bool equal(const T& a, const T& b)
|
||||
{
|
||||
if constexpr (Struct<T> && !Leaf<T>) {
|
||||
bool eq = true;
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
if (eq && !equal(a.[:m:], b.[:m:])) {
|
||||
eq = false;
|
||||
}
|
||||
}
|
||||
return eq;
|
||||
} else {
|
||||
return a == b;
|
||||
}
|
||||
}
|
||||
|
||||
/// Lexicographic member-wise ordering for reflectable structs.
|
||||
template <typename T>
|
||||
[[nodiscard]] std::strong_ordering compare(const T& a, const T& b)
|
||||
{
|
||||
if constexpr (Struct<T> && !Leaf<T>) {
|
||||
std::strong_ordering result = std::strong_ordering::equal;
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
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 <typename T> [[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<T> && !Leaf<T>) {
|
||||
std::uint64_t h = 0xcbf29ce484222325ULL;
|
||||
template for (constexpr auto m : members_v<T>)
|
||||
{
|
||||
h = mix(h, hash(v.[:m:]));
|
||||
}
|
||||
return h;
|
||||
} else {
|
||||
return static_cast<std::uint64_t>(std::hash<T>{}(v));
|
||||
}
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
} // namespace Void::Meta
|
||||
+213
-112
@@ -1,5 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
@@ -9,130 +13,227 @@
|
||||
namespace Void::Csv
|
||||
{
|
||||
|
||||
using Row = std::vector<std::string>;
|
||||
using Table = std::vector<Row>;
|
||||
using Row = std::vector<std::string>;
|
||||
using Table = std::vector<Row>;
|
||||
|
||||
// ── 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<std::size_t>
|
||||
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<std::size_t>
|
||||
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<std::string_view>
|
||||
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<std::string_view>
|
||||
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<CsvWithHeader>
|
||||
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<CsvWithHeader>
|
||||
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 <typename F>
|
||||
[[nodiscard]] std::string cell_to_string(const F& f)
|
||||
{
|
||||
if constexpr (std::same_as<F, std::string>) {
|
||||
return f;
|
||||
} else if constexpr (std::same_as<F, bool>) {
|
||||
return f ? "true" : "false";
|
||||
} else if constexpr (std::is_arithmetic_v<F>) {
|
||||
return std::format("{}", f);
|
||||
} else {
|
||||
return Void::Meta::repr(f);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
[[nodiscard]] bool cell_from_string(std::string_view s, F& f)
|
||||
{
|
||||
if constexpr (std::same_as<F, std::string>) {
|
||||
f = std::string{s};
|
||||
return true;
|
||||
} else if constexpr (std::same_as<F, bool>) {
|
||||
f = (s == "true" || s == "1");
|
||||
return true;
|
||||
} else if constexpr (std::is_integral_v<F>) {
|
||||
return std::from_chars(s.data(), s.data() + s.size(), f).ec ==
|
||||
std::errc{};
|
||||
} else if constexpr (std::is_floating_point_v<F>) {
|
||||
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 <typename T> [[nodiscard]] Row header_row()
|
||||
{
|
||||
Row h;
|
||||
for (auto name : Void::Meta::field_names<T>()) {
|
||||
h.emplace_back(name);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/// Stringify a struct into a CSV Row (declaration order).
|
||||
template <typename T> [[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 <typename T>
|
||||
[[nodiscard]] std::optional<T> 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<T>{std::move(out)} : std::nullopt;
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_META_REFLECTION
|
||||
|
||||
} // namespace Void::Csv
|
||||
+942
-379
File diff suppressed because it is too large.
Load diff
+536
-334
@@ -1,9 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/Time/Format.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
@@ -11,8 +16,10 @@
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
@@ -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 <typename T>
|
||||
concept HasMemberToJson = requires(const T& t) {
|
||||
{ t.to_json() } -> std::same_as<Value>;
|
||||
};
|
||||
// ── customization point
|
||||
// ───────────────────────────────────────────────────────
|
||||
|
||||
template <typename T>
|
||||
concept HasMemberFromJson = requires(const Value& v) {
|
||||
{ T::from_json(v) } -> std::same_as<std::expected<T, ReflectError>>;
|
||||
};
|
||||
template <typename T>
|
||||
concept HasMemberToJson = requires(const T& t) {
|
||||
{ t.to_json() } -> std::same_as<Value>;
|
||||
};
|
||||
|
||||
// ── supported leaf / container shapes ─────────────────────────────────────────
|
||||
template <typename T>
|
||||
concept HasMemberFromJson = requires(const Value& v) {
|
||||
{ T::from_json(v) } -> std::same_as<std::expected<T, ReflectError>>;
|
||||
};
|
||||
|
||||
namespace ReflectDetail
|
||||
{
|
||||
template <typename T>
|
||||
struct IsOptional : std::false_type {};
|
||||
template <typename U>
|
||||
struct IsOptional<std::optional<U>> : std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
struct IsVector : std::false_type {};
|
||||
template <typename U>
|
||||
struct IsVector<std::vector<U>> : std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
struct IsStringMap : std::false_type {};
|
||||
template <typename U>
|
||||
struct IsStringMap<std::map<std::string, U>> : std::true_type {};
|
||||
} // namespace ReflectDetail
|
||||
// ── supported leaf / container shapes (single source: Void::Meta)
|
||||
// ─────────────
|
||||
|
||||
#ifdef VOID_HAS_JSON_REFLECTION
|
||||
|
||||
template <typename T>
|
||||
concept ReflectableAggregate =
|
||||
std::is_aggregate_v<T> && !std::is_array_v<T> &&
|
||||
std::is_default_constructible_v<T>;
|
||||
template <typename T>
|
||||
concept ReflectableAggregate =
|
||||
std::is_aggregate_v<T> && !std::is_array_v<T> &&
|
||||
std::is_default_constructible_v<T>;
|
||||
|
||||
#else
|
||||
|
||||
template <typename T>
|
||||
concept ReflectableAggregate = false;
|
||||
template <typename T>
|
||||
concept ReflectableAggregate = false;
|
||||
|
||||
#endif
|
||||
|
||||
template <typename T>
|
||||
concept JsonConvertible =
|
||||
HasMemberToJson<T> || std::same_as<T, bool> || std::is_arithmetic_v<T> ||
|
||||
std::is_enum_v<T> || std::same_as<T, std::string> ||
|
||||
ReflectDetail::IsOptional<T>::value || ReflectDetail::IsVector<T>::value ||
|
||||
ReflectDetail::IsStringMap<T>::value || ReflectableAggregate<T>;
|
||||
template <typename T>
|
||||
concept JsonConvertible =
|
||||
HasMemberToJson<T> || std::same_as<T, bool> ||
|
||||
std::is_arithmetic_v<T> || std::is_enum_v<T> ||
|
||||
std::same_as<T, std::string> || Void::Meta::is_optional_v<T> ||
|
||||
Void::Meta::is_vector_v<T> || Void::Meta::is_string_map_v<T> ||
|
||||
Void::Meta::is_duration_v<T> || Void::Meta::is_time_point_v<T> ||
|
||||
Void::Meta::is_variant_v<T> || Void::Meta::is_std_array_v<T> ||
|
||||
Void::Meta::is_map_v<T> || ReflectableAggregate<T>;
|
||||
|
||||
// Anything serializable through this header (customized or reflected).
|
||||
template <typename T>
|
||||
concept Reflectable = JsonConvertible<T>;
|
||||
// Anything serializable through this header (customized or reflected).
|
||||
template <typename T>
|
||||
concept Reflectable = JsonConvertible<T>;
|
||||
|
||||
// ── to_json ───────────────────────────────────────────────────────────────────
|
||||
// ── to_json
|
||||
// ───────────────────────────────────────────────────────────────────
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] Value to_json(const T& v);
|
||||
template <Reflectable T> [[nodiscard]] Value to_json(const T& v);
|
||||
|
||||
namespace ReflectDetail
|
||||
{
|
||||
template <typename T>
|
||||
Value leaf_to_json(const T& v)
|
||||
{
|
||||
if constexpr (HasMemberToJson<T>) {
|
||||
return v.to_json();
|
||||
}
|
||||
else if constexpr (std::same_as<T, bool>) {
|
||||
return Value{v};
|
||||
}
|
||||
else if constexpr (std::is_enum_v<T>) {
|
||||
namespace ReflectDetail
|
||||
{
|
||||
template <typename T> Value leaf_to_json(const T& v)
|
||||
{
|
||||
if constexpr (HasMemberToJson<T>) {
|
||||
return v.to_json();
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
return Value{v};
|
||||
} else if constexpr (std::is_enum_v<T>) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
// Enum values serialize by name — stable across binary versions.
|
||||
return Value{Void::Detail::enum_name(v)};
|
||||
// Enum values serialize by name — stable across binary
|
||||
// versions.
|
||||
return Value{Void::Detail::enum_name(v)};
|
||||
#else
|
||||
return Value{static_cast<double>(
|
||||
static_cast<std::underlying_type_t<T>>(v))};
|
||||
return Value{static_cast<double>(
|
||||
static_cast<std::underlying_type_t<T>>(v))};
|
||||
#endif
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
return Value{static_cast<double>(v)};
|
||||
}
|
||||
else if constexpr (std::same_as<T, std::string>) {
|
||||
return Value{v};
|
||||
}
|
||||
else if constexpr (IsOptional<T>::value) {
|
||||
return v ? Json::to_json(*v) : Value{nullptr};
|
||||
}
|
||||
else if constexpr (IsVector<T>::value) {
|
||||
auto arr = Json::array();
|
||||
arr.as_array().reserve(v.size());
|
||||
for (const auto& e : v) {
|
||||
arr.as_array().push_back(Json::to_json(e));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
else if constexpr (IsStringMap<T>::value) {
|
||||
auto obj = Json::object();
|
||||
for (const auto& [k, e] : v) {
|
||||
obj.as_object().emplace_back(k, Json::to_json(e));
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
else {
|
||||
static_assert(ReflectableAggregate<T>,
|
||||
"type is not serializable via Json reflection");
|
||||
} else if constexpr (std::is_arithmetic_v<T>) {
|
||||
return Value{static_cast<double>(v)};
|
||||
} else if constexpr (std::same_as<T, std::string>) {
|
||||
return Value{v};
|
||||
} else if constexpr (Void::Meta::is_optional_v<T>) {
|
||||
return v ? Json::to_json(*v) : Value{nullptr};
|
||||
} else if constexpr (Void::Meta::is_vector_v<T>) {
|
||||
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<T>) {
|
||||
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<T>) {
|
||||
return Value{Void::Time::duration_to_string(v)};
|
||||
} else if constexpr (Void::Meta::is_time_point_v<T>) {
|
||||
// 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<std::chrono::milliseconds>(
|
||||
v.time_since_epoch()))};
|
||||
} else if constexpr (Void::Meta::is_std_array_v<T>) {
|
||||
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<T>) {
|
||||
// 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<T>) {
|
||||
return std::visit(
|
||||
[](const auto& alt) -> Value {
|
||||
using Alt = std::decay_t<decltype(alt)>;
|
||||
auto obj = Json::object();
|
||||
obj.as_object().emplace_back(
|
||||
"type", Value{Void::Meta::type_name<Alt>()});
|
||||
obj.as_object().emplace_back("value",
|
||||
Json::to_json(alt));
|
||||
return obj;
|
||||
},
|
||||
v);
|
||||
} else {
|
||||
static_assert(ReflectableAggregate<T>,
|
||||
"type is not serializable via Json reflection");
|
||||
#ifdef VOID_HAS_JSON_REFLECTION
|
||||
auto obj = Json::object();
|
||||
static constexpr auto members = std::define_static_array(
|
||||
std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::current()));
|
||||
template for (constexpr auto m : members) {
|
||||
obj.as_object().emplace_back(
|
||||
std::string{std::meta::identifier_of(m)},
|
||||
Json::to_json(v.[:m:]));
|
||||
}
|
||||
return obj;
|
||||
auto obj = Json::object();
|
||||
template for (constexpr auto m : Void::Meta::members_v<T>)
|
||||
{
|
||||
if constexpr (!Void::Meta::has_annotation<Skip>(m)) {
|
||||
if constexpr (Void::Meta::has_annotation<Flatten>(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<Rename>(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 <Reflectable T>
|
||||
[[nodiscard]] Value to_json(const T& v)
|
||||
{
|
||||
return ReflectDetail::leaf_to_json(v);
|
||||
}
|
||||
template <Reflectable T> [[nodiscard]] Value to_json(const T& v)
|
||||
{
|
||||
return ReflectDetail::leaf_to_json(v);
|
||||
}
|
||||
|
||||
// ── from_json ─────────────────────────────────────────────────────────────────
|
||||
// ── from_json
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j);
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j);
|
||||
|
||||
namespace ReflectDetail
|
||||
{
|
||||
[[nodiscard]] inline ReflectError nest(std::string_view field,
|
||||
ReflectError inner)
|
||||
{
|
||||
if (inner.field.empty()) {
|
||||
inner.field = std::string{field};
|
||||
}
|
||||
else {
|
||||
inner.field = std::string{field} + "." + inner.field;
|
||||
}
|
||||
return inner;
|
||||
}
|
||||
namespace ReflectDetail
|
||||
{
|
||||
[[nodiscard]] inline ReflectError nest(std::string_view field,
|
||||
ReflectError inner)
|
||||
{
|
||||
if (inner.field.empty()) {
|
||||
inner.field = std::string{field};
|
||||
} else {
|
||||
inner.field = std::string{field} + "." + inner.field;
|
||||
}
|
||||
return inner;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::expected<T, ReflectError> leaf_from_json(const Value& j)
|
||||
{
|
||||
if constexpr (HasMemberFromJson<T>) {
|
||||
return T::from_json(j);
|
||||
}
|
||||
else if constexpr (std::same_as<T, bool>) {
|
||||
if (!j.is_bool()) {
|
||||
return std::unexpected{ReflectError{"", "expected bool"}};
|
||||
}
|
||||
return j.as_bool();
|
||||
}
|
||||
else if constexpr (std::is_enum_v<T>) {
|
||||
template <typename T>
|
||||
std::expected<T, ReflectError> leaf_from_json(const Value& j)
|
||||
{
|
||||
if constexpr (HasMemberFromJson<T>) {
|
||||
return T::from_json(j);
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
if (!j.is_bool()) {
|
||||
return std::unexpected{ReflectError{"", "expected bool"}};
|
||||
}
|
||||
return j.as_bool();
|
||||
} else if constexpr (std::is_enum_v<T>) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum name string"}};
|
||||
}
|
||||
auto parsed = Void::Detail::enum_parse<T>(j.as_string());
|
||||
if (!parsed) {
|
||||
return std::unexpected{ReflectError{
|
||||
"", "unknown enumerator '" + j.as_string() + "'"}};
|
||||
}
|
||||
return *parsed;
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum name string"}};
|
||||
}
|
||||
auto parsed = Void::Detail::enum_parse<T>(j.as_string());
|
||||
if (!parsed) {
|
||||
return std::unexpected{ReflectError{
|
||||
"", "unknown enumerator '" + j.as_string() + "'"}};
|
||||
}
|
||||
return *parsed;
|
||||
#else
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum number"}};
|
||||
}
|
||||
return static_cast<T>(
|
||||
static_cast<std::underlying_type_t<T>>(j.as_number()));
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected enum number"}};
|
||||
}
|
||||
return static_cast<T>(
|
||||
static_cast<std::underlying_type_t<T>>(j.as_number()));
|
||||
#endif
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{ReflectError{"", "expected number"}};
|
||||
}
|
||||
return static_cast<T>(j.as_number());
|
||||
}
|
||||
else if constexpr (std::same_as<T, std::string>) {
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{ReflectError{"", "expected string"}};
|
||||
}
|
||||
return j.as_string();
|
||||
}
|
||||
else if constexpr (IsOptional<T>::value) {
|
||||
using U = typename T::value_type;
|
||||
if (j.is_null()) {
|
||||
return T{std::nullopt};
|
||||
}
|
||||
auto inner = Json::from_json<U>(j);
|
||||
if (!inner) {
|
||||
return std::unexpected{std::move(inner).error()};
|
||||
}
|
||||
return T{std::move(*inner)};
|
||||
}
|
||||
else if constexpr (IsVector<T>::value) {
|
||||
using U = typename T::value_type;
|
||||
if (!j.is_array()) {
|
||||
return std::unexpected{ReflectError{"", "expected array"}};
|
||||
}
|
||||
T out;
|
||||
out.reserve(j.as_array().size());
|
||||
std::size_t index = 0;
|
||||
for (const auto& e : j.as_array()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{nest(
|
||||
"[" + std::to_string(index) + "]",
|
||||
std::move(inner).error())};
|
||||
}
|
||||
out.push_back(std::move(*inner));
|
||||
++index;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
else if constexpr (IsStringMap<T>::value) {
|
||||
using U = typename T::mapped_type;
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out;
|
||||
for (const auto& [k, e] : j.as_object()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{nest(k, std::move(inner).error())};
|
||||
}
|
||||
out.emplace(k, std::move(*inner));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
else {
|
||||
static_assert(ReflectableAggregate<T>,
|
||||
"type is not deserializable via Json reflection");
|
||||
} else if constexpr (std::is_arithmetic_v<T>) {
|
||||
if (!j.is_number()) {
|
||||
return std::unexpected{ReflectError{"", "expected number"}};
|
||||
}
|
||||
return static_cast<T>(j.as_number());
|
||||
} else if constexpr (std::same_as<T, std::string>) {
|
||||
if (!j.is_string()) {
|
||||
return std::unexpected{ReflectError{"", "expected string"}};
|
||||
}
|
||||
return j.as_string();
|
||||
} else if constexpr (Void::Meta::is_optional_v<T>) {
|
||||
using U = typename T::value_type;
|
||||
if (j.is_null()) {
|
||||
return T{std::nullopt};
|
||||
}
|
||||
auto inner = Json::from_json<U>(j);
|
||||
if (!inner) {
|
||||
return std::unexpected{std::move(inner).error()};
|
||||
}
|
||||
return T{std::move(*inner)};
|
||||
} else if constexpr (Void::Meta::is_vector_v<T>) {
|
||||
using U = typename T::value_type;
|
||||
if (!j.is_array()) {
|
||||
return std::unexpected{ReflectError{"", "expected array"}};
|
||||
}
|
||||
T out;
|
||||
out.reserve(j.as_array().size());
|
||||
std::size_t index = 0;
|
||||
for (const auto& e : j.as_array()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{
|
||||
nest("[" + std::to_string(index) + "]",
|
||||
std::move(inner).error())};
|
||||
}
|
||||
out.push_back(std::move(*inner));
|
||||
++index;
|
||||
}
|
||||
return out;
|
||||
} else if constexpr (Void::Meta::is_string_map_v<T>) {
|
||||
using U = typename T::mapped_type;
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out;
|
||||
for (const auto& [k, e] : j.as_object()) {
|
||||
auto inner = Json::from_json<U>(e);
|
||||
if (!inner) {
|
||||
return std::unexpected{
|
||||
nest(k, std::move(inner).error())};
|
||||
}
|
||||
out.emplace(k, std::move(*inner));
|
||||
}
|
||||
return out;
|
||||
} else if constexpr (Void::Meta::is_duration_v<T>) {
|
||||
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<T>(*parsed);
|
||||
} else if constexpr (Void::Meta::is_time_point_v<T>) {
|
||||
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<typename T::duration>(
|
||||
*parsed)};
|
||||
} else if constexpr (Void::Meta::is_std_array_v<T>) {
|
||||
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<T>;
|
||||
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<U>(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<T>) {
|
||||
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<K>(*kf);
|
||||
if (!key) {
|
||||
return std::unexpected{
|
||||
nest(where, std::move(key).error())};
|
||||
}
|
||||
auto val = Json::from_json<MV>(*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<T>) {
|
||||
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<T> result;
|
||||
std::optional<ReflectError> failure;
|
||||
[&]<std::size_t... Is>(std::index_sequence<Is...>) {
|
||||
(
|
||||
[&] {
|
||||
if (result || failure) {
|
||||
return;
|
||||
}
|
||||
using Alt = std::variant_alternative_t<Is, T>;
|
||||
if (Void::Meta::type_name<Alt>() == tag) {
|
||||
auto inner = Json::from_json<Alt>(*vf);
|
||||
if (!inner) {
|
||||
failure = std::move(inner).error();
|
||||
} else {
|
||||
result = T{std::in_place_index<Is>,
|
||||
std::move(*inner)};
|
||||
}
|
||||
}
|
||||
}(),
|
||||
...);
|
||||
}(std::make_index_sequence<std::variant_size_v<T>>{});
|
||||
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<T>,
|
||||
"type is not deserializable via Json reflection");
|
||||
#ifdef VOID_HAS_JSON_REFLECTION
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out{};
|
||||
static constexpr auto members = std::define_static_array(
|
||||
std::meta::nonstatic_data_members_of(
|
||||
^^T, std::meta::access_context::current()));
|
||||
std::optional<ReflectError> failure;
|
||||
template for (constexpr auto m : members) {
|
||||
if (!failure) {
|
||||
constexpr auto name = std::meta::identifier_of(m);
|
||||
using MT = [:std::meta::type_of(m):];
|
||||
if (const Value* field = j.find(name)) {
|
||||
auto inner = Json::from_json<MT>(*field);
|
||||
if (!inner) {
|
||||
failure = nest(name, std::move(inner).error());
|
||||
}
|
||||
else {
|
||||
out.[:m:] = std::move(*inner);
|
||||
}
|
||||
}
|
||||
// absent field: keep the default-initialized value
|
||||
}
|
||||
}
|
||||
if (failure) {
|
||||
return std::unexpected{std::move(*failure)};
|
||||
}
|
||||
return out;
|
||||
if (!j.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected object"}};
|
||||
}
|
||||
T out{};
|
||||
std::optional<ReflectError> failure;
|
||||
template for (constexpr auto m : Void::Meta::members_v<T>)
|
||||
{
|
||||
if (!failure) {
|
||||
if constexpr (!Void::Meta::has_annotation<Skip>(m)) {
|
||||
using MT = [:std::meta::type_of(m):];
|
||||
if constexpr (Void::Meta::has_annotation<Flatten>(
|
||||
m)) {
|
||||
// Read the nested object's keys from this
|
||||
// object.
|
||||
auto inner = Json::from_json<MT>(j);
|
||||
if (!inner) {
|
||||
failure = std::move(inner).error();
|
||||
} else {
|
||||
out.[:m:] = std::move(*inner);
|
||||
}
|
||||
} else {
|
||||
constexpr auto rn =
|
||||
Void::Meta::annotation_of<Rename>(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<MT>(*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 <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j)
|
||||
{
|
||||
return ReflectDetail::leaf_from_json<T>(j);
|
||||
}
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError> from_json(const Value& j)
|
||||
{
|
||||
return ReflectDetail::leaf_from_json<T>(j);
|
||||
}
|
||||
|
||||
// ── versioned envelope + migrations ───────────────────────────────────────────
|
||||
// ── versioned envelope + migrations
|
||||
// ───────────────────────────────────────────
|
||||
|
||||
// Specialize to bump a state type's schema version:
|
||||
// template <> struct Void::Json::StateTraits<MyState> {
|
||||
// static constexpr std::uint32_t version = 3;
|
||||
// };
|
||||
template <typename T>
|
||||
struct StateTraits {
|
||||
static constexpr std::uint32_t version = 1;
|
||||
};
|
||||
// Specialize to bump a state type's schema version:
|
||||
// template <> struct Void::Json::StateTraits<MyState> {
|
||||
// static constexpr std::uint32_t version = 3;
|
||||
// };
|
||||
template <typename T> struct StateTraits {
|
||||
static constexpr std::uint32_t version = 1;
|
||||
};
|
||||
|
||||
// Ordered chain of per-version JSON transforms. Each step upgrades the bare
|
||||
// "data" payload from `from_version` to `from_version + 1`.
|
||||
class MigrationChain
|
||||
{
|
||||
public:
|
||||
using Step = std::function<Value(Value)>;
|
||||
// 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<Value(Value)>;
|
||||
|
||||
[[nodiscard]] std::expected<Value, ReflectError>
|
||||
migrate(Value data, std::uint32_t from, std::uint32_t to) const
|
||||
{
|
||||
while (from < to) {
|
||||
auto it = steps_.find(from);
|
||||
if (it == steps_.end()) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "no migration step from version " +
|
||||
std::to_string(from)}};
|
||||
}
|
||||
data = it->second(std::move(data));
|
||||
++from;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
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<Value, ReflectError>
|
||||
migrate(Value data, std::uint32_t from, std::uint32_t to) const
|
||||
{
|
||||
while (from < to) {
|
||||
auto it = steps_.find(from);
|
||||
if (it == steps_.end()) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "no migration step from version " +
|
||||
std::to_string(from)}};
|
||||
}
|
||||
data = it->second(std::move(data));
|
||||
++from;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private:
|
||||
std::map<std::uint32_t, Step> steps_;
|
||||
};
|
||||
[[nodiscard]] bool empty() const noexcept { return steps_.empty(); }
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] Value to_versioned_json(const T& v)
|
||||
{
|
||||
auto envelope = object();
|
||||
envelope.as_object().emplace_back(
|
||||
"__version", Value{static_cast<double>(StateTraits<T>::version)});
|
||||
envelope.as_object().emplace_back("data", to_json(v));
|
||||
return envelope;
|
||||
}
|
||||
private:
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError>
|
||||
from_versioned_json(const Value& envelope,
|
||||
const MigrationChain& migrations = {})
|
||||
{
|
||||
if (!envelope.is_object()) {
|
||||
return std::unexpected{ReflectError{"", "expected envelope object"}};
|
||||
}
|
||||
const Value* version = envelope.find("__version");
|
||||
const Value* data = envelope.find("data");
|
||||
if (!version || !version->is_number() || !data) {
|
||||
return std::unexpected{
|
||||
ReflectError{"__version", "malformed versioned envelope"}};
|
||||
}
|
||||
const auto from = static_cast<std::uint32_t>(version->as_number());
|
||||
constexpr auto to = StateTraits<T>::version;
|
||||
if (from > to) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "stored version " + std::to_string(from) +
|
||||
" is newer than supported version " +
|
||||
std::to_string(to)}};
|
||||
}
|
||||
if (from == to) {
|
||||
return from_json<T>(*data);
|
||||
}
|
||||
auto migrated = migrations.migrate(*data, from, to);
|
||||
if (!migrated) {
|
||||
return std::unexpected{std::move(migrated).error()};
|
||||
}
|
||||
return from_json<T>(*migrated);
|
||||
}
|
||||
std::map<std::uint32_t, State> steps_;
|
||||
};
|
||||
|
||||
template <Reflectable T> [[nodiscard]] Value to_versioned_json(const T& v)
|
||||
{
|
||||
auto envelope = object();
|
||||
envelope.as_object().emplace_back(
|
||||
"__version", Value{static_cast<double>(StateTraits<T>::version)});
|
||||
envelope.as_object().emplace_back("data", to_json(v));
|
||||
return envelope;
|
||||
}
|
||||
|
||||
template <Reflectable T>
|
||||
[[nodiscard]] std::expected<T, ReflectError>
|
||||
from_versioned_json(const Value& envelope,
|
||||
const MigrationChain& migrations = {})
|
||||
{
|
||||
if (!envelope.is_object()) {
|
||||
return std::unexpected{
|
||||
ReflectError{"", "expected envelope object"}};
|
||||
}
|
||||
const Value* version = envelope.find("__version");
|
||||
const Value* data = envelope.find("data");
|
||||
if (!version || !version->is_number() || !data) {
|
||||
return std::unexpected{
|
||||
ReflectError{"__version", "malformed versioned envelope"}};
|
||||
}
|
||||
const auto from = static_cast<std::uint32_t>(version->as_number());
|
||||
constexpr auto to = StateTraits<T>::version;
|
||||
if (from > to) {
|
||||
return std::unexpected{ReflectError{
|
||||
"__version", "stored version " + std::to_string(from) +
|
||||
" is newer than supported version " +
|
||||
std::to_string(to)}};
|
||||
}
|
||||
if (from == to) {
|
||||
return from_json<T>(*data);
|
||||
}
|
||||
auto migrated = migrations.migrate(*data, from, to);
|
||||
if (!migrated) {
|
||||
return std::unexpected{std::move(migrated).error()};
|
||||
}
|
||||
return from_json<T>(*migrated);
|
||||
}
|
||||
|
||||
} // namespace Void::Json
|
||||
@@ -3,7 +3,7 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <atomic>
|
||||
|
||||
@@ -2,29 +2,21 @@
|
||||
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<EdgeInfo> 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<const StateInfo> 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;
|
||||
}
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Detail/TypeName.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// 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 <typename Derived> struct EventEntry {
|
||||
const std::type_info* type{nullptr};
|
||||
std::function<bool(Derived&, const std::any&)> guard;
|
||||
std::function<Coro::Task<void>(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 <typename Derived> struct TransitionTable {
|
||||
std::vector<EventEntry<Derived>> 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<const std::type_info*> deferred;
|
||||
// Entry/exit actions (run by the reactive loop around the state).
|
||||
std::function<Coro::Task<void>(Derived&)> enter_action;
|
||||
std::function<Coro::Task<void>(Derived&)> exit_action;
|
||||
};
|
||||
|
||||
/// Fluent builder for one event row: `on.event<E>().guard(..).action(..)
|
||||
/// .to<S>()` (or `.finish(v)` / `.fail(v)`).
|
||||
template <typename Derived, typename E> class EventClause
|
||||
{
|
||||
public:
|
||||
|
||||
explicit EventClause(TransitionTable<Derived>& table)
|
||||
: m_table(&table)
|
||||
{
|
||||
}
|
||||
|
||||
EventClause& guard(std::function<bool(Derived&, const E&)> g)
|
||||
{
|
||||
m_guard = std::move(g);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventClause&
|
||||
action(std::function<Coro::Task<void>(Derived&, const E&)> a)
|
||||
{
|
||||
m_action = std::move(a);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventClause& action(std::function<void(Derived&, const E&)> a)
|
||||
{
|
||||
m_action = [a = std::move(a)](Derived& d,
|
||||
const E& e) -> Coro::Task<void> {
|
||||
a(d, e);
|
||||
co_return;
|
||||
};
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename S> void to()
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(Derived::States::template contains<S>(),
|
||||
"to<S>: S is not in this machine's "
|
||||
"States<...> list");
|
||||
}
|
||||
commit(Step::transition(typeid(S)), type_name<S>());
|
||||
}
|
||||
|
||||
void finish()
|
||||
requires std::is_void_v<SuccessOf<Derived>>
|
||||
{
|
||||
commit(Step::success(std::any{}), "(success)");
|
||||
}
|
||||
template <typename V>
|
||||
void finish(V&& value)
|
||||
requires(!std::is_void_v<SuccessOf<Derived>>)
|
||||
{
|
||||
commit(Step::success(std::any{
|
||||
SuccessOf<Derived>(std::forward<V>(value))}),
|
||||
"(success)");
|
||||
}
|
||||
|
||||
void fail()
|
||||
requires std::is_void_v<FailureOf<Derived>>
|
||||
{
|
||||
commit(Step::failure(std::any{}), "(fail)");
|
||||
}
|
||||
template <typename V>
|
||||
void fail(V&& value)
|
||||
requires(!std::is_void_v<FailureOf<Derived>>)
|
||||
{
|
||||
commit(Step::failure(std::any{
|
||||
FailureOf<Derived>{std::forward<V>(value)}}),
|
||||
"(fail)");
|
||||
}
|
||||
|
||||
/// Internal transition: run `fn` on the event but stay in the
|
||||
/// state (no exit/enter, no transition).
|
||||
void internal(std::function<void(Derived&, const E&)> 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<Derived> 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<const E&>(a));
|
||||
};
|
||||
}
|
||||
if (m_action) {
|
||||
entry.action =
|
||||
[a = std::move(m_action)](
|
||||
Derived& d,
|
||||
const std::any& any) -> Coro::Task<void> {
|
||||
co_await a(d, std::any_cast<const E&>(any));
|
||||
};
|
||||
}
|
||||
entry.step = std::move(step);
|
||||
entry.internal = is_internal;
|
||||
entry.event_name = type_name<E>();
|
||||
entry.target_name = std::move(target);
|
||||
m_table->events.push_back(std::move(entry));
|
||||
}
|
||||
|
||||
TransitionTable<Derived>* m_table;
|
||||
std::function<bool(Derived&, const E&)> m_guard;
|
||||
std::function<Coro::Task<void>(Derived&, const E&)> m_action;
|
||||
};
|
||||
|
||||
/// Fluent builder for the timeout row: `on.after(d).to<S>()` / `.fail(v)`.
|
||||
template <typename Derived> class AfterClause
|
||||
{
|
||||
public:
|
||||
|
||||
AfterClause(TransitionTable<Derived>& table,
|
||||
std::chrono::steady_clock::duration after)
|
||||
: m_table(&table), m_after(after)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename S> void to()
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(Derived::States::template contains<S>(),
|
||||
"after().to<S>: 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<S>();
|
||||
}
|
||||
|
||||
void fail()
|
||||
requires std::is_void_v<FailureOf<Derived>>
|
||||
{
|
||||
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 <typename V>
|
||||
void fail(V&& value)
|
||||
requires(!std::is_void_v<FailureOf<Derived>>)
|
||||
{
|
||||
m_table->has_timeout = true;
|
||||
m_table->timeout_after = m_after;
|
||||
m_table->timeout_step = Step::failure(
|
||||
std::any{FailureOf<Derived>{std::forward<V>(value)}});
|
||||
m_table->timeout_target_name = "(fail)";
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
TransitionTable<Derived>* m_table;
|
||||
std::chrono::steady_clock::duration m_after;
|
||||
};
|
||||
|
||||
/// Entry point handed to `transitions(TransitionBuilder& on)`.
|
||||
template <typename Derived> class TransitionBuilder
|
||||
{
|
||||
public:
|
||||
|
||||
explicit TransitionBuilder(TransitionTable<Derived>& table)
|
||||
: m_table(&table)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename E> [[nodiscard]] EventClause<Derived, E> event()
|
||||
{
|
||||
return EventClause<Derived, E>{*m_table};
|
||||
}
|
||||
|
||||
template <typename Rep, typename Period>
|
||||
[[nodiscard]] AfterClause<Derived>
|
||||
after(std::chrono::duration<Rep, Period> d)
|
||||
{
|
||||
return AfterClause<Derived>{
|
||||
*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 <typename E> void defer()
|
||||
{
|
||||
m_table->deferred.push_back(&typeid(E));
|
||||
}
|
||||
|
||||
/// Entry action — run when the state is entered (before it waits).
|
||||
void enter(std::function<void(Derived&)> fn)
|
||||
{
|
||||
m_table->enter_action =
|
||||
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
|
||||
fn(d);
|
||||
co_return;
|
||||
};
|
||||
}
|
||||
/// Exit action — run when the state is left (on any transition).
|
||||
void exit(std::function<void(Derived&)> fn)
|
||||
{
|
||||
m_table->exit_action =
|
||||
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
|
||||
fn(d);
|
||||
co_return;
|
||||
};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
TransitionTable<Derived>* m_table;
|
||||
};
|
||||
} // namespace Void::Fsm::Detail
|
||||
+109
-210
@@ -1,10 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/Detail/StateList.hpp>
|
||||
#include <Void/Fsm/Machine.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <any>
|
||||
@@ -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<Step>, no params
|
||||
// - entry : a member returning State / Coro::Task<StateKey>>, no
|
||||
// params
|
||||
// - startup-entry: the same taking the sub-machine's startup-data argument
|
||||
// - reactive : a member taking TransitionBuilder<D>&
|
||||
// - 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<E>()), so there is no
|
||||
// reactive role.
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
// Defined in Machine.hpp; forward-declared so InitialStateOf can pattern
|
||||
// match the state list.
|
||||
template <typename...> 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 <typename T> struct ChildSuccessBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildSuccessBox<void> {
|
||||
/// handler written `ok(ChildSuccess s)`. The sub's typed Success is read
|
||||
/// with `s.as<T>()` (the value is empty for a void-result sub).
|
||||
struct ChildSuccess {
|
||||
std::any value;
|
||||
template <typename T> [[nodiscard]] T as() const
|
||||
{
|
||||
return std::any_cast<T>(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 <typename T> struct ChildFailureBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildFailureBox<void> {
|
||||
/// The failure value of a launched sub-machine, handed to `no(ChildFailure
|
||||
/// f)`. The sub's typed Failure is read with `f.as<T>()` (empty for void).
|
||||
struct ChildFailure {
|
||||
std::any value;
|
||||
template <typename T> [[nodiscard]] T as() const
|
||||
{
|
||||
return std::any_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
template <class> inline constexpr bool is_csucc = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_csucc<ChildSuccessBox<T>> = true;
|
||||
template <class> inline constexpr bool is_cfail = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_cfail<ChildFailureBox<T>> = true;
|
||||
} // namespace Detail
|
||||
|
||||
template <class X>
|
||||
concept ChildSuccess = Detail::is_csucc<std::remove_cvref_t<X>>;
|
||||
template <class X>
|
||||
concept ChildFailure = Detail::is_cfail<std::remove_cvref_t<X>>;
|
||||
/// 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 <typename S>
|
||||
using MachineOf =
|
||||
std::remove_cvref_t<decltype(std::declval<S&>().self())>;
|
||||
// InitialStateOf / FirstStateOf live in Detail/StateList.hpp (they
|
||||
// reflect the nested `struct States { … }`).
|
||||
|
||||
template <typename> struct first_state_helper;
|
||||
template <typename F, typename... R>
|
||||
struct first_state_helper<States<F, R...>> {
|
||||
using type = F;
|
||||
};
|
||||
|
||||
/// A machine's initial state type: its nested `Initial` if declared,
|
||||
/// else the first entry of `States<...>`.
|
||||
template <typename M> 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<typename M::Initial>{};
|
||||
} else {
|
||||
return std::type_identity<
|
||||
typename first_state_helper<typename M::States>::type>{};
|
||||
}
|
||||
return Void::Meta::has_annotation<EntryTag>(m);
|
||||
}
|
||||
template <typename M>
|
||||
using InitialStateOf =
|
||||
typename decltype(initial_state_probe<M>())::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<Step> ready_task(Step s) { co_return s; }
|
||||
inline Coro::Task<StateKey> ready_task(StateKey s) { co_return s; }
|
||||
|
||||
// ── entry (0-arg member returning Step / Task<Step>) ──────────────
|
||||
template <typename S> Coro::Task<Step> invoke_entry(S& s)
|
||||
// ── entry (0-arg member returning StateKey / Task<StateKey>) ──────
|
||||
// When several members match, one annotated `[[= Fsm::entry]]` wins;
|
||||
// otherwise the first-declared match is used.
|
||||
template <typename S> Coro::Task<StateKey> 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<S&>().[:m:]());
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:]());
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
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<S&>().[:m:]());
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:]());
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
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 <typename S, typename... DataT>
|
||||
Coro::Task<Step> invoke_startup(S& s, DataT... data)
|
||||
Coro::Task<StateKey> 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<S&>().[:m:](
|
||||
std::declval<DataT>()...));
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:](std::move(data)...));
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
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<S&>().[:m:](
|
||||
std::declval<DataT>()...));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:](std::move(data)...));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
return s.[:m:](std::move(data)...);
|
||||
}
|
||||
}
|
||||
@@ -149,7 +166,7 @@ namespace Void::Fsm
|
||||
|
||||
// ── continuation handler (member taking a ChildSuccess/Failure box)
|
||||
template <typename S, typename Box>
|
||||
Coro::Task<Step> invoke_handler(S& s, Box box)
|
||||
Coro::Task<StateKey> 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<S&>().[:m:](std::declval<Box>()));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
if constexpr (std::is_same_v<R, StateKey>) {
|
||||
return ready_task(s.[:m:](std::move(box)));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
} else if constexpr (std::is_same_v<R,
|
||||
Coro::Task<StateKey>>) {
|
||||
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<T>()`. (Sub is retained in the
|
||||
/// signature so the call site stays `dispatch_result<Next, Sub>`.)
|
||||
template <typename Next, typename Sub>
|
||||
Coro::Task<Step> dispatch_result(Next& s, LaunchResult lr)
|
||||
Coro::Task<StateKey> dispatch_result(Next& s, LaunchResult lr)
|
||||
{
|
||||
using Succ = SuccessOf<Sub>;
|
||||
using Fail = FailureOf<Sub>;
|
||||
if (lr.kind == LaunchResult::Kind::Failure) {
|
||||
ChildFailureBox<Fail> box;
|
||||
if constexpr (!std::is_void_v<Fail>) {
|
||||
box.value = std::any_cast<Fail>(std::move(lr.failure));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
return invoke_handler(s, ChildFailure{std::move(lr.failure)});
|
||||
}
|
||||
ChildSuccessBox<Succ> box;
|
||||
if constexpr (!std::is_void_v<Succ>) {
|
||||
box.value = std::any_cast<Succ>(std::move(lr.value));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
return invoke_handler(s, ChildSuccess{std::move(lr.value)});
|
||||
}
|
||||
|
||||
// ── reactive (member taking TransitionBuilder<D>&) ────────────────
|
||||
template <typename S> consteval bool has_transitions()
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
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<D>& b) {
|
||||
x.[:m:](b);
|
||||
}) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// Fill `table` from S's transitions-shaped member (if any).
|
||||
template <typename S, typename D>
|
||||
void collect_transitions(S& s, TransitionTable<D>& table)
|
||||
{
|
||||
TransitionBuilder<D> 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<D>& 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 <typename S> Coro::Task<Step> drive_reactive(S& s)
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
TransitionTable<D> 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<const std::type_info*> 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<EventEnvelope> held;
|
||||
auto leave = [&](Step step) -> Coro::Task<Step> {
|
||||
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<std::chrono::steady_clock::time_point> 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 <typename S>
|
||||
[[nodiscard]] std::function<Coro::Task<Step>(StateBase&)> make_driver()
|
||||
[[nodiscard]] std::function<Coro::Task<StateKey>(StateBase&)>
|
||||
make_driver()
|
||||
{
|
||||
return [](StateBase& base) -> Coro::Task<Step> {
|
||||
S& s = static_cast<S&>(base);
|
||||
if constexpr (has_transitions<S>()) {
|
||||
co_return co_await drive_reactive(s);
|
||||
} else {
|
||||
co_return co_await invoke_entry(s);
|
||||
}
|
||||
return [](StateBase& base) -> Coro::Task<StateKey> {
|
||||
co_return co_await invoke_entry(static_cast<S&>(base));
|
||||
};
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <meta>
|
||||
#include <type_traits>
|
||||
|
||||
// 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<Ss...>` 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 <meta::info M> consteval bool is_state_member()
|
||||
{
|
||||
if constexpr (meta::is_type(M)) {
|
||||
using S = typename[:M:];
|
||||
return std::is_class_v<S> && std::derived_from<S, StateBase>;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reflection of the first state member of `StatesT` (declaration order),
|
||||
/// or
|
||||
/// `^^void` when the list has none.
|
||||
template <typename StatesT> 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<m>()) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return ^^void;
|
||||
}
|
||||
|
||||
/// The first declared state type of `StatesT` (void if empty).
|
||||
template <typename StatesT>
|
||||
using FirstStateOf = typename[:first_state_member<StatesT>():];
|
||||
|
||||
/// A machine's initial state type: its nested `Initial` if declared, else
|
||||
/// the first member of its `States` list.
|
||||
template <typename M> consteval auto initial_state_probe()
|
||||
{
|
||||
if constexpr (requires { typename M::Initial; }) {
|
||||
return std::type_identity<typename M::Initial>{};
|
||||
} else {
|
||||
return std::type_identity<FirstStateOf<typename M::States>>{};
|
||||
}
|
||||
}
|
||||
template <typename M>
|
||||
using InitialStateOf = typename decltype(initial_state_probe<M>())::type;
|
||||
|
||||
/// Compile-time membership test: is `S` one of `StatesT`'s state members?
|
||||
/// Drives the next<S>() / startMachine<,Next>() target validation.
|
||||
template <typename StatesT, typename S> 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<m>()) {
|
||||
if constexpr (std::is_same_v<typename[:m:], S>) {
|
||||
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 <typename StatesT, typename M>
|
||||
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<m>()) {
|
||||
machine.template add<typename[:m:]>();
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace Void::Fsm::Detail
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
// Umbrella header for the FSM module. The implementation is split for
|
||||
// maintainability:
|
||||
// - Machine.hpp — the Machine<Derived, ResultT> 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<Derived> 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 <Void/Fsm/Fsm.hpp> to get the whole machine API as before.
|
||||
|
||||
|
||||
+112
-151
@@ -6,11 +6,11 @@
|
||||
#include <Void/Fsm/Detail/Awaiter.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Introspect.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Detail/Roles.hpp>
|
||||
#include <Void/Fsm/Detail/StateList.hpp>
|
||||
#include <Void/Fsm/Detail/TypeName.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
|
||||
@@ -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<S>() targets:
|
||||
/// using States = Void::Fsm::States<Idle, Running, Done>;
|
||||
/// The first entry is the initial state unless `using Initial = S;`.
|
||||
template <typename... Ss> struct States {
|
||||
static constexpr std::size_t size = sizeof...(Ss);
|
||||
|
||||
template <typename S> static constexpr bool contains()
|
||||
{
|
||||
return (std::is_same_v<S, Ss> || ...);
|
||||
}
|
||||
};
|
||||
|
||||
/// Options for a Machine (namespace scope to dodge the GCC
|
||||
/// nested-default-arg trap).
|
||||
struct MachineOptions {
|
||||
@@ -76,25 +62,33 @@ namespace Void::Fsm
|
||||
|
||||
// ── Machine<Derived> ──────────────────────────────────────────────────
|
||||
//
|
||||
// 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<E>()) — there is no declarative transition
|
||||
// table. Result types are the nested `Success`/`Failure` (default void).
|
||||
//
|
||||
// // header
|
||||
// class Login : public Void::Fsm::Machine<Login> {
|
||||
// public:
|
||||
// using Success = Token;
|
||||
// int attempts = 0;
|
||||
// struct Check : State { // entry by signature
|
||||
// Coro::Task<Step> run() {
|
||||
// if (++self().attempts > 3) co_return fail();
|
||||
// co_return self().service<IAuth>().ok() ? succeed(Token{})
|
||||
// : next<Check>();
|
||||
// }
|
||||
// };
|
||||
// using States = Void::Fsm::States<Check>;
|
||||
// struct States { struct Check; };
|
||||
// };
|
||||
// // source (namespace scope)
|
||||
// struct Login::States::Check : Login::State { // entry by signature
|
||||
// Coro::Task<StateKey>> run() {
|
||||
// if (++self().attempts > 3) co_return fail();
|
||||
// co_return self().service<IAuth>().ok() ? succeed(Token{})
|
||||
// : next<Check>();
|
||||
// }
|
||||
// };
|
||||
template <typename Derived> 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 <typename S> [[nodiscard]] Step next() const
|
||||
/// time when the machine declares a `States` list.
|
||||
template <typename S> [[nodiscard]] StateKey next() const
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(
|
||||
Derived::States::template contains<S>(),
|
||||
"next<S>: S is not in this machine's "
|
||||
"States<...> list");
|
||||
static_assert(Detail::states_contains<
|
||||
typename Derived::States, S>(),
|
||||
"next<S>: 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<S>()/add_if<S>()), skipping the static check.
|
||||
template <typename S>
|
||||
[[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 <typename S> [[nodiscard]] Step goto_state() const
|
||||
template <typename S>
|
||||
[[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<Recovery>(co_await try_work());
|
||||
template <typename S>
|
||||
[[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<S>();
|
||||
}
|
||||
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<Detail::SuccessOf<Derived>>
|
||||
{
|
||||
return Step::success(std::any{});
|
||||
return StateKey::success(std::any{});
|
||||
}
|
||||
template <typename V>
|
||||
[[nodiscard]] Step succeed(V&& value) const
|
||||
[[nodiscard]] StateKey succeed(V&& value) const
|
||||
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
|
||||
{
|
||||
return Step::success(
|
||||
return StateKey::success(
|
||||
std::any{Detail::SuccessOf<Derived>(
|
||||
std::forward<V>(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<Detail::FailureOf<Derived>>
|
||||
{
|
||||
return Step::failure(std::any{});
|
||||
return StateKey::failure(std::any{});
|
||||
}
|
||||
template <typename V>
|
||||
[[nodiscard]] Step fail(V&& value) const
|
||||
[[nodiscard]] StateKey fail(V&& value) const
|
||||
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
|
||||
{
|
||||
return Step::failure(
|
||||
return StateKey::failure(
|
||||
std::any{Detail::FailureOf<Derived>{
|
||||
std::forward<V>(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<Login, AfterLogin>(seed);
|
||||
template <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step startMachine(Args&&... args) const
|
||||
[[nodiscard]] StateKey startMachine(Args&&... args) const
|
||||
{
|
||||
return m_machine->template start_machine<Sub, Next>(
|
||||
std::forward<Args>(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<Step>,
|
||||
// - entry : a member returning
|
||||
// State/Coro::Task<StateKey>>,
|
||||
// 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<Sub, This>()`).
|
||||
// - continuation : members taking `ChildSuccess` /
|
||||
// `ChildFailure` (the sub's typed result, read
|
||||
// via .as<T>(), after `startMachine<Sub,
|
||||
// This>`).
|
||||
//
|
||||
// struct Idle : State { // reactive
|
||||
// void transitions(TransitionBuilder& on) {
|
||||
// on.event<Go>().to<Running>();
|
||||
// on.after(5s).to<TimedOut>(); } };
|
||||
// Events are handled imperatively inside an entry:
|
||||
// struct Idle : State { // entry
|
||||
// Coro::Task<StateKey> run() {
|
||||
// auto e = co_await await_any<Go, Stop>();
|
||||
// co_return std::holds_alternative<Go>(e) ? next<Running>()
|
||||
// : next<Done>(); }
|
||||
// };
|
||||
// struct After : State { // continuation
|
||||
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
|
||||
// Coro::Task<Step> 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<Derived>;
|
||||
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
|
||||
// Coro::Task<StateKey> ok(ChildSuccess s){ ... }
|
||||
// Coro::Task<StateKey> 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<typename Derived::States>(
|
||||
*this);
|
||||
using Init = Detail::InitialStateOf<Derived>;
|
||||
if constexpr (!std::is_void_v<Init>) {
|
||||
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<S>());
|
||||
// describe() collector: fills a table if S is reactive.
|
||||
m_collectors.emplace(
|
||||
key,
|
||||
[](Detail::StateBase& base,
|
||||
TransitionTable& table) -> bool {
|
||||
if constexpr (Detail::has_transitions<S>()) {
|
||||
Detail::collect_transitions(static_cast<S&>(base),
|
||||
table);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename S> 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 <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step start_machine(Args&&... args)
|
||||
[[nodiscard]] StateKey start_machine(Args&&... args)
|
||||
{
|
||||
if constexpr (requires { typename Derived::States; }) {
|
||||
static_assert(
|
||||
Derived::States::template contains<Next>(),
|
||||
"startMachine<Sub, Next>: Next is not in States<...>");
|
||||
Detail::states_contains<typename Derived::States,
|
||||
Next>(),
|
||||
"startMachine<Sub, Next>: Next is not in States { … }");
|
||||
}
|
||||
using Init = Detail::InitialStateOf<Sub>;
|
||||
auto launcher =
|
||||
@@ -993,7 +974,7 @@ namespace Void::Fsm
|
||||
child.m_startup_injector =
|
||||
[... d = std::move(data)](
|
||||
Detail::StateBase& base) mutable
|
||||
-> Coro::Task<Step> {
|
||||
-> Coro::Task<StateKey> {
|
||||
return Detail::invoke_startup<Init>(
|
||||
static_cast<Init&>(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<Step> {
|
||||
LaunchResult lr) -> Coro::Task<StateKey> {
|
||||
return Detail::dispatch_result<Next, Sub>(
|
||||
static_cast<Next&>(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<StateInfo> describe()
|
||||
{
|
||||
std::vector<StateInfo> 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<bool>(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 <typename... Ss> void register_states(States<Ss...>)
|
||||
{
|
||||
(add<Ss>(), ...);
|
||||
}
|
||||
|
||||
template <typename First, typename... Rest>
|
||||
static const std::type_info* first_type(States<First, Rest...>)
|
||||
{
|
||||
return &typeid(First);
|
||||
}
|
||||
static const std::type_info* first_type(States<>)
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template <typename S> [[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<S>() 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<FsmError>(step.payload())
|
||||
.message);
|
||||
on_machine_exit();
|
||||
co_return;
|
||||
}
|
||||
}
|
||||
@@ -1385,15 +1350,11 @@ namespace Void::Fsm
|
||||
std::type_index,
|
||||
std::function<std::unique_ptr<Detail::StateBase>()>>
|
||||
m_factories;
|
||||
// Per-state signature-inferred driver thunk (entry / reactive).
|
||||
std::unordered_map<std::type_index, std::function<Coro::Task<Step>(
|
||||
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<bool(Detail::StateBase&, TransitionTable&)>>
|
||||
m_collectors;
|
||||
std::function<Coro::Task<StateKey>(Detail::StateBase&)>>
|
||||
m_drivers;
|
||||
std::unordered_map<std::type_index, int> m_index;
|
||||
std::vector<std::string> m_names;
|
||||
std::unordered_map<std::string, const std::type_info*>
|
||||
@@ -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<LaunchResult> 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<Coro::Task<Step>(Detail::StateBase&)>
|
||||
std::function<Coro::Task<StateKey>(Detail::StateBase&)>
|
||||
m_startup_injector;
|
||||
|
||||
// External jump request (jump<S>()); applied by drive() at the
|
||||
@@ -1437,5 +1398,5 @@ namespace Void::Fsm
|
||||
// suspended frame chain of a machine parked on an event.
|
||||
std::optional<Coro::Task<void>> m_driver;
|
||||
};
|
||||
|
||||
template <typename Derived> using State = Machine<Derived>::State;
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
@@ -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<S>() / 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<Coro::Task<Step>(Detail::StateBase&,
|
||||
LaunchResult)>;
|
||||
using Dispatch = std::function<Coro::Task<StateKey>(
|
||||
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<Coro::Task<LaunchResult>()> 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;
|
||||
@@ -1,81 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <concepts>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#if __has_include(<meta>) && defined(__cpp_consteval)
|
||||
#include <meta>
|
||||
#include <string>
|
||||
|
||||
#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<T>` 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 `"<unrepresentable>"`.
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value);
|
||||
|
||||
template <typename T>
|
||||
concept Formattable = std::formattable<T, char>;
|
||||
|
||||
template <typename T>
|
||||
concept HasFormatMethod = requires(const T& v) {
|
||||
{ v.format() } -> std::convertible_to<std::string>;
|
||||
};
|
||||
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
template <typename T> [[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<T> → std::format("{}", v)
|
||||
/// 2. a `.format()` method returning something string-convertible
|
||||
/// 3. C++26 reflection: `Type{field1: value1, field2: value2}`
|
||||
/// 4. otherwise `"<unrepresentable>"`
|
||||
template <typename T> [[nodiscard]] std::string repr(const T& value)
|
||||
{
|
||||
if constexpr (Formattable<T>) {
|
||||
return std::format("{}", value);
|
||||
} else if constexpr (HasFormatMethod<T>) {
|
||||
return std::string{value.format()};
|
||||
}
|
||||
#ifdef VOID_RESULT_HAS_REFLECTION
|
||||
else if constexpr (std::is_class_v<T> || std::is_union_v<T>) {
|
||||
return reflect_struct(value);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return "<unrepresentable>";
|
||||
}
|
||||
return Void::Meta::repr(value);
|
||||
}
|
||||
|
||||
} // namespace Void::Result::Detail
|
||||
@@ -5,122 +5,209 @@
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
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<long long>(attempt + 1);
|
||||
const auto capped = std::min(raw, static_cast<long long>(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<long long>(attempt + 1);
|
||||
const auto capped =
|
||||
std::min(raw, static_cast<long long>(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<double>(base.count());
|
||||
for (std::size_t i = 0; i < attempt; ++i) ms *= multiplier;
|
||||
const auto clamped = std::min(ms, static_cast<double>(max.count()));
|
||||
return std::chrono::milliseconds{static_cast<long long>(clamped)};
|
||||
}
|
||||
};
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
delay(std::size_t attempt) const noexcept
|
||||
{
|
||||
double ms = static_cast<double>(base.count());
|
||||
for (std::size_t i = 0; i < attempt; ++i) {
|
||||
ms *= multiplier;
|
||||
}
|
||||
const auto clamped =
|
||||
std::min(ms, static_cast<double>(max.count()));
|
||||
return std::chrono::milliseconds{
|
||||
static_cast<long long>(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 <typename Backoff = ExponentialBackoff>
|
||||
struct Policy
|
||||
{
|
||||
std::size_t max_attempts{3};
|
||||
Backoff backoff{};
|
||||
enum class JitterMode { Full, Equal };
|
||||
|
||||
using BackoffType = Backoff;
|
||||
};
|
||||
template <typename Backoff = ExponentialBackoff> struct Jittered {
|
||||
Backoff inner{};
|
||||
JitterMode mode{JitterMode::Full};
|
||||
|
||||
// ── retry — retries a callable up to max_attempts times ──────────────────────
|
||||
// The callable must return std::expected<T, E>. 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<long long> dist{0, base - floor};
|
||||
return std::chrono::milliseconds{floor + dist(rng)};
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry(const Policy& policy, F&& fn)
|
||||
{
|
||||
using Result = std::invoke_result_t<F>;
|
||||
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 <typename Backoff = ExponentialBackoff> 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 <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry_or_throw(const Policy& policy, F&& fn)
|
||||
{
|
||||
auto result = retry(policy, std::forward<F>(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<T,E>.
|
||||
namespace Detail
|
||||
{
|
||||
// Sleep for `wait`, honoring a total budget measured from `start`.
|
||||
// Returns false if the budget is exhausted (caller should stop
|
||||
// retrying).
|
||||
template <typename Policy>
|
||||
[[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<milliseconds>(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 <typename Policy, typename F, typename Pred>
|
||||
requires std::invocable<F> && std::predicate<Pred, std::invoke_result_t<F>>
|
||||
std::invoke_result_t<F> retry_while(const Policy& policy, F&& fn, Pred&& should_retry)
|
||||
{
|
||||
std::invoke_result_t<F> 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<T, E>.
|
||||
// Retries on unexpected values. Returns the last result (success or final
|
||||
// error) after all attempts.
|
||||
|
||||
template <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry(const Policy& policy, F&& fn)
|
||||
{
|
||||
using Result = std::invoke_result_t<F>;
|
||||
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 <typename Policy, typename F>
|
||||
requires std::invocable<F>
|
||||
auto retry_or_throw(const Policy& policy, F&& fn)
|
||||
{
|
||||
auto result = retry(policy, std::forward<F>(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<T,E>.
|
||||
|
||||
template <typename Policy, typename F, typename Pred>
|
||||
requires std::invocable<F> &&
|
||||
std::predicate<Pred, std::invoke_result_t<F>>
|
||||
std::invoke_result_t<F> retry_while(const Policy& policy, F&& fn,
|
||||
Pred&& should_retry)
|
||||
{
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
std::invoke_result_t<F> 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
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <initializer_list>
|
||||
#include <span>
|
||||
#include <string>
|
||||
@@ -24,6 +26,23 @@ namespace Void::Logging
|
||||
explicit FieldScope(
|
||||
std::initializer_list<std::pair<std::string, std::string>>
|
||||
fields);
|
||||
explicit FieldScope(
|
||||
std::vector<std::pair<std::string, std::string>> 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 <typename T>
|
||||
[[nodiscard]] static FieldScope from(const T& obj)
|
||||
{
|
||||
std::vector<std::pair<std::string, std::string>> 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;
|
||||
|
||||
|
||||
@@ -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<std::string> include;
|
||||
std::vector<std::string> 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
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
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 <typename R>
|
||||
concept HasHasValue = requires(const R& r) {
|
||||
{ r.has_value() } -> std::convertible_to<bool>;
|
||||
};
|
||||
|
||||
class CircuitBreaker
|
||||
{
|
||||
public:
|
||||
|
||||
enum class State { Closed, Open, HalfOpen };
|
||||
|
||||
using Clock =
|
||||
std::function<std::chrono::steady_clock::time_point()>;
|
||||
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 <std::invocable F>
|
||||
requires HasHasValue<std::invoke_result_t<F>>
|
||||
auto execute(F&& fn) -> std::optional<std::invoke_result_t<F>>
|
||||
{
|
||||
if (!allow()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto result = std::forward<F>(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
|
||||
@@ -0,0 +1,123 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Resilience
|
||||
{
|
||||
|
||||
// ── KeyedRateLimiter<Key> ───────────────────────────────────────────────
|
||||
// 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 <typename Key, typename Hash = std::hash<Key>>
|
||||
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<TokenBucket> 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<TokenBucket>(
|
||||
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<Key, Entry, Hash> map_;
|
||||
};
|
||||
|
||||
} // namespace Void::Resilience
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
|
||||
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<std::chrono::steady_clock::time_point()>;
|
||||
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<double> 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
|
||||
@@ -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 <Void/Resilience/CircuitBreaker.hpp>
|
||||
#include <Void/Resilience/KeyedRateLimiter.hpp>
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
#include <Void/Resilience/ResourceMonitor.hpp>
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
|
||||
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<void(std::uint64_t usage)>;
|
||||
|
||||
// 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<std::uint64_t>(
|
||||
static_cast<double>(limit) * high)},
|
||||
low_{static_cast<std::uint64_t>(static_cast<double>(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<double>(usage_) /
|
||||
static_cast<double>(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
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
|
||||
#include <memory>
|
||||
@@ -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>() == "IClock".
|
||||
template <typename I> [[nodiscard]] std::string interface_name()
|
||||
{
|
||||
return Void::Meta::type_name<I>();
|
||||
}
|
||||
#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<I>() 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 <typename I> void provide(std::shared_ptr<I> 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 <typename I> [[nodiscard]] std::shared_ptr<I> 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<I>(it->second.impl);
|
||||
}
|
||||
}
|
||||
return std::static_pointer_cast<I>(it->second.impl);
|
||||
return m_parent ? m_parent->get<I>() : nullptr;
|
||||
}
|
||||
|
||||
/// Resolve I; throws std::runtime_error if not provided.
|
||||
@@ -79,8 +103,13 @@ namespace Void::Service
|
||||
|
||||
template <typename I> [[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<I>() : 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<std::type_index, Entry> m_services;
|
||||
std::vector<std::type_index> m_order;
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/times.h>
|
||||
#include <unistd.h>
|
||||
#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<std::uint64_t> 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<std::uint64_t>(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<SystemMemory> 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<std::uint64_t>(info.totalram) * unit;
|
||||
// freeram excludes reclaimable cache/buffers, so this is conservative.
|
||||
m.available =
|
||||
(static_cast<std::uint64_t>(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<double> 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<double>(ticks - last_ticks_) /
|
||||
static_cast<double>(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
|
||||
@@ -5,40 +5,62 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
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<Output, Void::Result::Error>
|
||||
run(const std::filesystem::path& executable,
|
||||
std::vector<std::string> 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<void(std::string_view line)> on_stdout;
|
||||
std::function<void(std::string_view line)> on_stderr;
|
||||
};
|
||||
|
||||
/// Run a command through /bin/sh -c "command".
|
||||
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
|
||||
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<Output, Void::Result::Error>
|
||||
run(const std::filesystem::path& executable,
|
||||
std::vector<std::string> 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<Output, Void::Result::Error>
|
||||
run_streaming(
|
||||
const std::filesystem::path& executable,
|
||||
std::vector<std::string> 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<Output, Void::Result::Error>
|
||||
shell(std::string_view command,
|
||||
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
|
||||
|
||||
} // namespace Void::Process
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
// Reflection-readable test metadata. Annotate a suite's test methods:
|
||||
// struct MathTests : Void::Testing::Suite<MathTests> {
|
||||
// [[= 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
|
||||
@@ -0,0 +1,175 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Testing/Annotations.hpp>
|
||||
#include <Void/Testing/Config.hpp>
|
||||
#include <Void/Testing/Detail/Registry.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#define VOID_TESTING_HAS_REFLECTION 1
|
||||
#endif
|
||||
|
||||
// ── Reflection-based test registration
|
||||
// ──────────────────────────────────────── Derive a test suite from
|
||||
// `Suite<Derived>` (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<MathTests> {
|
||||
// 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 <typename Derived> class Suite
|
||||
{
|
||||
protected:
|
||||
|
||||
Suite() = default;
|
||||
|
||||
private:
|
||||
|
||||
/// Run one reflected test method against a fresh Derived instance,
|
||||
/// wrapping it in setup()/teardown() when present.
|
||||
template <meta::info M> 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<Name>(^^Derived);
|
||||
n.has_value()) {
|
||||
return std::string{n->value.view()};
|
||||
} else {
|
||||
return Void::Meta::type_name<Derived>();
|
||||
}
|
||||
}
|
||||
|
||||
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<std::string> tags;
|
||||
template for (constexpr auto a :
|
||||
std::define_static_array(
|
||||
meta::annotations_of_with_type(
|
||||
m, ^^Tag)))
|
||||
{
|
||||
constexpr Tag t = meta::extract<Tag>(a);
|
||||
tags.emplace_back(t.value.view());
|
||||
}
|
||||
|
||||
bool disabled = false;
|
||||
std::string skip_reason;
|
||||
if constexpr (constexpr auto s =
|
||||
Void::Meta::annotation_of<Skip>(m);
|
||||
s.has_value()) {
|
||||
disabled = true;
|
||||
skip_reason = std::string{s->reason.view()};
|
||||
}
|
||||
|
||||
reg.add(TestCase{
|
||||
.run = [] { run_method<m>(); },
|
||||
.name = std::string{meta::identifier_of(m)},
|
||||
.suite = suite,
|
||||
.file = loc.file_name(),
|
||||
.line = static_cast<int>(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 <typename Derived> class Suite
|
||||
{
|
||||
protected:
|
||||
|
||||
Suite() = default;
|
||||
};
|
||||
|
||||
#endif // VOID_TESTING_HAS_REFLECTION
|
||||
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#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<Sig>
|
||||
// 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 <typename I> [[nodiscard]] std::vector<std::string> method_names()
|
||||
{
|
||||
std::vector<std::string> 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 <typename I> [[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<MockDb, IDatabase>());
|
||||
template <typename Mock, typename I> [[nodiscard]] consteval bool covers()
|
||||
{
|
||||
return std::derived_from<Mock, I> && !std::is_abstract_v<Mock>;
|
||||
}
|
||||
|
||||
#endif // VOID_MOCK_HAS_REFLECTION
|
||||
|
||||
} // namespace Void::TestingMock
|
||||
+177
-82
@@ -1,106 +1,201 @@
|
||||
#pragma once
|
||||
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <ratio>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
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<double>(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<double>(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<double>(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<double>(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<std::chrono::seconds>(d).count();
|
||||
if (total_s < 60) {
|
||||
const double s = static_cast<double>(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<std::chrono::seconds>(d).count();
|
||||
if (total_s < 60) {
|
||||
const double s = static_cast<double>(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 <typename Rep, typename Period>
|
||||
[[nodiscard]] std::string
|
||||
format_duration(std::chrono::duration<Rep, Period> d) noexcept
|
||||
{
|
||||
return format_duration(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(d));
|
||||
}
|
||||
/// Format any chrono duration via the nanosecond overload.
|
||||
template <typename Rep, typename Period>
|
||||
[[nodiscard]] std::string
|
||||
format_duration(std::chrono::duration<Rep, Period> d) noexcept
|
||||
{
|
||||
return format_duration(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(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<std::chrono::nanoseconds>
|
||||
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<nanoseconds>(
|
||||
duration<double, typename decltype(unit)::period>{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 <class Period>
|
||||
[[nodiscard]] constexpr std::optional<std::string_view>
|
||||
duration_suffix()
|
||||
{
|
||||
if constexpr (std::is_same_v<Period, std::nano>) {
|
||||
return "ns";
|
||||
} else if constexpr (std::is_same_v<Period, std::micro>) {
|
||||
return "us";
|
||||
} else if constexpr (std::is_same_v<Period, std::milli>) {
|
||||
return "ms";
|
||||
} else if constexpr (std::is_same_v<Period, std::ratio<1>>) {
|
||||
return "s";
|
||||
} else if constexpr (std::is_same_v<Period, std::ratio<60>>) {
|
||||
return "m";
|
||||
} else if constexpr (std::is_same_v<Period, std::ratio<3600>>) {
|
||||
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 ("<n>ns"),
|
||||
/// which is exact for the realistic cases. The inverse of parse_duration
|
||||
/// for the standard aliases.
|
||||
template <class Rep, class Period>
|
||||
[[nodiscard]] std::string
|
||||
duration_to_string(std::chrono::duration<Rep, Period> d)
|
||||
{
|
||||
constexpr auto suffix = Detail::duration_suffix<Period>();
|
||||
if constexpr (suffix.has_value()) {
|
||||
return std::format("{}{}", d.count(), *suffix);
|
||||
} else {
|
||||
const auto ns =
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(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<std::chrono::milliseconds>(
|
||||
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<std::chrono::milliseconds>(
|
||||
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
|
||||
@@ -1,3 +1,3 @@
|
||||
void_add_module(Configuration
|
||||
INTERNAL_DEPS Functional System Data
|
||||
INTERNAL_DEPS Functional System Data Time
|
||||
)
|
||||
@@ -1 +1,3 @@
|
||||
void_add_module(Data)
|
||||
void_add_module(Data
|
||||
INTERNAL_DEPS Time
|
||||
)
|
||||
@@ -25,6 +25,15 @@ namespace Void::Logging
|
||||
m_count = fields.size();
|
||||
}
|
||||
|
||||
FieldScope::FieldScope(
|
||||
std::vector<std::pair<std::string, std::string>> 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) {
|
||||
|
||||
@@ -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 += '=';
|
||||
|
||||
+24
-12
@@ -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<const Formatter>
|
||||
make_formatter(const Configuration::Config& cfg)
|
||||
{
|
||||
const auto format = cfg.get_or("format", "default");
|
||||
if (format == "pattern") {
|
||||
auto fmt = std::make_shared<PatternFormatter>(
|
||||
std::string{cfg.get_or(
|
||||
auto fmt =
|
||||
std::make_shared<PatternFormatter>(std::string{cfg.get_or(
|
||||
"pattern", "{time} [{level}] {scopes}{message}")});
|
||||
if (cfg.get_or_as<bool>("color", false)) {
|
||||
fmt->set_color_policy(ColorPolicy::defaults());
|
||||
@@ -115,10 +125,14 @@ namespace Void::Logging
|
||||
return fmt;
|
||||
}
|
||||
if (format == "json") {
|
||||
return std::make_shared<JsonLinesFormatter>();
|
||||
auto fmt = std::make_shared<JsonLinesFormatter>();
|
||||
fmt->set_field_filter(make_field_filter(cfg));
|
||||
return fmt;
|
||||
}
|
||||
if (format == "logfmt") {
|
||||
return std::make_shared<LogfmtFormatter>();
|
||||
auto fmt = std::make_shared<LogfmtFormatter>();
|
||||
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<bool>("split.combined", true);
|
||||
opt.combined = sub.get_or_as<bool>("split.combined", true);
|
||||
opt.max_bytes =
|
||||
sub.get_or_as<std::size_t>("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<std::size_t>("history.max_kb", 8192) *
|
||||
1024;
|
||||
sub.get_or_as<std::size_t>("history.max_kb", 8192) * 1024;
|
||||
opt.max_files =
|
||||
sub.get_or_as<std::size_t>("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());
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
void_add_module(Resilience)
|
||||
+265
-194
@@ -12,16 +12,25 @@ namespace Void::Process
|
||||
std::vector<std::string>,
|
||||
std::string_view,
|
||||
std::chrono::milliseconds)
|
||||
{
|
||||
return Void::Result::fail("Process::run: not implemented on Windows");
|
||||
}
|
||||
|
||||
Void::Result::Result<Output, Void::Result::Error>
|
||||
run_streaming(const std::filesystem::path&,
|
||||
std::vector<std::string>,
|
||||
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<Output, Void::Result::Error>
|
||||
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<std::size_t>(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<std::size_t>(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<Output, Void::Result::Error>
|
||||
run(const std::filesystem::path& executable,
|
||||
std::vector<std::string> 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<void(std::string_view)>& 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<Output, Void::Result::Error>
|
||||
run_impl(const std::filesystem::path& executable,
|
||||
std::vector<std::string> 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<const char*> 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<char* const*>(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<std::size_t>(n);
|
||||
remaining -= static_cast<std::size_t>(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<std::chrono::milliseconds>(
|
||||
deadline - std::chrono::steady_clock::now())
|
||||
.count();
|
||||
if (left_ms <= 0) {
|
||||
::kill(pid, SIGTERM);
|
||||
break;
|
||||
}
|
||||
|
||||
int ret = ::poll(pfds, static_cast<nfds_t>(nfds),
|
||||
static_cast<int>(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<Output, Void::Result::Error>
|
||||
run(const std::filesystem::path& executable,
|
||||
std::vector<std::string> args, std::string_view stdin_data,
|
||||
std::chrono::milliseconds timeout)
|
||||
{
|
||||
return run_impl(executable, std::move(args), stdin_data, timeout,
|
||||
nullptr);
|
||||
}
|
||||
|
||||
Void::Result::Result<Output, Void::Result::Error> run_streaming(
|
||||
const std::filesystem::path& executable, std::vector<std::string> 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<const char*> argv;
|
||||
argv.push_back(executable.c_str());
|
||||
for (const auto& a : args) {
|
||||
argv.push_back(a.c_str());
|
||||
Void::Result::Result<Output, Void::Result::Error>
|
||||
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<char* const*>(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<std::size_t>(n);
|
||||
remaining -= static_cast<std::size_t>(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<std::chrono::milliseconds>(
|
||||
deadline - std::chrono::steady_clock::now())
|
||||
.count();
|
||||
if (left_ms <= 0) {
|
||||
::kill(pid, SIGTERM);
|
||||
break;
|
||||
}
|
||||
|
||||
int ret = ::poll(pfds, static_cast<nfds_t>(nfds),
|
||||
static_cast<int>(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<Output, Void::Result::Error>
|
||||
shell(std::string_view command, std::chrono::milliseconds timeout)
|
||||
{
|
||||
return run("/bin/sh", {"-c", std::string{command}}, {}, timeout);
|
||||
}
|
||||
|
||||
} // namespace Void::Process
|
||||
|
||||
|
||||
@@ -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(<dlfcn.h>)
|
||||
@@ -44,7 +45,7 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct Work : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& svc = service<VoidTest::ICalc>();
|
||||
const int total = svc.accumulate(1);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::EventBus::EventBus;
|
||||
using Void::EventBus::Mode;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct Tick {
|
||||
int n = 0;
|
||||
};
|
||||
|
||||
struct EventBusAsync : Void::Testing::Suite<EventBusAsync> {
|
||||
// Async handlers run on the bus worker, not the publisher thread.
|
||||
Test handler_runs_off_publisher_thread()
|
||||
{
|
||||
EventBus bus{Mode::Async};
|
||||
std::atomic<std::thread::id> handler_thread{};
|
||||
bus.subscribe<Tick>([&](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<int> total{0};
|
||||
bus.subscribe<Tick>([&](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<int> count{0};
|
||||
const auto id = bus.subscribe<Tick>(
|
||||
[&](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<Tick>([&](const Tick& t) { seen = t.n; });
|
||||
bus.publish(Tick{7});
|
||||
Void::Testing::expect_eq(seen, 7); // no flush needed
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Concurrency::ThreadPool;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ThreadPoolBackpressure
|
||||
: Void::Testing::Suite<ThreadPoolBackpressure> {
|
||||
// Unbounded pool (the default) accepts everything and never
|
||||
// rejects.
|
||||
Test unbounded_default_accepts_all()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
std::atomic<int> 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<bool> started{false};
|
||||
std::atomic<bool> 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
|
||||
@@ -0,0 +1,42 @@
|
||||
#include <Void/Configuration/Argparse.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
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<std::string> 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<Opts>(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<Opts>(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"});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#include <Void/Configuration/Bind.hpp>
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<Settings>(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<Settings>(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<Settings>(cfg);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Configuration::Config;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ByteSize : Void::Testing::Suite<ByteSize> {
|
||||
Test si_units()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("a", "10KB");
|
||||
cfg.set("b", "2MB");
|
||||
cfg.set("c", "1GB");
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("a").value(),
|
||||
std::uint64_t{10'000});
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("b").value(),
|
||||
std::uint64_t{2'000'000});
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("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<std::uint64_t>("a").value(),
|
||||
std::uint64_t{1024});
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("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<std::size_t>("plain").value(), std::size_t{512});
|
||||
Void::Testing::expect_eq(
|
||||
cfg.get_as<std::size_t>("half").value(), std::size_t{1500});
|
||||
Void::Testing::expect_eq(
|
||||
cfg.get_as<std::size_t>("bytes").value(), std::size_t{64});
|
||||
}
|
||||
|
||||
Test invalid_unit_is_error()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("bad", "10ZZ");
|
||||
Void::Testing::expect(
|
||||
!cfg.get_as<std::uint64_t>("bad").has_value());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,86 @@
|
||||
#include <Void/Containers/BufferPool.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::BufferPool::BufferPool;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct BufferPoolTests : Void::Testing::Suite<BufferPoolTests> {
|
||||
// Logical size is the request; capacity rounds up to a power of
|
||||
// two.
|
||||
Test acquire_rounds_capacity_to_size_class()
|
||||
{
|
||||
BufferPool<std::int16_t> 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<std::int16_t> 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<float> 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<int> pool;
|
||||
auto buf = pool.acquire(4);
|
||||
for (std::size_t i = 0; i < buf.size(); ++i) {
|
||||
buf[i] = static_cast<int>(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<int> 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
|
||||
@@ -0,0 +1,123 @@
|
||||
#include <Void/Containers/Cache.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
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<TP> now =
|
||||
std::make_shared<TP>(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<CacheTests> {
|
||||
// ── TTL ───────────────────────────────────────────────────
|
||||
Test ttl_expires_lazily()
|
||||
{
|
||||
ManualClock clk;
|
||||
Cache<int, std::string> 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<int, int> 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<int, int> 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<int, int> 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<int, int> 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<int, int> 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<int, int> 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<int, int> 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
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <Void/Containers/Debug.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct P {
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test debug_dump_reflects_struct_elements()
|
||||
{
|
||||
std::vector<P> 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<int> n{1, 2, 3};
|
||||
Void::Testing::expect_eq(Void::Containers::debug_dump(n),
|
||||
std::string{"[1, 2, 3]"});
|
||||
std::vector<int> empty;
|
||||
Void::Testing::expect_eq(Void::Containers::debug_dump(empty),
|
||||
std::string{"[]"});
|
||||
}
|
||||
+121
-124
@@ -1,138 +1,135 @@
|
||||
#include <Void/Core/Bits.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// ── 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<Bits> {
|
||||
// ── 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<std::uint8_t>(4),
|
||||
std::uint8_t{0x0F});
|
||||
}
|
||||
Test range_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::range_mask<std::uint8_t>(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<std::uint8_t>(4),
|
||||
std::uint8_t{0x0F});
|
||||
}
|
||||
|
||||
Void::Testing::Test range_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::range_mask<std::uint8_t>(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
|
||||
@@ -0,0 +1,32 @@
|
||||
#include <Void/Core/Flags.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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>{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<Perm>{}),
|
||||
std::string{});
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test flags_parse_names()
|
||||
{
|
||||
const auto f = Void::Flags::parse<Perm>("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<Perm>("Exec|Nope");
|
||||
Void::Testing::expect(g.test(Perm::Exec) && !g.test(Perm::Read));
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<Point>(), std::size_t{2});
|
||||
const auto names = M::field_names<Point>();
|
||||
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<Color>, std::size_t{3});
|
||||
constexpr auto vals = M::enum_values<Color>();
|
||||
Void::Testing::expect(vals[0] == Color::Red && vals[2] == Color::Blue);
|
||||
const auto entries = M::enum_entries<Color>();
|
||||
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<Color>("Green").value() ==
|
||||
Color::Green);
|
||||
Void::Testing::expect(!M::enum_parse<Color>("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<Annotated>;
|
||||
static_assert(M::has_annotation<Marker>(members[0]));
|
||||
static_assert(!M::has_annotation<Marker>(members[1]));
|
||||
Void::Testing::expect(M::has_annotation<Marker>(members[0]));
|
||||
Void::Testing::expect(!M::has_annotation<Marker>(members[1]));
|
||||
}
|
||||
|
||||
Void::Testing::Test meta_type_name()
|
||||
{
|
||||
Void::Testing::expect_eq(M::type_name<Point>(), std::string{"Point"});
|
||||
Void::Testing::expect_eq(M::type_name<Nest>(), std::string{"Nest"});
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#include <Void/Data/Csv.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<Rec>();
|
||||
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<Rec>(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);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<JsonQuery> {
|
||||
// ── 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<std::string> 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<std::string> 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
|
||||
@@ -0,0 +1,61 @@
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<User>(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<User>(*j);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect_eq(r.error().field, std::string{"name"});
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#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<Circle, Square>;
|
||||
|
||||
struct Sample {
|
||||
std::string name;
|
||||
std::chrono::milliseconds latency{0};
|
||||
std::chrono::seconds ttl{0};
|
||||
std::array<int, 3> rgb{0, 0, 0};
|
||||
std::map<int, std::string> by_id;
|
||||
std::optional<std::chrono::milliseconds> deadline;
|
||||
std::chrono::system_clock::time_point created{};
|
||||
};
|
||||
|
||||
struct ReflectChrono : Void::Testing::Suite<ReflectChrono> {
|
||||
// ── 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<Sample>(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<Sample>(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<Sample>(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<Sample>(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<Sample>(to_json(s));
|
||||
Void::Testing::expect(back.has_value());
|
||||
const auto ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
back->created.time_since_epoch())
|
||||
.count();
|
||||
Void::Testing::expect_eq(ms,
|
||||
static_cast<long long>(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<Sample>(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<Sample>(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<Sample>(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<Sample>(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<Shape>(jc);
|
||||
Void::Testing::expect(bc.has_value());
|
||||
Void::Testing::expect(std::holds_alternative<Circle>(*bc));
|
||||
Void::Testing::expect_eq(std::get<Circle>(*bc).radius, 2.0);
|
||||
|
||||
const Shape sq = Square{3.0};
|
||||
const auto bs = from_json<Shape>(to_json(sq));
|
||||
Void::Testing::expect(bs.has_value());
|
||||
Void::Testing::expect(std::holds_alternative<Square>(*bs));
|
||||
Void::Testing::expect_eq(std::get<Square>(*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<Shape>(j);
|
||||
Void::Testing::expect(!back.has_value());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
#endif // VOID_HAS_JSON_REFLECTION
|
||||
@@ -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<std::string>* log = nullptr;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
if (self().log) {
|
||||
self().log->push_back("start");
|
||||
}
|
||||
co_return next<Work>();
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct Start : State {
|
||||
Task<StateKey> start()
|
||||
{
|
||||
if (self().log) {
|
||||
self().log->push_back("start");
|
||||
}
|
||||
co_return next<Work>();
|
||||
}
|
||||
};
|
||||
|
||||
struct Work : State {
|
||||
Task<Step> 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<Work>();
|
||||
}
|
||||
struct Work : State {
|
||||
Task<StateKey> 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<Work>();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Start, Work>;
|
||||
|
||||
Counter()
|
||||
: Void::Fsm::Machine<Counter>(
|
||||
MachineOptions{.own_worker = false})
|
||||
@@ -62,12 +64,12 @@ namespace
|
||||
using Success = int;
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Boom : State {
|
||||
Task<Step> run() { co_return fail("kaboom"); }
|
||||
struct States {
|
||||
struct Boom : State {
|
||||
Task<StateKey> run() { co_return fail("kaboom"); }
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Boom>;
|
||||
|
||||
Failing()
|
||||
: Void::Fsm::Machine<Failing>(
|
||||
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<Trivial> {
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(); }
|
||||
struct States {
|
||||
struct Done : State {
|
||||
Task<StateKey> run() { co_return succeed(); }
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Done>;
|
||||
Trivial()
|
||||
: Void::Fsm::Machine<Trivial>(
|
||||
MachineOptions{.own_worker = false})
|
||||
@@ -137,13 +140,13 @@ Void::Testing::Test fsm_dynamic_state_registration()
|
||||
|
||||
bool express;
|
||||
struct Express : State {
|
||||
Task<Step> run() { co_return succeed(99); }
|
||||
Task<StateKey> run() { co_return succeed(99); }
|
||||
};
|
||||
struct Normal : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
if (self().has_state<Express>()) {
|
||||
co_return next_dynamic<Express>();
|
||||
|
||||
@@ -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<Step> run()
|
||||
Task<StateKey> 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<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(service<IDoubler>().twice(21));
|
||||
}
|
||||
|
||||
@@ -3,15 +3,20 @@
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
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<Flow>
|
||||
{
|
||||
public:
|
||||
@@ -29,29 +34,29 @@ namespace
|
||||
using Success = int;
|
||||
std::vector<std::string> 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<Click>();
|
||||
on.template event<Done>().template to<Idle>();
|
||||
}
|
||||
struct States {
|
||||
struct Busy : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
m.log.push_back("enter");
|
||||
co_await await_event<Done>(); // Click buffered
|
||||
m.log.push_back("exit");
|
||||
co_return next<Idle>();
|
||||
}
|
||||
};
|
||||
struct Idle : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Click>(); // buffered Click
|
||||
self().log.push_back("click");
|
||||
co_return next<End>();
|
||||
}
|
||||
};
|
||||
struct End : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
};
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.template event<Click>()
|
||||
.action([](Flow& m, const Click&) {
|
||||
m.log.push_back("click");
|
||||
})
|
||||
.template to<End>();
|
||||
}
|
||||
};
|
||||
struct End : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
using States = Fsm::States<Busy, Idle, End>;
|
||||
};
|
||||
} // 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<std::string> 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<Counter>
|
||||
{
|
||||
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<Tick>().internal(
|
||||
[](Counter& m, const Tick&) { ++m.ticks; });
|
||||
on.template event<Stop>().template to<Done>();
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
++m.enters; // entered exactly once
|
||||
for (;;) {
|
||||
auto ev = co_await await_any<Tick, Stop>();
|
||||
if (std::holds_alternative<Stop>(ev)) {
|
||||
co_return next<Done>();
|
||||
}
|
||||
++m.ticks; // internal: handled, stay here
|
||||
}
|
||||
}
|
||||
};
|
||||
struct Done : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(self().ticks);
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(self().ticks); }
|
||||
};
|
||||
using States = Fsm::States<Run, Done>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -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<Step> run()
|
||||
{
|
||||
auto a = co_await await_event<Add>();
|
||||
self().total += a.n;
|
||||
auto b = co_await await_event<Add>();
|
||||
self().total += b.n;
|
||||
co_return succeed(self().total);
|
||||
}
|
||||
struct States {
|
||||
struct Take : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto a = co_await await_event<Add>();
|
||||
self().total += a.n;
|
||||
auto b = co_await await_event<Add>();
|
||||
self().total += b.n;
|
||||
co_return succeed(self().total);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Take>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -63,16 +65,17 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() { co_return goto_state<C>(); }
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return goto_state<C>(); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<StateKey> run() { co_return succeed(3); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> run() { co_return succeed(3); }
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -98,17 +101,18 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Loop : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return next<Loop>();
|
||||
}
|
||||
struct States {
|
||||
struct Loop : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return next<Loop>();
|
||||
}
|
||||
};
|
||||
struct Done : State {
|
||||
Task<StateKey> run() { co_return succeed(99); }
|
||||
};
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(99); }
|
||||
};
|
||||
using States = Fsm::States<Loop, Done>;
|
||||
|
||||
explicit Jumper(MachineOptions o = {}) : Fsm::Machine<Jumper>(o) {}
|
||||
};
|
||||
@@ -124,7 +128,7 @@ Void::Testing::Test jump_redirects_at_next_boundary()
|
||||
while (fsm.pump() > 0) {
|
||||
} // Loop -> next<Loop> -> park again
|
||||
|
||||
fsm.jump<Jumper::Done>(); // request a jump
|
||||
fsm.jump<Jumper::States::Done>(); // 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<Step> run() { co_return succeed(++self().runs); }
|
||||
struct States {
|
||||
struct Once : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(++self().runs);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Once>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -173,13 +181,14 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Fsm::States<A, B>; // initial = A
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> 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<Pick::B>();
|
||||
fsm.restart_at<Pick::States::B>();
|
||||
const auto second = fsm.wait();
|
||||
Void::Testing::expect_eq(*second, 2); // B
|
||||
}
|
||||
@@ -204,32 +213,33 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(2); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<StateKey> run() { co_return succeed(3); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> run() { co_return succeed(3); }
|
||||
};
|
||||
// Not in States<> — added via replace<>.
|
||||
// Not in States — added via replace<>.
|
||||
struct Extra : State {
|
||||
Task<Step> run() { co_return succeed(7); }
|
||||
Task<StateKey> run() { co_return succeed(7); }
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test remove_and_set_initial_before_start()
|
||||
{
|
||||
Mut fsm;
|
||||
Void::Testing::expect(fsm.has_state<Mut::C>());
|
||||
fsm.remove<Mut::C>();
|
||||
Void::Testing::expect(!fsm.has_state<Mut::C>());
|
||||
Void::Testing::expect(fsm.has_state<Mut::States::C>());
|
||||
fsm.remove<Mut::States::C>();
|
||||
Void::Testing::expect(!fsm.has_state<Mut::States::C>());
|
||||
Void::Testing::expect_eq(fsm.describe().size(), std::size_t{2});
|
||||
|
||||
fsm.set_initial<Mut::B>();
|
||||
fsm.set_initial<Mut::States::B>();
|
||||
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<Mut::A, Mut::Extra>(); // A was initial -> Extra becomes initial
|
||||
Void::Testing::expect(!fsm.has_state<Mut::A>());
|
||||
// A was initial -> Extra becomes initial.
|
||||
fsm.replace<Mut::States::A, Mut::Extra>();
|
||||
Void::Testing::expect(!fsm.has_state<Mut::States::A>());
|
||||
Void::Testing::expect(fsm.has_state<Mut::Extra>());
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect_eq(*outcome, 7);
|
||||
@@ -257,14 +268,15 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Go>();
|
||||
co_return succeed(5);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Go>();
|
||||
co_return succeed(5);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
#include <Void/Fsm/Fsm.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
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<StateKey>). 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<Annotated>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Pick : State {
|
||||
Task<StateKey> first() // declared first
|
||||
{
|
||||
co_return succeed(1);
|
||||
}
|
||||
[[= Fsm::entry]] Task<StateKey> chosen()
|
||||
{
|
||||
co_return succeed(2);
|
||||
}
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
// Two nullary entry candidates, none annotated → first-declared wins.
|
||||
class FirstWins : public Fsm::Machine<FirstWins>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Pick : State {
|
||||
Task<StateKey> first() { co_return succeed(1); }
|
||||
Task<StateKey> 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<Seeded>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Begin : State {
|
||||
Task<StateKey> run() // no startup data
|
||||
{
|
||||
co_return succeed(0);
|
||||
}
|
||||
Task<StateKey> run(int seed) // with startup data
|
||||
{
|
||||
co_return succeed(seed);
|
||||
}
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
class Launcher : public Fsm::Machine<Launcher>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Go : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Seeded, After>(7);
|
||||
}
|
||||
};
|
||||
struct After : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed(s.as<int>());
|
||||
}
|
||||
};
|
||||
};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test startup_entry_used_when_launched_with_data()
|
||||
{
|
||||
Launcher fsm; // Seeded launched via startMachine<Seeded, After>(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
|
||||
}
|
||||
@@ -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<int>* order = nullptr;
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
// Two typed mailboxes: pull whichever arrives.
|
||||
|
||||
@@ -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<Step> run()
|
||||
{
|
||||
auto ev = co_await await_any<Tick, Cancel>();
|
||||
if (std::holds_alternative<Cancel>(ev)) {
|
||||
co_return fail("cancelled");
|
||||
}
|
||||
co_return succeed(std::string{"ticked"});
|
||||
}
|
||||
struct States {
|
||||
struct Waiting : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto ev = co_await await_any<Tick, Cancel>();
|
||||
if (std::holds_alternative<Cancel>(ev)) {
|
||||
co_return fail("cancelled");
|
||||
}
|
||||
co_return succeed(std::string{"ticked"});
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Waiting>;
|
||||
|
||||
explicit Work(MachineOptions opts = {})
|
||||
: Void::Fsm::Machine<Work>(opts)
|
||||
@@ -57,23 +59,24 @@ namespace
|
||||
|
||||
using Success = std::string;
|
||||
|
||||
struct Running : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto r = co_await run_region<Work>();
|
||||
if (r.has_value()) {
|
||||
co_return succeed(*r);
|
||||
}
|
||||
co_return next<Aborted>();
|
||||
}
|
||||
struct States {
|
||||
struct Running : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto r = co_await run_region<Work>();
|
||||
if (r.has_value()) {
|
||||
co_return succeed(*r);
|
||||
}
|
||||
co_return next<Aborted>();
|
||||
}
|
||||
};
|
||||
struct Aborted : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(std::string{"aborted"});
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Aborted : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return succeed(std::string{"aborted"});
|
||||
}
|
||||
};
|
||||
using States = Void::Fsm::States<Running, Aborted>;
|
||||
|
||||
explicit Job(MachineOptions opts = {})
|
||||
: Void::Fsm::Machine<Job>(opts)
|
||||
|
||||
@@ -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<Sub>(Resume::History) re-enters a region at the sub-state it last
|
||||
@@ -23,17 +24,18 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
++g_a_runs;
|
||||
co_return next<B>();
|
||||
}
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
++g_a_runs;
|
||||
co_return next<B>();
|
||||
}
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(2); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Fsm::States<A, B>;
|
||||
};
|
||||
|
||||
class Host : public Fsm::Machine<Host>
|
||||
@@ -42,16 +44,18 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await run_region<Region>(); // Initial: A then B
|
||||
co_await run_region<Region>(
|
||||
Resume::History); // History: B only
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await run_region<Region>(); // Initial: A
|
||||
// then B
|
||||
co_await run_region<Region>(
|
||||
Resume::History); // History: B only
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
};
|
||||
} // 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<H2> {
|
||||
using Success = int;
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await run_region<Region>();
|
||||
co_await run_region<Region>(); // Initial again
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await run_region<Region>();
|
||||
co_await run_region<Region>(); // Initial again
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
};
|
||||
H2 fsm;
|
||||
const auto outcome = fsm.run_blocking();
|
||||
|
||||
@@ -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<std::string> log;
|
||||
|
||||
struct A : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter A");
|
||||
co_return;
|
||||
}
|
||||
Task<Step> run()
|
||||
{
|
||||
self().log.push_back("run A");
|
||||
co_return next<B>();
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit A");
|
||||
co_return;
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter A");
|
||||
co_return;
|
||||
}
|
||||
Task<StateKey> run()
|
||||
{
|
||||
self().log.push_back("run A");
|
||||
co_return next<B>();
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit A");
|
||||
co_return;
|
||||
}
|
||||
};
|
||||
|
||||
struct B : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter B");
|
||||
co_return;
|
||||
}
|
||||
Task<Step> run()
|
||||
{
|
||||
self().log.push_back("run B");
|
||||
co_return succeed(1);
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit B");
|
||||
co_return;
|
||||
}
|
||||
struct B : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter B");
|
||||
co_return;
|
||||
}
|
||||
Task<StateKey> run()
|
||||
{
|
||||
self().log.push_back("run B");
|
||||
co_return succeed(1);
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit B");
|
||||
co_return;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<A, B>;
|
||||
|
||||
Lifecycle()
|
||||
: Void::Fsm::Machine<Lifecycle>(
|
||||
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<NoRun> {
|
||||
struct Stuck : State {
|
||||
Task<void> on_enter() override { co_return; }
|
||||
// no run() override
|
||||
struct States {
|
||||
struct Stuck : State {
|
||||
Task<void> on_enter() override { co_return; }
|
||||
// no run() override
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Stuck>;
|
||||
NoRun()
|
||||
: Void::Fsm::Machine<NoRun>(MachineOptions{.own_worker = false})
|
||||
{
|
||||
|
||||
@@ -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<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
co_return succeed(m.seed * 10);
|
||||
@@ -45,7 +46,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Boom : State {
|
||||
Task<Step> run() { co_return fail("child boom"); }
|
||||
Task<StateKey> run() { co_return fail("child boom"); }
|
||||
};
|
||||
FailingChild()
|
||||
: Void::Fsm::Machine<FailingChild>(
|
||||
@@ -64,7 +65,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto a = co_await run_child<Subtotal>(3); // 30
|
||||
auto b = co_await run_child<Subtotal>(4); // 40
|
||||
@@ -91,7 +92,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto r = co_await run_child<FailingChild>();
|
||||
if (!r.has_value()) {
|
||||
@@ -136,7 +137,7 @@ Void::Testing::Test fsm_nesting_with_worker_thread()
|
||||
using Success = int;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto a = co_await run_child<Subtotal>(5); // 50
|
||||
co_return succeed(a.value_or(-1));
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::StateKey;
|
||||
using Void::Fsm::State;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// Orthogonal regions: run_parallel<A, B>() runs both sub-machines concurrently
|
||||
@@ -22,14 +23,15 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<GoLeft>();
|
||||
co_return succeed(1);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<GoLeft>();
|
||||
co_return succeed(1);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
|
||||
class Right : public Fsm::Machine<Right>
|
||||
@@ -37,14 +39,15 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<GoRight>();
|
||||
co_return succeed(2);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<GoRight>();
|
||||
co_return succeed(2);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
|
||||
// Joins both children: their results sum to 3.
|
||||
@@ -53,15 +56,17 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto [a, b] = co_await run_parallel<Left, Right>();
|
||||
co_return succeed((a.has_value() ? *a : 0) +
|
||||
(b.has_value() ? *b : 0));
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto [a, b] =
|
||||
co_await run_parallel<Left, Right>();
|
||||
co_return succeed((a.has_value() ? *a : 0) +
|
||||
(b.has_value() ? *b : 0));
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
|
||||
explicit Both(Fsm::MachineOptions o = {}) : Fsm::Machine<Both>(o) {}
|
||||
};
|
||||
@@ -107,21 +112,25 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto v = co_await run_parallel_any<Left, Right>();
|
||||
// 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<StateKey> run()
|
||||
{
|
||||
auto v =
|
||||
co_await run_parallel_any<Left, Right>();
|
||||
// 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<Run>;
|
||||
|
||||
explicit Race(Fsm::MachineOptions o = {}) : Fsm::Machine<Race>(o) {}
|
||||
};
|
||||
|
||||
@@ -4,11 +4,14 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
|
||||
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<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
const bool ok = co_await with_retry(
|
||||
m.retries, 1ms, [&m]() -> Task<bool> {
|
||||
++m.attempts;
|
||||
co_return m.attempts > m.fail_n;
|
||||
});
|
||||
co_return next_or<Fallback>(
|
||||
ok ? succeed(std::string{"ok"})
|
||||
: fail("exhausted"));
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct Try : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
const bool ok = co_await with_retry(
|
||||
m.retries, 1ms, [&m]() -> Task<bool> {
|
||||
++m.attempts;
|
||||
co_return m.attempts > m.fail_n;
|
||||
});
|
||||
co_return next_or<Fallback>(
|
||||
ok ? succeed(std::string{"ok"})
|
||||
: fail("exhausted"));
|
||||
}
|
||||
};
|
||||
|
||||
struct Fallback : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return succeed(std::string{"fallback"});
|
||||
}
|
||||
struct Fallback : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(std::string{"fallback"});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Try, Fallback>;
|
||||
|
||||
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<Step> run() { co_return next<B>(); }
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return next<B>(); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
using States = Void::Fsm::States<A, B>;
|
||||
Pipe()
|
||||
: Void::Fsm::Machine<Pipe>(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<Flow>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.event<Go>()
|
||||
.guard([](Flow&, const Go&) { return true; })
|
||||
.template to<Active>();
|
||||
on.event<Cancel>().template to<Done>();
|
||||
on.after(1h).template to<Done>();
|
||||
}
|
||||
struct States {
|
||||
struct Idle : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto ev = co_await await_any<Go, Cancel>();
|
||||
co_return std::holds_alternative<Go>(ev)
|
||||
? next<Active>()
|
||||
: next<Done>();
|
||||
}
|
||||
};
|
||||
struct Active : State {
|
||||
Task<StateKey> run() { co_return next<Done>(); }
|
||||
};
|
||||
struct Done : State {
|
||||
Task<StateKey> run() { co_return succeed(0); }
|
||||
};
|
||||
};
|
||||
struct Active : State {
|
||||
Task<Step> run() { co_return next<Done>(); }
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(0); }
|
||||
};
|
||||
using States = Void::Fsm::States<Idle, Active, Done>;
|
||||
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);
|
||||
}
|
||||
@@ -5,11 +5,13 @@
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
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<Gate>
|
||||
{
|
||||
public:
|
||||
@@ -32,42 +35,46 @@ namespace
|
||||
int total = 0;
|
||||
std::vector<std::string> trace;
|
||||
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
// Guarded: only positive amounts advance.
|
||||
on.event<Go>()
|
||||
.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<Idle>();
|
||||
on.event<Stop>().template to<Done>();
|
||||
on.after(10s).fail("idle timeout");
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct Idle : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
for (;;) {
|
||||
auto ev = co_await await_any<Go, Stop>();
|
||||
if (std::holds_alternative<Stop>(ev)) {
|
||||
co_return next<Done>();
|
||||
}
|
||||
const Go g = std::get<Go>(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<Step> run() { co_return succeed(self().total); }
|
||||
// Imperative terminal state: reports the accumulated total.
|
||||
struct Done : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(self().total);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Idle, Done>;
|
||||
|
||||
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<Step> run()
|
||||
{
|
||||
auto w = co_await await_event_for<Wake>(15ms);
|
||||
if (w.has_value()) {
|
||||
co_return succeed(std::string{"woken"});
|
||||
}
|
||||
co_return succeed(std::string{"timed_out"});
|
||||
}
|
||||
struct States {
|
||||
struct Waiting : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto w = co_await await_event_for<Wake>(15ms);
|
||||
if (w.has_value()) {
|
||||
co_return succeed(std::string{"woken"});
|
||||
}
|
||||
co_return succeed(std::string{"timed_out"});
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Waiting>;
|
||||
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<Deadline>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Pending : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.event<Wake>().template to<Resolved>();
|
||||
on.after(15ms).template to<Expired>();
|
||||
}
|
||||
struct States {
|
||||
struct Pending : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto w = co_await await_event_for<Wake>(15ms);
|
||||
co_return w.has_value() ? next<Resolved>()
|
||||
: next<Expired>();
|
||||
}
|
||||
};
|
||||
struct Resolved : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Expired : State {
|
||||
Task<StateKey> run() { co_return succeed(2); }
|
||||
};
|
||||
};
|
||||
struct Resolved : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Expired : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Void::Fsm::States<Pending, Resolved, Expired>;
|
||||
Deadline() {}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -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<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<int>(); // park here
|
||||
co_return next<Process>();
|
||||
}
|
||||
};
|
||||
struct Process : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
m.data.processed += 1;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
#include <Void/Fsm/Fsm.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
|
||||
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<Vending>
|
||||
{
|
||||
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<StateKey> run()
|
||||
{
|
||||
co_await await_event<Charge>(); // first coin -> start collecting
|
||||
co_return next<Collecting>();
|
||||
}
|
||||
};
|
||||
|
||||
struct Vending::States::Collecting : Vending::State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
for (;;) {
|
||||
auto ev = co_await await_any<Charge, Dispense>();
|
||||
if (std::holds_alternative<Dispense>(ev)) {
|
||||
co_return next<Done>();
|
||||
}
|
||||
m.credit += std::get<Charge>(ev).amount;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct Vending::States::Done : Vending::State {
|
||||
Task<StateKey> 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"});
|
||||
}
|
||||
@@ -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<Sub, Next>(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<T>()`. No override, no fixed names.
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -29,16 +30,17 @@ namespace
|
||||
using Success = int;
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run(int seed)
|
||||
{
|
||||
if (seed < 0) {
|
||||
co_return fail("negative");
|
||||
}
|
||||
co_return succeed(seed * 2);
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run(int seed)
|
||||
{
|
||||
if (seed < 0) {
|
||||
co_return fail("negative");
|
||||
}
|
||||
co_return succeed(seed * 2);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
};
|
||||
|
||||
class Calc : public Fsm::Machine<Calc>
|
||||
@@ -49,24 +51,27 @@ namespace
|
||||
|
||||
int input = 0;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return startMachine<Doubler, AfterDouble>(
|
||||
self().input);
|
||||
}
|
||||
struct States {
|
||||
struct Start : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Doubler, AfterDouble>(
|
||||
self().input);
|
||||
}
|
||||
};
|
||||
struct AfterDouble : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed("doubled:" +
|
||||
std::to_string(s.as<int>()));
|
||||
}
|
||||
Task<StateKey> no(ChildFailure f)
|
||||
{
|
||||
co_return succeed("failed:" +
|
||||
f.as<FsmError>().message);
|
||||
}
|
||||
};
|
||||
};
|
||||
struct AfterDouble : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed("doubled:" + std::to_string(s.value));
|
||||
}
|
||||
Task<Step> no(ChildFailure auto f)
|
||||
{
|
||||
co_return succeed("failed:" + f.value.message);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<Start, AfterDouble>;
|
||||
|
||||
explicit Calc(int in) : input(in) {}
|
||||
};
|
||||
@@ -98,10 +103,11 @@ namespace
|
||||
{
|
||||
public:
|
||||
|
||||
struct Ping : State {
|
||||
Task<Step> run() { co_return succeed(); }
|
||||
struct States {
|
||||
struct Ping : State {
|
||||
Task<StateKey> run() { co_return succeed(); }
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Ping>;
|
||||
};
|
||||
|
||||
class Host : public Fsm::Machine<Host>
|
||||
@@ -110,14 +116,21 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Go : State {
|
||||
Task<Step> run() { co_return startMachine<Pinger, Done>(); }
|
||||
struct States {
|
||||
struct Go : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Pinger, Done>();
|
||||
}
|
||||
};
|
||||
struct Done : State {
|
||||
// void-result sub: ChildSuccess box has no value.
|
||||
Task<StateKey> ok(ChildSuccess)
|
||||
{
|
||||
co_return succeed(42);
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Done : State {
|
||||
// void-result sub: ChildSuccess box has no value.
|
||||
Task<Step> ok(ChildSuccess auto) { co_return succeed(42); }
|
||||
};
|
||||
using States = Fsm::States<Go, Done>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -140,25 +153,27 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return startMachine<Doubler, B>(3); // 3 -> 6
|
||||
}
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Doubler, B>(3); // 3 -> 6
|
||||
}
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
// 6 -> 12
|
||||
co_return startMachine<Doubler, C>(s.as<int>());
|
||||
}
|
||||
};
|
||||
struct C : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed(s.as<int>());
|
||||
}
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return startMachine<Doubler, C>(s.value); // 6 -> 12
|
||||
}
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed(s.value);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -184,14 +199,15 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return succeed(7);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return succeed(7);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
|
||||
class Outer : public Fsm::Machine<Outer>
|
||||
@@ -200,16 +216,20 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Begin : State {
|
||||
Task<Step> run() { co_return startMachine<WaitSub, Fin>(); }
|
||||
struct States {
|
||||
struct Begin : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<WaitSub, Fin>();
|
||||
}
|
||||
};
|
||||
struct Fin : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed(s.as<int>());
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Fin : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed(s.value);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<Begin, Fin>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#include <Void/Functional/Retry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <expected>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Testing::Test;
|
||||
using namespace std::chrono_literals;
|
||||
namespace R = Void::Retry;
|
||||
|
||||
struct RetryJitter : Void::Testing::Suite<RetryJitter> {
|
||||
Test full_jitter_stays_within_bounds()
|
||||
{
|
||||
R::Jittered<R::ConstantDelay> 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<R::ConstantDelay> 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<R::ConstantDelay> policy;
|
||||
policy.max_attempts = 5;
|
||||
policy.backoff = R::ConstantDelay{0ms};
|
||||
policy.max_elapsed = 5ms;
|
||||
|
||||
int calls = 0;
|
||||
auto result =
|
||||
R::retry(policy, [&]() -> std::expected<int, int> {
|
||||
++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<R::Jittered<R::ConstantDelay>> policy;
|
||||
policy.max_attempts = 3;
|
||||
policy.backoff = {R::ConstantDelay{1ms}, R::JitterMode::Full};
|
||||
|
||||
int calls = 0;
|
||||
auto result =
|
||||
R::retry(policy, [&]() -> std::expected<int, int> {
|
||||
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
|
||||
@@ -0,0 +1,45 @@
|
||||
#include <Void/Log/Field.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#include <Void/Log/Field.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<StructuredFields> {
|
||||
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
|
||||
@@ -0,0 +1,89 @@
|
||||
#include <Void/Resilience/CircuitBreaker.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
|
||||
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<TP> now =
|
||||
std::make_shared<TP>(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<CircuitBreakerTests> {
|
||||
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<int, int>{42}; };
|
||||
const auto bad = [] {
|
||||
return std::expected<int, int>{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
|
||||
@@ -0,0 +1,75 @@
|
||||
#include <Void/Resilience/KeyedRateLimiter.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
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<TP> now =
|
||||
std::make_shared<TP>(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<KeyedRateLimiterTests> {
|
||||
// Each key drains its own bucket independently.
|
||||
Test keys_are_independent()
|
||||
{
|
||||
ManualClock clk;
|
||||
KeyedRateLimiter<std::uint64_t> 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<std::string> 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<int> 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<int> 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
|
||||
@@ -0,0 +1,55 @@
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
|
||||
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<TP> now =
|
||||
std::make_shared<TP>(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<RateLimiterTests> {
|
||||
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
|
||||
@@ -0,0 +1,51 @@
|
||||
#include <Void/Resilience/ResourceMonitor.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Resilience::ResourceMonitor;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ResourceMonitorTests : Void::Testing::Suite<ResourceMonitorTests> {
|
||||
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
|
||||
@@ -0,0 +1,19 @@
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<IClock>(),
|
||||
std::string{"IClock"});
|
||||
}
|
||||
@@ -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<Step> run()
|
||||
Task<StateKey> 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<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
int last = 0;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <memory>
|
||||
|
||||
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<ScopedRegistry> {
|
||||
Test child_falls_through_to_parent()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
parent.provide<IGreeter>(std::make_shared<Greeter>(1));
|
||||
|
||||
ServiceRegistry child{&parent};
|
||||
Void::Testing::expect(child.has<IGreeter>());
|
||||
Void::Testing::expect_eq(child.require<IGreeter>().id(), 1);
|
||||
}
|
||||
|
||||
Test child_shadows_parent()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
parent.provide<IGreeter>(std::make_shared<Greeter>(1));
|
||||
|
||||
ServiceRegistry child{&parent};
|
||||
child.provide<IGreeter>(std::make_shared<Greeter>(2));
|
||||
|
||||
Void::Testing::expect_eq(child.require<IGreeter>().id(), 2);
|
||||
// Parent is untouched.
|
||||
Void::Testing::expect_eq(parent.require<IGreeter>().id(), 1);
|
||||
}
|
||||
|
||||
Test child_local_provide_invisible_to_parent()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
ServiceRegistry child{&parent};
|
||||
child.provide<IOther>(std::make_shared<Other>());
|
||||
|
||||
Void::Testing::expect(child.has<IOther>());
|
||||
Void::Testing::expect(!parent.has<IOther>());
|
||||
}
|
||||
|
||||
Test miss_in_both_returns_nullptr()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
ServiceRegistry child{&parent};
|
||||
Void::Testing::expect(child.get<IGreeter>() == nullptr);
|
||||
Void::Testing::expect(!child.has<IGreeter>());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,43 @@
|
||||
#include <Void/System/Metrics.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct MetricsTests : Void::Testing::Suite<MetricsTests> {
|
||||
// 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<double>(i) * 0.5;
|
||||
}
|
||||
(void)sink;
|
||||
const double usage = sampler.usage();
|
||||
Void::Testing::expect(usage >= 0.0);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,66 @@
|
||||
#include <Void/System/Process.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ProcessStream : Void::Testing::Suite<ProcessStream> {
|
||||
// stdout lines are delivered to the callback as they arrive, and
|
||||
// the full output is still captured.
|
||||
Test streams_stdout_lines()
|
||||
{
|
||||
std::vector<std::string> 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<std::string> 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<std::string> 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<std::string> 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
|
||||
@@ -1,28 +1,27 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Fixture.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
class VectorFixture : public Void::Testing::Fixture
|
||||
namespace
|
||||
{
|
||||
public:
|
||||
using Void::Testing::Test;
|
||||
|
||||
std::vector<int> 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<ContainerFixture> {
|
||||
std::vector<int> 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
|
||||
@@ -0,0 +1,46 @@
|
||||
#include <Void/TestingMock/Reflect.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string_view>
|
||||
|
||||
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<MockReflect> {
|
||||
Test lists_virtual_methods()
|
||||
{
|
||||
const auto names = Void::TestingMock::method_names<IDb>();
|
||||
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<IDb>() == 2);
|
||||
}
|
||||
|
||||
Test covers_detects_completeness()
|
||||
{
|
||||
static_assert(Void::TestingMock::covers<GoodMock, IDb>());
|
||||
static_assert(!Void::TestingMock::covers<BadMock, IDb>());
|
||||
Void::Testing::expect(
|
||||
Void::TestingMock::covers<GoodMock, IDb>());
|
||||
Void::Testing::expect(
|
||||
!Void::TestingMock::covers<BadMock, IDb>());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
Reference in new issue
Block a user