21 Commits
Author SHA1 Message Date
faumaray 68d86f76a2 Build release artifacts with RelWithDebInfo
Release / release (push) Successful in 29m41s
2026-08-01 18:07:13 +03:00
faumaray cb58236538 Release 1.1.0 with transactional plugin validation 2026-08-01 17:59:57 +03:00
faumaray 4418374de7 Release: make checksums directly verifiable
Release / release (push) Successful in 1m6s
2026-07-30 03:42:14 +03:00
faumaray d1572a55a5 Release: export token for publisher
Release / release (push) Failing after 1m2s
2026-07-30 03:33:57 +03:00
faumaray f732845dc7 Release: use native Gitea job token
Release / release (push) Failing after 1m2s
2026-07-30 03:30:45 +03:00
faumaray c509aa7424 Make rotating logger failure test deterministic
Release / release (push) Failing after 21m4s
2026-07-30 02:03:44 +03:00
faumaray f528ef644c Align release workflow with Gitea Actions
Release / release (push) Failing after 20m42s
2026-07-29 23:11:54 +03:00
faumaray 721e11f4ce Remove assistant-only repository artifacts 2026-07-29 22:51:54 +03:00
faumaray 4c2b96ac69 Add reusable strict JSON, rate limiting, and sealed secrets 2026-07-29 22:40:15 +03:00
faumaray 7edce967f2 Update: align component feed identities
CI / GCC 16 / C++26 / werror (push) Failing after 1m57s
CI / GCC 16 / C++26 / default (push) Failing after 2m36s
CI / GCC 16 / C++26 / sanitizers (push) Failing after 2m39s
2026-07-29 00:41:57 +03:00
faumaray 05815c4668 Update: add component catalog transactions
CI / GCC 16 / C++26 / sanitizers (push) Failing after 2m35s
CI / GCC 16 / C++26 / default (push) Failing after 2m39s
CI / GCC 16 / C++26 / werror (push) Failing after 1m54s
2026-07-29 00:22:20 +03:00
faumaray 9d8b334b4b Plugin: initialize readiness detail
CI / GCC 16 / C++26 / default (push) Failing after 2m39s
CI / GCC 16 / C++26 / sanitizers (push) Failing after 2m40s
CI / GCC 16 / C++26 / werror (push) Failing after 1m54s
2026-07-28 23:18:07 +03:00
faumaray 541d4e8b6d Plugin: adapt legacy lifecycle to modules
CI / GCC 16 / C++26 / sanitizers (push) Failing after 2m42s
CI / GCC 16 / C++26 / default (push) Failing after 2m43s
CI / GCC 16 / C++26 / werror (push) Failing after 1m52s
2026-07-28 22:58:44 +03:00
faumaray fb5388a7ee Plugin: add reusable module descriptor
CI / GCC 16 / C++26 / sanitizers (push) Failing after 1m48s
CI / GCC 16 / C++26 / werror (push) Failing after 1m56s
CI / GCC 16 / C++26 / default (push) Failing after 7m11s
2026-07-28 22:33:51 +03:00
faumaray 053ee5b296 update
CI / GCC 16 / C++26 / sanitizers (push) Failing after 4s
CI / GCC 16 / C++26 / werror (push) Failing after 3s
CI / GCC 16 / C++26 / default (push) Failing after 1m48s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-25 23:42:52 +03:00
faumaray 3851aeb703 Update
CI / GCC 16 / C++26 / werror (push) Failing after 3m9s
CI / GCC 16 / C++26 / sanitizers (push) Failing after 10m15s
CI / GCC 16 / C++26 / default (push) Failing after 13m1s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-20 01:18:53 +03:00
faumaray 8583a479dd Update
CI / GCC 16 / C++26 / default (push) Has been cancelled
CI / GCC 16 / C++26 / sanitizers (push) Has been cancelled
CI / GCC 16 / C++26 / werror (push) Has been cancelled
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:49:06 +03:00
faumaray fa30098129 Update
CI / GCC 16 / C++26 / default (push) Has been cancelled
CI / GCC 16 / C++26 / sanitizers (push) Has been cancelled
CI / GCC 16 / C++26 / werror (push) Has been cancelled
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-12 03:00:38 +03:00
Aleksey Selihov 4fca5523f6 Merge pull request 'feat/plugin-system' (#2) from feat/plugin-system into main
CI / GCC 16 / C++26 / default (push) Has been cancelled
CI / GCC 16 / C++26 / sanitizers (push) Has been cancelled
CI / GCC 16 / C++26 / werror (push) Has been cancelled
Reviewed-on: Void/VoidLibrary#2
2026-07-11 23:40:11 +00:00
Aleksey Selihov 704d1a8e89 Merge branch 'main' into feat/plugin-system
CI / GCC 16 / C++26 / default (pull_request) Has been cancelled
CI / GCC 16 / C++26 / sanitizers (pull_request) Has been cancelled
CI / GCC 16 / C++26 / werror (pull_request) Has been cancelled
2026-07-11 23:38:22 +00:00
Aleksey Selihov 6f1b5f0b72 Merge pull request 'Process update and UdpSocket' (#1) from feat/plugin-system into main
CI / GCC 16 / C++26 / sanitizers (push) Has been cancelled
CI / GCC 16 / C++26 / werror (push) Has been cancelled
CI / GCC 16 / C++26 / default (push) Has been cancelled
Reviewed-on: Void/VoidLibrary#1
2026-07-11 18:44:30 +00:00
81 changed files with 11348 additions and 1249 deletions

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
name: Release
on:
push:
tags:
- "v*"
workflow_dispatch:
jobs:
release:
runs-on: echoion-release-serial
permissions:
contents: write
steps:
- name: Check out VoidLibrary
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
fetch-depth: 0
persist-credentials: false
- name: Check out pinned public release tooling
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
repository: Void/Echoion
ref: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
path: .release-tools
persist-credentials: false
- name: Verify immutable release inputs
shell: bash
run: |
set -euo pipefail
[[ "${{ vars.ECHOION_RELEASE_TOOLS_REF }}" =~ ^[0-9a-f]{40}$ ]]
test "$(git -C .release-tools rev-parse HEAD)" = \
"${{ vars.ECHOION_RELEASE_TOOLS_REF }}"
[[ "$GITHUB_REF_TYPE" == "tag" ]]
[[ "$GITHUB_REF_NAME" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]
version="${BASH_REMATCH[1]}"
project_version="$(
sed -nE \
's/^project\(Void VERSION ([0-9]+\.[0-9]+\.[0-9]+).*$/\1/p' \
CMakeLists.txt
)"
test "$version" = "$project_version"
- name: Configure
run: |
cmake -S . -B build-relwithdebinfo -G Ninja \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DBUILD_SHARED_LIBS=ON \
-DVOID_ENABLE_TESTING=ON \
-DVOID_WARNINGS_AS_ERRORS=ON
- name: Build and test
run: |
cmake --build build-relwithdebinfo --config RelWithDebInfo --parallel
ctest --test-dir build-relwithdebinfo \
--build-config RelWithDebInfo --output-on-failure
- name: Install and package
shell: bash
run: |
set -euo pipefail
version="${GITHUB_REF_NAME#v}"
package="voidlibrary-${version}-linux-x86_64"
epoch="$(git show -s --format=%ct HEAD)"
cmake --install build-relwithdebinfo \
--config RelWithDebInfo \
--prefix "$PWD/stage/$package"
python3 .release-tools/scripts/verify-relwithdebinfo.py \
--root "$PWD/stage/$package"
mkdir -p dist
SOURCE_DATE_EPOCH="$epoch" \
tar --sort=name --mtime="@$epoch" \
--owner=0 --group=0 --numeric-owner \
--zstd -cf "dist/$package.tar.zst" \
-C stage "$package"
(
cd dist
sha256sum "$package.tar.zst" > SHA256SUMS
)
- name: Publish native Gitea release
env:
GITEA_RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 .release-tools/scripts/gitea_release.py \
--api-url "${{ gitea.api_url }}" \
publish \
--owner Void \
--repo VoidLibrary \
--tag "$GITHUB_REF_NAME" \
--target "$GITHUB_SHA" \
--name "VoidLibrary ${GITHUB_REF_NAME#v}" \
--body "Reproducible VoidLibrary SDK and shared-library package." \
--artifacts dist
-1
View File
@@ -1,3 +1,2 @@
build
build*
CLAUDE.md
-228
View File
@@ -1,228 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Build
Requires CMake 4.0+ and a C++26 compiler. GCC 16+ is the default — it ships
the experimental `-freflection` flag and the `<meta>` header that several
modules use. Clang is supported but currently lacks P2996 reflection, so
modules that use it stay reflection-free behind `__has_include(<meta>)`.
```bash
# Configure (g++, Ninja, Debug)
cmake -B build -S . -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Debug
# Build
cmake --build build
# Run all tests
ctest --test-dir build
# Or run the single test binary directly (supports --filter, --parallel, ...)
./build/tests/VoidTests --filter "Json*"
```
Format code with:
```bash
clang-format -i <file>
```
## Architecture
VoidLibrary is a C++26 modular shared library organized as **umbrella modules** — one CMake target each, grouping related functionality. The C++ namespaces of absorbed components are unchanged (e.g. `Void::Ring` lives in `include/Void/Containers/Ring.hpp`, linked via `Void::Containers`).
| Module | Type | Contents |
|---|---|---|
| `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 |
| `Text` | INTERFACE | Str, Format, Tokenizer, Diff, Encoding, Semver |
| `Data` | INTERFACE | Json, Csv, Ini |
| `Async` | INTERFACE | Coro (Task, Generator), Concurrency (ThreadPool, Channel, ParallelFor), EventBus, Observable |
| `Time` | INTERFACE | Stopwatch, Format (durations/ISO-8601), Bench |
| `Log` | SHARED | `Void::Log` header-only facade + `Void::Logging` framework |
| `System` | SHARED | FileSystem (Path, Query, TempDir) + Process |
| `Configuration` | SHARED | Config, Env + Argparse |
| `Stacktrace` | SHARED | Boost.Stacktrace capture, color helpers (kept separate to isolate the Boost dep) |
| `Plugin` | SHARED | dlopen loader + manager, C ABI, hot reload (see below) |
| `Service` | INTERFACE | `IService` + type-keyed `ServiceRegistry` (DI); plugin-service bridge |
| `Fsm` | SHARED | inheritance + coroutine workflow FSM + `Orchestrator` (see below) |
| `Testing` / `TestingMock` | STATIC / INTERFACE | test + mock frameworks |
`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`.
Module layout:
- Headers: `include/Void/<Module>/*.hpp`
- Sources: `src/<Module>/*.cpp`
- CMake target: `Void_<Module>` with alias `Void::<Module>`
Every header-only module **must** have at least a one-line `src/<Module>/module.cmake` (`void_add_module(<Module>)`) — git does not track empty directories, and discovery iterates `src/*`.
`void_add_module` accepts three dependency lists:
- `INTERNAL_DEPS` — other `Void::*` modules (linked unconditionally).
- `EXTERNAL_DEPS` — third-party targets fetched via `cmake/Dependencies.cmake` (`FetchContent`); add new ones there before referencing.
- `OPTIONAL_DEPS` — `Void::*` modules linked only if they exist; each present dep additionally defines `VOID_HAS_<UPPERCASE>` for conditional code. Resolution is deferred to `void_finalize_modules()`, so it does not depend on discovery order.
### Tests
All tests compile into **one binary**, `build/tests/VoidTests` (registered as the single ctest entry):
| Category | Location | Suite label |
|---|---|---|
| Standalone | `tests/standalone/<Module>/<Feature>.cpp` | `<Feature>` (file stem) |
| Internal (cross-module) | `tests/internal/*.cpp` | `internal_<stem>` |
**The `tests/standalone/<Module>` directory name must exactly match a module name** — the scanner iterates registered modules and silently skips unknown directories. After moving/renaming tests, compare the runner's total test count.
#### Writing a test
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/Suite.hpp>
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() { /*…*/ }
};
}
```
- 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`.
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.
**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
Two layers, both in the `Log` module:
**`Void::Log` facade** (`Log/Log.hpp`, header-only — usable from any module with zero link deps). Leveled function templates `Log::trace/debug/info/warn/error/fatal("Module.Feature", fmt, args...)` format lazily — with no sink installed a call is one relaxed atomic load and zero allocation. `set_sink(fn)` routes everything to any callable (this is the hook for external logging libraries; `LoggingAdapter.hpp` bridges to `Void::Logging`). `set_min_level` + `set_module_level` filter before formatting. **No macros** — this codebase forbids macro APIs; behavior toggles are runtime options.
**`Void::Logging::Logger`** — abstract sink base class, **async by default**: entries go through a lock-free MPSC queue to a logger-owned worker thread that delivers batches via `on_flush`. `Mode::Immediate`/`Buffered` make the same class synchronous (constructor arg or `set_mode` — no separate async/sync classes). Async capacity + `OverflowPolicy{Block,DropNewest,DropOldest}` bound the queue. `flush()` blocks until everything submitted before the call is delivered; it is virtual so composite sinks propagate it.
Deriving a sink:
1. **Override `write(const Entry&)`** — called per-entry (worker thread in Async mode).
2. **Optionally override `on_flush(std::span<const Entry>)`** — for batch I/O.
3. **Call `flush()` in your derived destructor** — the base destructor only stops/joins the worker (calling a pure virtual from `~Logger` is UB); entries left after your destructor are silently dropped.
Shipped sinks: `ConsoleLogger` (color via a default colored `PatternFormatter`; `set_color_policy`), `FileLogger`, `RotatingFileLogger`, `SplitFileLogger` (one file per level under a dir + a combined `all.log`), `HistoryLogger` (always-on, never-filtered durable JSON-lines audit trail, rolling), `NullLogger`, `CallbackLogger`, `MultiLogger` (tee; uses `Logger::relay`), `SyslogLogger` (POSIX). File rotation is factored into `Detail::RollingFile` (size + max-files), shared by the rotating/split/history sinks.
`Formatter`s: `PatternFormatter`, `JsonLinesFormatter`, `LogfmtFormatter`. The pattern grammar is `{token:spec}` where spec = `[align][width][,color]` (align `<`/`>`/`^`, width like std::format, color a name or `auto`=level color). Built-in tokens: `time/level/thread/scopes/message/file/line/kind`; unknown tokens resolve against `register_token(name, fn)` custom renderers, then `Entry::fields` by key, else stay literal. `ColorPolicy{enabled, level_colors, token_colors}` (`ColorPolicy::defaults()`) drives color; only `PatternFormatter` colorizes, never file/JSON/logfmt. Structured fields come from `Logging::FieldScope` (RAII, thread-local, snapshotted into `Entry::fields` like scopes). `from_config` sink keys: `console/file/rotating/split/history/syslog` plus `log.color`, `log.split.dir`, `log.split.combined`, `log.history.path`, etc.
`Logging::from_config(cfg)` builds the whole tree from `Configuration::Config` keys (`log.sinks`, `log.level`, `log.format`, `log.async`, ...); `apply_facade_config` sets facade levels.
Other key points:
- Virtual extension points are called **outside** any internal lock.
- `Level::Disabled` suppresses all output. `Trace < Debug < ... < Fatal`.
- `push_scope(name)` returns a RAII `ScopedContext` (breadcrumbs in `Entry::scopes`); `scope(name)` emits a boundary pair without touching the stack.
- `make_preset(level, prefix)` returns a non-owning `Preset` callable.
- Stop logging from other threads before destroying a logger.
### 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 `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
`Void::Service` — dependency inversion + FSM orchestration.
- `IService` base (`service_name()`, `on_start()`/`on_stop()` lifecycle).
- `ServiceRegistry` — type-keyed: `provide<I>(impl)`, `get<I>()` (nullptr if absent), `require<I>()` (throws), `has<I>()`, `remove<I>()` (withdraws the local entry; holders keep the instance alive, a parent's entry is re-exposed), `start_all()`/`stop_all()`. Consumers depend only on interface `I` and resolve at runtime; a concrete deriving `IService` is recovered for lifecycle via `dynamic_cast` even when registered under a plain interface. `shared_mutex`, reads are the hot path.
- `Fsm::Orchestrator` (in the Fsm module): owns a `ServiceRegistry`, `launch<F>(args...)` constructs an FSM, injects the registry (`set_services`), starts and supervises it via a `FsmHandle` (status/stop); `stop_all()` is balanced once against `start_services()`.
- `Service/PluginService.hpp`: `PluginServiceBinding<I>` binds a plugin-provided service into a registry and re-binds on hot reload. The interface `I` must derive `IService` (single inheritance) so the host recovers it from the plugin's exported `IService*` by `static_cast` — no `dynamic_cast` across the RTLD_LOCAL boundary. The registry entry pins the plugin instance.
### Fsm module (inheritance + coroutine workflow)
`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 `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 (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, 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 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).
- **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.
### Plugin module (hot reload)
`Void::Plugin` loads C-ABI plugins (`.so`) and hot-reloads them with state transfer:
- **C ABI** (`Plugin.hpp`): required `void_plugin_create/destroy/info`; optional `void_plugin_transfer_state(old,new)` (raw), `void_plugin_configure(inst, config)` (host-supplied config string, called after create and after each reload swap, before `on_load()`), and the v2 state protocol `void_plugin_state_version` + `void_plugin_serialize_state`/`void_plugin_free_string` + `void_plugin_deserialize_state(inst, json, from_version)`. `ABI_VERSION` is checked; `IPlugin`'s vtable is frozen (append-only). State transfer prefers v2 serialize→deserialize (survives layout changes; migrations live in the *new* .so via `Json::MigrationChain`), falling back to `transfer_state`.
- **`PluginLoader`** — owns one instance; `reload()` copies the `.so` to a fresh-inode temp (so `dlopen` loads new bytes), creates the new instance, transfers state, swaps, destroys the old. Move-only.
- **`PluginManager`** — multi-plugin registry with **RCU-style pinned handles**: `acquire(name)` returns a `PluginHandle` (one `atomic<shared_ptr>` load) that keeps its instance alive for the whole call; `reload(name)` builds the new instance, transfers state, then `atomic_exchange`s it in — in-flight handles keep the old instance (and its mapped `.so`, since `dlclose_on_swap=false`) alive until they drop. Work never stops. `watch(name)` auto-reloads via `FileSystem::FileWatcher`. Discovery: `load_directory(dir)` loads every shared-library file in a directory (filename order, per-file `expected` results). `unload(name)` drops the registry entry (instance dies with its last handle). `on_reloaded(cb)` is **multi-observer** — it returns a `ReloadCallbackId` for `remove_on_reloaded` and fires after every successful reload, manual or watched. `PluginManagerOptions::config_provider` feeds `void_plugin_configure`. Host-side state carry: `serialize_state(name)` → `StateSnapshot{json, version}` and `deserialize_state(name, json, from_version)` wrap the plugin's v2 exports so an embedder can persist plugin state across its *own* hot reload.
- **Reload safety rule**: deployments must install the new `.so` by **atomic rename (fresh inode)**, never by overwriting the mapped file in place — in-place overwrite corrupts the running instance's mmap (SIGBUS). The tests' `install()` helper shows the pattern (copy to `.incoming`, then rename).
## Code style
Enforced by `.clang-format` (LLVM-based): 4-space indent (tabs), 80-column limit, Linux brace wrapping style, pointer alignment right.
+16 -6
View File
@@ -1,5 +1,12 @@
cmake_minimum_required(VERSION 4.0.0)
project(Void VERSION 1.0.0 LANGUAGES CXX)
project(Void VERSION 1.1.0 LANGUAGES CXX)
if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
elseif(NOT DEFINED BUILD_SHARED_LIBS)
# Keep Void's shared default local when embedded so a dependency does not
# silently change the linkage policy of its parent project.
set(BUILD_SHARED_LIBS ON)
endif()
option(VOID_ENABLE_TESTING "Build the test suite" ON)
option(VOID_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF)
option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
@@ -41,14 +48,17 @@ if(VOID_ENABLE_TESTING)
endif()
get_property(ALL_DISCOVERED_MODULES GLOBAL PROPERTY VOID_MODULES)
get_property(ALL_EXTERNAL_DEPS GLOBAL PROPERTY VOID_EXT_DEPS)
get_property(ALL_MODULE_DEPENDENCY_RECORDS GLOBAL PROPERTY
VOID_MODULE_DEPENDENCY_RECORDS)
if(ALL_EXTERNAL_DEPS)
list(REMOVE_DUPLICATES ALL_EXTERNAL_DEPS)
set(VOID_MODULES_LIST "${ALL_DISCOVERED_MODULES}")
set(VOID_MODULE_DEPENDENCY_RECORDS "${ALL_MODULE_DEPENDENCY_RECORDS}")
if(WIN32 AND NOT CYGWIN)
set(VOID_BOOST_STACKTRACE_COMPONENT stacktrace_windbg)
else()
set(VOID_BOOST_STACKTRACE_COMPONENT stacktrace_addr2line)
endif()
set(VOID_EXTERNAL_DEPS_LIST "${ALL_EXTERNAL_DEPS}")
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
VERSION ${PROJECT_VERSION}
+2 -2
View File
@@ -96,5 +96,5 @@ namespace and auto-loads the test scanner so downstream projects can use
Tests are free functions or methods on a `Void::Testing::Fixture` subclass
returning `Void::Testing::Test` (or `Void::Testing::DisabledTest`).
Registration is automatic — the CMake test scanner parses each `.cpp` at
configure time and generates the registration shim. See `CLAUDE.md` for the
comment-metadata syntax (`// @tag`, `// @skip`).
configure time and generates the registration shim. Free-function tests can
use `// @tag` and `// @skip` comment metadata.
+14
View File
@@ -0,0 +1,14 @@
# Isolated completeness probe used by cmake/Dependencies.cmake. Imported
# targets created by a failed find_package stay scoped to this directory, so a
# subsequent FetchContent fallback can define its own Boost targets safely.
if(WIN32 AND NOT CYGWIN)
set(_stacktrace_component stacktrace_windbg)
else()
set(_stacktrace_component stacktrace_addr2line)
endif()
find_package(Boost CONFIG QUIET
COMPONENTS ${_stacktrace_component} url)
if(TARGET Boost::${_stacktrace_component} AND TARGET Boost::url)
set_property(GLOBAL PROPERTY VOID_COMPLETE_SYSTEM_BOOST TRUE)
endif()
+129 -13
View File
@@ -1,33 +1,127 @@
include(FetchContent)
function(void_ensure_boost_header_targets)
if(NOT TARGET Boost::headers AND TARGET Boost::boost)
add_library(Boost::headers INTERFACE IMPORTED)
set_property(TARGET Boost::headers PROPERTY
INTERFACE_LINK_LIBRARIES Boost::boost)
endif()
foreach(_component IN ITEMS beast asio)
if(NOT TARGET Boost::${_component} AND
TARGET boost_${_component})
add_library(Boost::${_component} ALIAS boost_${_component})
elseif(NOT TARGET Boost::${_component} AND TARGET Boost::headers)
# System Boost packages commonly expose one aggregate include
# target rather than per-header-library targets.
add_library(Boost::${_component} INTERFACE IMPORTED)
set_property(TARGET Boost::${_component} PROPERTY
INTERFACE_LINK_LIBRARIES Boost::headers)
endif()
endforeach()
endfunction()
function(void_install_fetched_boost_runtime)
get_property(_runtime_registered GLOBAL
PROPERTY VOID_FETCHED_BOOST_RUNTIME_REGISTERED)
if(_runtime_registered)
return()
endif()
set_property(GLOBAL PROPERTY VOID_FETCHED_BOOST_RUNTIME_REGISTERED TRUE)
# Boost disables its install rules when consumed through add_subdirectory.
# Register the selected shared runtime closure explicitly so an installed
# shared Void package never points back into its build tree.
foreach(_target IN ITEMS
boost_container
boost_context
boost_coroutine
boost_date_time
boost_stacktrace_addr2line
boost_stacktrace_windbg
boost_url)
if(TARGET ${_target})
get_target_property(_type ${_target} TYPE)
if(_type STREQUAL "SHARED_LIBRARY" OR
_type STREQUAL "MODULE_LIBRARY")
if(UNIX)
set_property(TARGET ${_target} PROPERTY
INSTALL_RPATH "$ORIGIN")
endif()
install(TARGETS ${_target}
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
endif()
endif()
endforeach()
endfunction()
function(void_fetch_dependency DEP_NAME)
if(DEP_NAME STREQUAL "Boost")
# Components Void uses across modules: stacktrace_backtrace (Stacktrace),
# url + system (Net; beast/asio are header-only and come via Boost::headers).
if(TARGET Boost::stacktrace_backtrace AND TARGET Boost::url)
if(WIN32 AND NOT CYGWIN)
set(_stacktrace_component stacktrace_windbg)
else()
set(_stacktrace_component stacktrace_addr2line)
endif()
# Components Void uses across modules: a platform Stacktrace backend,
# plus url, beast, and asio (Net).
if(TARGET Boost::${_stacktrace_component} AND TARGET Boost::url)
void_ensure_boost_header_targets()
return()
endif()
# On modern Boost (1.85+) system/asio/beast are header-only and folded
# into Boost::headers; only stacktrace_backtrace and url are components.
find_package(Boost QUIET COMPONENTS stacktrace_backtrace url)
if(TARGET Boost::stacktrace_backtrace AND TARGET Boost::url)
# Probe in a child directory because a failed component-aware
# find_package(Boost) can still leave partial imported targets such as
# Boost::headers in its directory scope. Those partial targets collide
# with Boost's FetchContent build. Imported targets created by this
# probe stay in the child scope; only a boolean result is exported.
get_property(_boost_probe_ran GLOBAL
PROPERTY VOID_COMPLETE_SYSTEM_BOOST SET)
if(NOT _boost_probe_ran)
set_property(GLOBAL PROPERTY VOID_COMPLETE_SYSTEM_BOOST FALSE)
add_subdirectory(
"${CMAKE_CURRENT_FUNCTION_LIST_DIR}/BoostProbe"
"${PROJECT_BINARY_DIR}/void-boost-probe"
EXCLUDE_FROM_ALL)
endif()
get_property(_complete_system_boost GLOBAL
PROPERTY VOID_COMPLETE_SYSTEM_BOOST)
if(_complete_system_boost)
# On modern Boost, beast/asio are header-only and folded into
# Boost::headers. The fetched Asio target carries its own System
# dependency; requiring a separate system component here rejects
# otherwise complete distro packages where Boost.System is folded
# into Boost::headers.
find_package(Boost CONFIG REQUIRED
COMPONENTS ${_stacktrace_component} url)
void_ensure_boost_header_targets()
return()
endif()
if(TARGET Boost::headers OR TARGET Boost::boost)
message(FATAL_ERROR
"[Void] Incomplete Boost targets already exist in the parent "
"project. Provide ${_stacktrace_component} and url before "
"adding Void, or let Void resolve Boost first.")
endif()
message(STATUS "[Void] Boost (stacktrace/url) not found — falling back to FetchContent")
set(BOOST_INCLUDE_LIBRARIES "stacktrace;url;system;beast;asio" CACHE STRING "" FORCE)
set(BOOST_ENABLE_CMAKE ON CACHE BOOL "" FORCE)
# Keep Boost's selection local to this dependency resolution. Avoid
# overwriting a parent project's cache when Void is embedded.
set(BOOST_INCLUDE_LIBRARIES "stacktrace;url;system;beast;asio")
FetchContent_Declare(Boost
URL https://github.com/boostorg/boost/releases/download/boost-1.84.0/boost-1.84.0.tar.xz
URL_HASH SHA256=2e64e5d79a738d0fa6fb546c6e5c2bd28f88d268a2a080546f74e5ff98f29d0e
EXCLUDE_FROM_ALL
)
FetchContent_MakeAvailable(Boost)
if(NOT TARGET Boost::stacktrace_backtrace AND TARGET boost_stacktrace_backtrace)
add_library(Boost::stacktrace_backtrace ALIAS boost_stacktrace_backtrace)
if(NOT TARGET Boost::${_stacktrace_component} AND
TARGET boost_${_stacktrace_component})
add_library(Boost::${_stacktrace_component}
ALIAS boost_${_stacktrace_component})
endif()
void_ensure_boost_header_targets()
void_install_fetched_boost_runtime()
return()
endif()
@@ -47,9 +141,31 @@ function(void_fetch_dependency DEP_NAME)
endif()
if(DEP_NAME STREQUAL "SQLite3")
if(NOT TARGET SQLite3::SQLite3)
if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3)
find_package(SQLite3 REQUIRED)
endif()
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif()
return()
endif()
if(DEP_NAME STREQUAL "Sodium")
if(TARGET Sodium::Sodium)
return()
endif()
find_package(PkgConfig REQUIRED)
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
add_library(Sodium::Sodium INTERFACE IMPORTED)
set_property(TARGET Sodium::Sodium PROPERTY
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
return()
endif()
if(DEP_NAME STREQUAL "LibArchive")
if(NOT TARGET LibArchive::LibArchive)
find_package(LibArchive REQUIRED)
endif()
return()
endif()
# FIXME: Add if needed external
+93 -4
View File
@@ -1,5 +1,5 @@
set_property(GLOBAL PROPERTY VOID_MODULES "")
set_property(GLOBAL PROPERTY VOID_EXT_DEPS "")
set_property(GLOBAL PROPERTY VOID_MODULE_DEPENDENCY_RECORDS "")
set_property(GLOBAL PROPERTY VOID_PENDING_OPTIONAL_DEPS "")
function(void_add_module MODULE_NAME)
@@ -35,16 +35,62 @@ function(void_add_module MODULE_NAME)
target_sources(${TGT} PRIVATE ${SRC})
target_compile_features(${TGT} PUBLIC cxx_std_26)
endif()
get_target_property(_module_target_type ${TGT} TYPE)
if(_module_target_type STREQUAL "SHARED_LIBRARY" OR
_module_target_type STREQUAL "MODULE_LIBRARY")
# External packages are implementation details of compiled shared
# modules: Void's installed public headers do not expose their types.
# Keeping these links private also lets a shared Void SDK carry a
# fetched runtime dependency without requiring that dependency's CMake
# development package on every consumer machine.
set(_external_scope PRIVATE)
set(_record_external_dependencies FALSE)
else()
set(_external_scope ${SCOPE})
set(_record_external_dependencies TRUE)
endif()
add_library(${ALIAS} ALIAS ${TGT})
set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME})
set(_module_external_deps "")
foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS)
string(REGEX REPLACE "::.*" "" BASE_DEP ${ext_dep})
set_property(GLOBAL APPEND PROPERTY VOID_EXT_DEPS ${BASE_DEP})
# FindSQLite3's package name and imported-target namespace differ.
# Preserve the package name in exported dependency metadata.
if(ext_dep MATCHES "^SQLite::")
set(BASE_DEP SQLite3)
else()
string(REGEX REPLACE "::.*" "" BASE_DEP ${ext_dep})
endif()
if(_record_external_dependencies)
list(APPEND _module_external_deps ${BASE_DEP})
endif()
include(cmake/Dependencies.cmake)
void_fetch_dependency(${BASE_DEP})
if(NOT TARGET ${ext_dep})
message(FATAL_ERROR
"[Void] Dependency '${ext_dep}' required by module "
"'${MODULE_NAME}' was not provided")
endif()
endforeach()
set(_module_internal_deps ${ARG_INTERNAL_DEPS} ${ARG_OPTIONAL_DEPS})
if(_module_internal_deps)
list(REMOVE_DUPLICATES _module_internal_deps)
string(REPLACE ";" "," _module_internal_record
"${_module_internal_deps}")
else()
set(_module_internal_record "-")
endif()
if(_module_external_deps)
list(REMOVE_DUPLICATES _module_external_deps)
string(REPLACE ";" "," _module_external_record
"${_module_external_deps}")
else()
set(_module_external_record "-")
endif()
set_property(GLOBAL APPEND PROPERTY VOID_MODULE_DEPENDENCY_RECORDS
"${MODULE_NAME}|${_module_internal_record}|${_module_external_record}")
foreach(int_dep IN LISTS ARG_INTERNAL_DEPS)
target_link_libraries(${TGT} ${SCOPE} ${PROJECT_NAME}::${int_dep})
endforeach()
@@ -59,7 +105,41 @@ function(void_add_module MODULE_NAME)
endif()
if(ARG_EXTERNAL_DEPS)
target_link_libraries(${TGT} ${SCOPE} ${ARG_EXTERNAL_DEPS})
if(_external_scope STREQUAL "PRIVATE")
foreach(_external_dep IN LISTS ARG_EXTERNAL_DEPS)
string(MAKE_C_IDENTIFIER "${_external_dep}"
_external_dep_identifier)
set(_build_external_target
"_void_${MODULE_NAME}_${_external_dep_identifier}")
add_library(${_build_external_target} INTERFACE IMPORTED)
set_property(TARGET ${_build_external_target} PROPERTY
INTERFACE_LINK_LIBRARIES "${_external_dep}")
target_link_libraries(${TGT} PRIVATE
"$<BUILD_INTERFACE:${_build_external_target}>")
endforeach()
else()
# Keep fetched dependency build targets out of Void's install
# export. Static and interface consumers still receive the same
# canonical targets after find_dependency().
foreach(_external_dep IN LISTS ARG_EXTERNAL_DEPS)
string(MAKE_C_IDENTIFIER "${_external_dep}"
_external_dep_identifier)
set(_build_external_target
"_void_${MODULE_NAME}_${_external_dep_identifier}")
add_library(${_build_external_target} INTERFACE IMPORTED)
set_property(TARGET ${_build_external_target} PROPERTY
INTERFACE_LINK_LIBRARIES "${_external_dep}")
# Defer namespace reconstruction until a consumer evaluates
# the installed target. Otherwise CMake canonicalizes aliases
# from a FetchContent dependency (Boost::url -> boost_url) and
# requires the third-party target in Void's export set.
string(REPLACE "::" "$<1:::>" _install_external_dep
"${_external_dep}")
target_link_libraries(${TGT} ${_external_scope}
"$<BUILD_INTERFACE:${_build_external_target}>"
"$<INSTALL_INTERFACE:${_install_external_dep}>")
endforeach()
endif()
endif()
foreach(_lib IN LISTS ARG_DEPS_WIN32)
@@ -121,6 +201,15 @@ function(void_add_module MODULE_NAME)
CXX_EXTENSIONS OFF
EXPORT_NAME ${MODULE_NAME}
)
if(UNIX AND _module_target_type STREQUAL "SHARED_LIBRARY")
set_property(TARGET ${TGT} PROPERTY INSTALL_RPATH "$ORIGIN")
endif()
if(WIN32 AND _module_target_type STREQUAL "SHARED_LIBRARY")
# Void's public headers do not require consumers to opt into a DLL
# import macro. Generate the export table for compiled shared modules
# so the same installed targets remain usable on Windows.
set_property(TARGET ${TGT} PROPERTY WINDOWS_EXPORT_ALL_SYMBOLS ON)
endif()
# GCC 16+ exposes experimental C++26 reflection (P2996) via -freflection.
# Apply it to every module unconditionally so any module is free to use
+97 -2
View File
@@ -2,10 +2,97 @@
include(CMakeFindDependencyMacro)
set(_void_external_deps "@VOID_EXTERNAL_DEPS_LIST@")
set(_void_known_modules "@VOID_MODULES_LIST@")
set(_void_module_dependency_records "@VOID_MODULE_DEPENDENCY_RECORDS@")
function(_void_module_dependencies module out_internal out_external)
foreach(record IN LISTS _void_module_dependency_records)
string(REPLACE "|" ";" fields "${record}")
list(GET fields 0 record_module)
if(NOT record_module STREQUAL module)
continue()
endif()
list(GET fields 1 internal_csv)
list(GET fields 2 external_csv)
if(internal_csv STREQUAL "-")
set(internal "")
else()
string(REPLACE "," ";" internal "${internal_csv}")
endif()
if(external_csv STREQUAL "-")
set(external "")
else()
string(REPLACE "," ";" external "${external_csv}")
endif()
set(${out_internal} "${internal}" PARENT_SCOPE)
set(${out_external} "${external}" PARENT_SCOPE)
return()
endforeach()
set(${out_internal} "" PARENT_SCOPE)
set(${out_external} "" PARENT_SCOPE)
endfunction()
# With no requested components, preserve the historical all-modules package
# behavior. Component-aware consumers resolve only the transitive dependencies
# of the modules they explicitly request.
if(Void_FIND_COMPONENTS)
set(_void_pending_modules ${Void_FIND_COMPONENTS})
else()
set(_void_pending_modules ${_void_known_modules})
endif()
set(_void_required_modules "")
while(_void_pending_modules)
list(POP_FRONT _void_pending_modules module)
if(NOT module IN_LIST _void_known_modules OR
module IN_LIST _void_required_modules)
continue()
endif()
list(APPEND _void_required_modules "${module}")
_void_module_dependencies("${module}" internal_deps external_deps)
list(APPEND _void_pending_modules ${internal_deps})
endwhile()
set(_void_external_deps "")
foreach(module IN LISTS _void_required_modules)
_void_module_dependencies("${module}" internal_deps external_deps)
list(APPEND _void_external_deps ${external_deps})
endforeach()
if(_void_external_deps)
list(REMOVE_DUPLICATES _void_external_deps)
endif()
foreach(dep IN LISTS _void_external_deps)
if(dep STREQUAL "Boost")
find_dependency(Boost REQUIRED COMPONENTS stacktrace_backtrace)
find_dependency(Boost CONFIG REQUIRED COMPONENTS
@VOID_BOOST_STACKTRACE_COMPONENT@ url)
if(NOT TARGET Boost::headers AND TARGET Boost::boost)
add_library(Boost::headers INTERFACE IMPORTED)
set_property(TARGET Boost::headers PROPERTY
INTERFACE_LINK_LIBRARIES Boost::boost)
endif()
foreach(_component IN ITEMS beast asio)
if(NOT TARGET Boost::${_component} AND TARGET Boost::headers)
add_library(Boost::${_component} INTERFACE IMPORTED)
set_property(TARGET Boost::${_component} PROPERTY
INTERFACE_LINK_LIBRARIES Boost::headers)
endif()
endforeach()
elseif(dep STREQUAL "Sodium")
find_dependency(PkgConfig REQUIRED)
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
if(NOT TARGET Sodium::Sodium)
add_library(Sodium::Sodium INTERFACE IMPORTED)
set_property(TARGET Sodium::Sodium PROPERTY
INTERFACE_LINK_LIBRARIES PkgConfig::SODIUM)
endif()
elseif(dep STREQUAL "LibArchive")
find_dependency(LibArchive REQUIRED)
elseif(dep STREQUAL "SQLite3")
find_dependency(SQLite3 REQUIRED)
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif()
elseif(NOT TARGET ${dep})
find_dependency(${dep})
endif()
@@ -13,6 +100,14 @@ endforeach()
include("${CMAKE_CURRENT_LIST_DIR}/@EXPORT_SET_NAME@.cmake")
foreach(component IN LISTS Void_FIND_COMPONENTS)
if(TARGET Void::${component})
set(Void_${component}_FOUND TRUE)
else()
set(Void_${component}_FOUND FALSE)
endif()
endforeach()
# Auto-load the testing helper so consumers get void_add_tests + the
# auto-scan sweep just by find_package(Void).
if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/VoidTesting.cmake")
+16 -3
View File
@@ -51,7 +51,11 @@ foreach(line IN LISTS lines)
if(_match)
string(REGEX REPLACE "^[ \t]*class[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*:.*" "\\1" fixture_class_name "${line}")
set(in_fixture_class TRUE)
string(REGEX MATCH "^[ \t]*" fixture_indent "${line}")
# Derive indentation without an empty-match-capable regex. CMake 4
# rejects such expressions even when the current input is non-empty.
string(STRIP "${line}" _trimmed_fixture_line)
string(FIND "${line}" "${_trimmed_fixture_line}" _indent_length)
string(SUBSTRING "${line}" 0 ${_indent_length} fixture_indent)
endif()
if(in_fixture_class)
@@ -127,8 +131,17 @@ foreach(line IN LISTS lines)
set(current_skip "")
else()
# If line is code (not comment/empty), break the comment association
string(REGEX MATCH "^[ \t]*$" _is_empty "${line}")
string(REGEX MATCH "^[ \t]*//" _is_comment "${line}")
string(STRIP "${line}" _stripped_line)
if(_stripped_line STREQUAL "")
set(_is_empty TRUE)
else()
set(_is_empty FALSE)
endif()
if(line MATCHES "^[ \t]*//")
set(_is_comment TRUE)
else()
set(_is_comment FALSE)
endif()
if(NOT _is_empty AND NOT _is_comment)
set(current_tags "")
set(current_skip "")
+29
View File
@@ -0,0 +1,29 @@
# Short URL service
Void::ShortUrl::IShortener is a provider-neutral ABI-v1 service for creating
short URLs and, when supported, resolving their keys. It has no dependency on
Echoion or any specific HTTP provider.
Implementations derive from IShortener and can be registered directly in a
Void::Service::ServiceRegistry. Plugin implementations export the standard
void_plugin_service(void*) symbol and are bound with
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>.
The versioned contract lives in Void::ShortUrl::V1; aliases in Void::ShortUrl
select the current ABI. Implementations report a provider identifier and health
status. An empty custom key asks the provider to generate one, and an expiry of
zero means permanent.
Keep the returned shared pointer for the complete operation. That pin guarantees
the implementation and its shared object remain alive during plugin reload.
resolve() intentionally defaults to not_supported, which permits providers
backed by external APIs that cannot reverse a short link.
V1 is frozen: enum ordinals, data-member order, and virtual method order must
not change after release. Incompatible evolution is introduced as V2 with a
new service interface. Because the ABI carries C++ standard-library values,
host and provider must use the same C++ runtime and the exact toolchain
contract recorded by the application release.
A provider must either honor a non-empty custom key and non-zero expiry or
return unsupported/conflict; silently ignoring either request is invalid.
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
namespace Void::Archive
{
struct ExtractionOptions {
std::size_t maxEntries{10'000};
std::uint64_t maxFileBytes{512ULL * 1024 * 1024};
std::uint64_t maxTotalBytes{2ULL * 1024 * 1024 * 1024};
bool overwriteExisting{false};
};
struct ExtractionResult {
std::size_t entries{0};
std::uint64_t bytes{0};
};
/// Extract a tar/tar.zst archive without invoking an external process.
/// Only regular files and directories are accepted. Absolute/traversal
/// paths, links, special files, duplicates and configured size/count
/// overages fail the whole operation.
[[nodiscard]] Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path& archivePath,
const std::filesystem::path& destination,
const ExtractionOptions& options = {});
} // namespace Void::Archive
+156
View File
@@ -0,0 +1,156 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <algorithm>
#include <array>
#include <bit>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <format>
#include <span>
#include <string>
namespace Void::Binary
{
/// Bounds-checked, non-owning reader for binary formats.
class Reader
{
public:
explicit constexpr Reader(std::span<const std::byte> bytes) noexcept
: m_bytes(bytes)
{
}
[[nodiscard]] constexpr std::size_t position() const noexcept
{
return m_position;
}
[[nodiscard]] constexpr std::size_t size() const noexcept
{
return m_bytes.size();
}
[[nodiscard]] constexpr std::size_t remaining() const noexcept
{
return m_bytes.size() - m_position;
}
[[nodiscard]] constexpr bool empty() const noexcept
{
return remaining() == 0;
}
[[nodiscard]] Void::Result::Result<void> seek(std::size_t position)
{
if (position > m_bytes.size()) {
return Void::Result::fail(std::format(
"Binary::Reader::seek: offset {} exceeds size {}",
position, m_bytes.size()));
}
m_position = position;
return {};
}
[[nodiscard]] Void::Result::Result<void> skip(std::size_t count)
{
if (count > remaining()) {
return truncated("skip", count);
}
m_position += count;
return {};
}
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
readBytes(std::size_t count)
{
if (count > remaining()) {
return std::unexpected{truncatedError("readBytes", count)};
}
const auto result = m_bytes.subspan(m_position, count);
m_position += count;
return result;
}
[[nodiscard]] Void::Result::Result<std::span<const std::byte>>
peekBytes(std::size_t count) const
{
if (count > remaining()) {
return std::unexpected{truncatedError("peekBytes", count)};
}
return m_bytes.subspan(m_position, count);
}
template <std::integral T>
requires(!std::same_as<T, bool>)
[[nodiscard]] Void::Result::Result<T>
read(std::endian byteOrder = std::endian::native)
{
auto bytes = readBytes(sizeof(T));
if (!bytes) {
return std::unexpected{bytes.error()};
}
std::array<std::byte, sizeof(T)> storage{};
std::ranges::copy(*bytes, storage.begin());
T value = std::bit_cast<T>(storage);
if constexpr (std::endian::native != std::endian::little &&
std::endian::native != std::endian::big) {
return Void::Result::fail(
"Binary::Reader::read: mixed-endian targets are "
"unsupported");
} else if (byteOrder != std::endian::native) {
value = std::byteswap(value);
}
return value;
}
[[nodiscard]] Void::Result::Result<std::string>
readString(std::size_t count)
{
auto bytes = readBytes(count);
if (!bytes) {
return std::unexpected{bytes.error()};
}
return std::string{reinterpret_cast<const char*>(bytes->data()),
bytes->size()};
}
[[nodiscard]] Void::Result::Result<Reader>
subreader(std::size_t count)
{
auto bytes = readBytes(count);
if (!bytes) {
return std::unexpected{bytes.error()};
}
return Reader{*bytes};
}
private:
std::span<const std::byte> m_bytes;
std::size_t m_position{0};
[[nodiscard]] Void::Result::Error
truncatedError(std::string_view operation,
std::size_t requested) const
{
return Void::Result::Error{
std::format("Binary::Reader::{}: requested {} bytes at "
"offset {}, only {} "
"remain",
operation, requested, m_position, remaining())};
}
[[nodiscard]] Void::Result::Result<void>
truncated(std::string_view operation,
std::size_t requested) const
{
return std::unexpected{truncatedError(operation, requested)};
}
};
} // namespace Void::Binary
+78
View File
@@ -0,0 +1,78 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <filesystem>
#include <memory>
#include <span>
#include <string_view>
#include <vector>
namespace Void::Crypto
{
enum class HashAlgorithm { Sha1, Sha256, Sha512 };
using Digest = std::vector<std::byte>;
class Hasher
{
public:
[[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm);
~Hasher();
Hasher(Hasher&&) noexcept;
Hasher& operator=(Hasher&&) noexcept;
Hasher(const Hasher&) = delete;
Hasher& operator=(const Hasher&) = delete;
[[nodiscard]] Void::Result::Result<void>
update(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void>
update(std::string_view data);
/// Finalize this hash. Calling finalize or update again is an
/// error.
[[nodiscard]] Void::Result::Result<Digest> finalize();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit Hasher(std::unique_ptr<Impl> impl) noexcept;
};
[[nodiscard]] Void::Result::Result<Digest>
hash(HashAlgorithm algorithm, std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> hash(HashAlgorithm algorithm,
std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha1(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha1(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
sha256(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha256(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
sha512(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
sha1File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha256File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha512File(const std::filesystem::path& path);
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
/// Verify an Ed25519 detached signature over the exact message bytes.
/// Invalid key/signature sizes are errors; a well-formed but invalid
/// signature returns false.
[[nodiscard]] Void::Result::Result<bool>
verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> publicKey);
} // namespace Void::Crypto
+6 -3
View File
@@ -606,7 +606,8 @@ namespace Void::Json
// (\uD800-\uDBFF followed by \uDC00-\uDFFF)
// into one code point, so astral characters
// (emoji, …) become valid 4-byte UTF-8
// instead of two invalid encoded surrogates.
// instead of two invalid encoded
// surrogates.
if (cp >= 0xD800 && cp <= 0xDBFF) {
unsigned lo = 0;
if (pos + 1 < src.size() &&
@@ -617,7 +618,8 @@ namespace Void::Json
cp = 0x10000u +
((cp - 0xD800u) << 10) +
(lo - 0xDC00u);
for (std::size_t i = 0; i < 6; ++i) {
for (std::size_t i = 0; i < 6;
++i) {
advance();
}
}
@@ -965,7 +967,8 @@ namespace Void::Json
inline void escape_string(std::string& out, std::string_view s)
{
out += '"';
for (const unsigned char c : s) {
for (const char value : s) {
const auto c = static_cast<unsigned char>(value);
switch (c) {
case '"':
out += "\\\"";
+379
View File
@@ -0,0 +1,379 @@
#pragma once
#include <charconv>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <map>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
namespace Void::Json::Strict
{
inline constexpr std::size_t default_maximum_depth{64U};
struct ParseError {
std::size_t offset{};
std::string message;
};
struct Value {
using Array = std::vector<Value>;
using Object = std::map<std::string, Value, std::less<>>;
std::variant<std::nullptr_t, bool, std::int64_t, std::string, Array,
Object>
value;
};
namespace Detail
{
struct ParseFailure {
ParseError error;
};
class Parser final
{
public:
explicit Parser(const std::string_view input,
const std::size_t maximumDepth)
: input_{input}, maximumDepth_{maximumDepth}
{
}
[[nodiscard]] Value parse()
{
skipWhitespace();
Value result = parseValue(0U);
skipWhitespace();
if (position_ != input_.size()) {
fail("trailing data");
}
return result;
}
private:
[[noreturn]] void fail(const std::string_view message) const
{
throw ParseFailure{
.error =
{
.offset = position_,
.message = std::string{message},
},
};
}
void skipWhitespace()
{
while (position_ < input_.size() &&
(input_[position_] == ' ' ||
input_[position_] == '\t' ||
input_[position_] == '\r' ||
input_[position_] == '\n')) {
++position_;
}
}
[[nodiscard]] char take()
{
if (position_ >= input_.size()) {
fail("unexpected end of input");
}
return input_[position_++];
}
void expect(const char expected)
{
if (take() != expected) {
fail("unexpected character");
}
}
void expectLiteral(const std::string_view literal)
{
if (input_.substr(position_, literal.size()) != literal) {
fail("invalid literal");
}
position_ += literal.size();
}
[[nodiscard]] static int hexValue(const char value)
{
if (value >= '0' && value <= '9') {
return value - '0';
}
if (value >= 'a' && value <= 'f') {
return value - 'a' + 10;
}
if (value >= 'A' && value <= 'F') {
return value - 'A' + 10;
}
return -1;
}
[[nodiscard]] std::uint32_t unicodeEscape()
{
std::uint32_t value{};
for (int index{}; index < 4; ++index) {
const int digit = hexValue(take());
if (digit < 0) {
fail("invalid unicode escape");
}
value = value * 16U + static_cast<std::uint32_t>(digit);
}
return value;
}
static void appendUtf8(std::string& output,
const std::uint32_t codepoint)
{
if (codepoint <= 0x7FU) {
output.push_back(static_cast<char>(codepoint));
} else if (codepoint <= 0x7FFU) {
output.push_back(
static_cast<char>(0xC0U | (codepoint >> 6U)));
output.push_back(
static_cast<char>(0x80U | (codepoint & 0x3FU)));
} else if (codepoint <= 0xFFFFU) {
output.push_back(
static_cast<char>(0xE0U | (codepoint >> 12U)));
output.push_back(static_cast<char>(
0x80U | ((codepoint >> 6U) & 0x3FU)));
output.push_back(
static_cast<char>(0x80U | (codepoint & 0x3FU)));
} else {
output.push_back(
static_cast<char>(0xF0U | (codepoint >> 18U)));
output.push_back(static_cast<char>(
0x80U | ((codepoint >> 12U) & 0x3FU)));
output.push_back(static_cast<char>(
0x80U | ((codepoint >> 6U) & 0x3FU)));
output.push_back(
static_cast<char>(0x80U | (codepoint & 0x3FU)));
}
}
[[nodiscard]] std::string parseString()
{
expect('"');
std::string output;
while (true) {
const unsigned char value =
static_cast<unsigned char>(take());
if (value == '"') {
return output;
}
if (value < 0x20U) {
fail("control character in string");
}
if (value != '\\') {
output.push_back(static_cast<char>(value));
continue;
}
switch (take()) {
case '"':
output.push_back('"');
break;
case '\\':
output.push_back('\\');
break;
case '/':
output.push_back('/');
break;
case 'b':
output.push_back('\b');
break;
case 'f':
output.push_back('\f');
break;
case 'n':
output.push_back('\n');
break;
case 'r':
output.push_back('\r');
break;
case 't':
output.push_back('\t');
break;
case 'u':
{
std::uint32_t codepoint = unicodeEscape();
if (codepoint >= 0xD800U &&
codepoint <= 0xDBFFU) {
if (take() != '\\' || take() != 'u') {
fail("missing low surrogate");
}
const std::uint32_t low =
unicodeEscape();
if (low < 0xDC00U || low > 0xDFFFU) {
fail("invalid low surrogate");
}
codepoint =
0x10000U +
((codepoint - 0xD800U) << 10U) +
low - 0xDC00U;
} else if (codepoint >= 0xDC00U &&
codepoint <= 0xDFFFU) {
fail("unexpected low surrogate");
}
appendUtf8(output, codepoint);
break;
}
default:
fail("invalid string escape");
}
}
}
[[nodiscard]] Value parseNumber()
{
const std::size_t start = position_;
if (input_[position_] == '-') {
++position_;
}
if (position_ >= input_.size()) {
fail("incomplete number");
}
if (input_[position_] == '0') {
++position_;
} else {
if (input_[position_] < '1' ||
input_[position_] > '9') {
fail("invalid number");
}
while (position_ < input_.size() &&
input_[position_] >= '0' &&
input_[position_] <= '9') {
++position_;
}
}
if (position_ < input_.size() &&
(input_[position_] == '.' || input_[position_] == 'e' ||
input_[position_] == 'E')) {
fail("floating-point numbers are not supported");
}
std::int64_t value{};
const auto result =
std::from_chars(input_.data() + start,
input_.data() + position_, value);
if (result.ec != std::errc{} ||
result.ptr != input_.data() + position_) {
fail("integer is out of range");
}
return Value{value};
}
[[nodiscard]] Value parseArray(const std::size_t depth)
{
expect('[');
skipWhitespace();
Value::Array result;
if (position_ < input_.size() && input_[position_] == ']') {
++position_;
return Value{std::move(result)};
}
while (true) {
result.push_back(parseValue(depth + 1U));
skipWhitespace();
const char separator = take();
if (separator == ']') {
return Value{std::move(result)};
}
if (separator != ',') {
fail("array requires comma or closing bracket");
}
skipWhitespace();
}
}
[[nodiscard]] Value parseObject(const std::size_t depth)
{
expect('{');
skipWhitespace();
Value::Object result;
if (position_ < input_.size() && input_[position_] == '}') {
++position_;
return Value{std::move(result)};
}
while (true) {
if (position_ >= input_.size() ||
input_[position_] != '"') {
fail("object key must be a string");
}
std::string key = parseString();
skipWhitespace();
expect(':');
skipWhitespace();
auto [iterator, inserted] = result.emplace(
std::move(key), parseValue(depth + 1U));
static_cast<void>(iterator);
if (!inserted) {
fail("duplicate object key");
}
skipWhitespace();
const char separator = take();
if (separator == '}') {
return Value{std::move(result)};
}
if (separator != ',') {
fail("object requires comma or closing brace");
}
skipWhitespace();
}
}
[[nodiscard]] Value parseValue(const std::size_t depth)
{
if (depth > maximumDepth_ || position_ >= input_.size()) {
fail("nesting limit or unexpected end of input");
}
switch (input_[position_]) {
case '{':
return parseObject(depth);
case '[':
return parseArray(depth);
case '"':
return Value{parseString()};
case 't':
expectLiteral("true");
return Value{true};
case 'f':
expectLiteral("false");
return Value{false};
case 'n':
expectLiteral("null");
return Value{nullptr};
default:
if (input_[position_] == '-' ||
(input_[position_] >= '0' &&
input_[position_] <= '9')) {
return parseNumber();
}
fail("invalid value");
}
}
std::string_view input_;
std::size_t maximumDepth_;
std::size_t position_{};
};
} // namespace Detail
[[nodiscard]] inline std::expected<Value, ParseError>
parse(const std::string_view input,
const std::size_t maximumDepth = default_maximum_depth)
{
try {
return Detail::Parser{input, maximumDepth}.parse();
} catch (const Detail::ParseFailure& failure) {
return std::unexpected{failure.error};
}
}
} // namespace Void::Json::Strict
+21
View File
@@ -3,6 +3,8 @@
#include <Void/Log/Log.hpp>
#include <Void/Log/Logger.hpp>
#include <memory>
// Bridge between Void::Log (the thin emission layer used by all modules) and
// Void::Logging::Logger (the full sink implementation).
//
@@ -69,4 +71,23 @@ namespace Void::Log
};
}
/// Owning variant for process-global sinks. The logger remains alive until
/// this sink is replaced or the logging state is destroyed.
[[nodiscard]] inline Sink
make_sink(std::shared_ptr<Void::Logging::Logger> logger)
{
return [logger = std::move(logger)](
Level level, std::string_view module, std::string_view message,
const std::source_location& location) {
if (!logger) {
return;
}
auto full = std::string{"["};
full += module;
full += "] ";
full += message;
logger->log(to_logging_level(level), full, location);
};
}
} // namespace Void::Log
+233
View File
@@ -0,0 +1,233 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Net
{
using RouteParameters = std::map<std::string, std::string, std::less<>>;
struct ServerRequest {
Method method{Method::Get};
std::string path;
std::vector<Header> headers;
std::string body;
RouteParameters parameters;
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
struct ServerResponse {
std::uint16_t status{200};
std::vector<Header> headers;
std::string body;
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
using RouteResult = Void::Result::Result<ServerResponse>;
using RouteHandler = std::function<RouteResult(const ServerRequest&)>;
/// A transport-neutral method/path router. Patterns support exact segments,
/// `:name` parameters, and a final `*name` catch-all. Route registration
/// and dispatch are thread-safe; handlers run without the router lock held.
class Router
{
public:
Router() = default;
Router(const Router&) = delete;
Router& operator=(const Router&) = delete;
Router(Router&&) = delete;
Router& operator=(Router&&) = delete;
[[nodiscard]] Void::Result::Result<void>
add(Method method, std::string pattern, RouteHandler handler);
/// A successful empty optional means that no route matched.
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
dispatch(ServerRequest request) const;
[[nodiscard]] std::size_t size() const;
private:
struct Route {
Method method;
std::string pattern;
std::vector<std::string> segments;
RouteHandler handler;
};
mutable std::shared_mutex mutex_;
std::vector<Route> routes_;
};
struct StaticFile {
std::filesystem::path path;
std::string_view content_type;
std::uintmax_t size{};
};
[[nodiscard]] std::string_view
content_type_for(const std::filesystem::path& path);
/// Resolves URL paths beneath one canonical document root. Percent-decoded
/// traversal, backslashes, control characters, and symlink escapes are
/// rejected. Missing files are represented by a successful empty optional.
class StaticFileResolver
{
public:
[[nodiscard]] static Void::Result::Result<StaticFileResolver>
create(std::filesystem::path root,
std::string index_file = "index.html");
[[nodiscard]] Void::Result::Result<std::optional<StaticFile>>
resolve(std::string_view request_path) const;
[[nodiscard]] const std::filesystem::path& root() const noexcept
{
return root_;
}
private:
StaticFileResolver(std::filesystem::path root,
std::string index_file)
: root_(std::move(root)), index_file_(std::move(index_file))
{
}
std::filesystem::path root_;
std::string index_file_;
};
struct WebSocketConnectionId {
std::uint64_t value{};
auto operator<=>(const WebSocketConnectionId&) const = default;
};
struct WebSocketClose {
std::uint16_t code{1000};
std::string reason;
};
/// Implemented by the concrete WebSocket transport owned by an HTTP server.
class WebSocketConnection
{
public:
virtual ~WebSocketConnection() = default;
[[nodiscard]] virtual WebSocketConnectionId id() const noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<void>
send_text(std::string_view message) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
send_binary(std::span<const std::byte> message) = 0;
virtual void close(const WebSocketClose& close) noexcept = 0;
};
struct WebSocketEvents {
std::function<void(const std::shared_ptr<WebSocketConnection>&)>
opened;
std::function<void(const std::shared_ptr<WebSocketConnection>&,
std::string_view)>
text;
std::function<void(const std::shared_ptr<WebSocketConnection>&,
std::span<const std::byte>)>
binary;
std::function<void(WebSocketConnectionId, const WebSocketClose&)>
closed;
std::function<void(WebSocketConnectionId,
const Void::Result::Error&)>
error;
};
/// Thread-safe connection ownership and lifecycle dispatch. All callbacks
/// and transport close operations run without the registry lock held. Call
/// shutdown() for close callbacks; destruction performs a best-effort close
/// without invoking user code.
class WebSocketSessions
{
public:
WebSocketSessions() = default;
explicit WebSocketSessions(WebSocketEvents events)
: events_(std::move(events))
{
}
~WebSocketSessions() noexcept;
WebSocketSessions(const WebSocketSessions&) = delete;
WebSocketSessions& operator=(const WebSocketSessions&) = delete;
WebSocketSessions(WebSocketSessions&&) = delete;
WebSocketSessions& operator=(WebSocketSessions&&) = delete;
void set_events(WebSocketEvents events);
/// Register a transport connection and emit `opened`. Returns false
/// for a duplicate connection ID.
[[nodiscard]] Void::Result::Result<bool>
open(std::shared_ptr<WebSocketConnection> connection);
[[nodiscard]] std::shared_ptr<WebSocketConnection>
find(WebSocketConnectionId id) const;
[[nodiscard]] bool contains(WebSocketConnectionId id) const;
[[nodiscard]] std::size_t size() const;
[[nodiscard]] bool receive_text(WebSocketConnectionId id,
std::string_view message) const;
[[nodiscard]] bool
receive_binary(WebSocketConnectionId id,
std::span<const std::byte> message) const;
[[nodiscard]] bool fail(WebSocketConnectionId id,
const Void::Result::Error& error) const;
/// Record a transport-initiated close without closing it again.
[[nodiscard]] bool disconnect(WebSocketConnectionId id,
WebSocketClose close = {});
/// Remove and actively close one connection.
[[nodiscard]] bool close(WebSocketConnectionId id,
WebSocketClose close = {});
/// Remove and actively close every connection. Returns the count.
std::size_t shutdown(WebSocketClose close = {1001,
"server shutdown"});
private:
using Connections = std::map<WebSocketConnectionId,
std::shared_ptr<WebSocketConnection>>;
[[nodiscard]] bool remove(WebSocketConnectionId id,
const WebSocketClose& close,
bool close_transport);
[[nodiscard]] Connections take_all(bool stop_accepting = false);
mutable std::mutex mutex_;
Connections connections_;
WebSocketEvents events_;
bool accepting_{true};
};
} // namespace Void::Net
+80 -65
View File
@@ -9,82 +9,97 @@
namespace Void::Plugin
{
enum class LoadError {
FileNotFound,
DlopenFailed,
SymbolMissing,
AbiMismatch,
CreateFailed,
NotSupported, // platform does not support dlopen
StateRejected, // new instance refused the serialized state
ActivationFailed, // on_load threw or readiness validation failed
UnknownPlugin, // PluginManager: no plugin registered under that name
};
enum class LoadError {
FileNotFound,
DlopenFailed,
SymbolMissing,
AbiMismatch,
CreateFailed,
NotSupported, // platform does not support dlopen
StateRejected, // new instance refused the serialized state
ActivationFailed, // on_load threw or readiness validation failed
UnknownPlugin, // PluginManager: no plugin registered under that name
NameMismatch, // replacement reports a different registry name
};
[[nodiscard]] std::string_view to_string(LoadError e) noexcept;
[[nodiscard]] std::string_view to_string(LoadError e) noexcept;
// ── PluginLoader ──────────────────────────────────────────────────────────────
// Owns one plugin instance loaded from a shared library.
//
// Hot-reload protocol:
// 1. The new .so (at the same canonical path) is copied to a temp file so
// dlopen gets a fresh inode even if the path was already cached.
// 2. New instance is created and optional transfer_state() called (both
// old and new instances are alive simultaneously at this point).
// 3. Old instance is destroyed and old handle is closed.
//
// Thread safety: not thread-safe. Protect with external locking if needed.
// ── PluginLoader
// ────────────────────────────────────────────────────────────── Owns one
// plugin instance loaded from a shared library.
//
// Hot-reload protocol:
// 1. The new .so (at the same canonical path) is copied to a temp file so
// dlopen gets a fresh inode even if the path was already cached.
// 2. New instance is created and optional transfer_state() called (both
// old and new instances are alive simultaneously at this point).
// 3. Old instance is destroyed and old handle is closed.
//
// Thread safety: not thread-safe. Protect with external locking if needed.
class PluginLoader {
public:
[[nodiscard]] static std::expected<PluginLoader, LoadError>
load(std::filesystem::path path);
class PluginLoader
{
public:
~PluginLoader();
PluginLoader(PluginLoader&&) noexcept;
PluginLoader& operator=(PluginLoader&&) noexcept;
PluginLoader(const PluginLoader&) = delete;
PluginLoader& operator=(const PluginLoader&) = delete;
[[nodiscard]] static std::expected<PluginLoader, LoadError>
load(std::filesystem::path path);
[[nodiscard]] IPlugin* plugin() noexcept { return plugin_; }
[[nodiscard]] const IPlugin* plugin() const noexcept { return plugin_; }
[[nodiscard]] const PluginInfo& info() const noexcept { return info_; }
[[nodiscard]] bool loaded() const noexcept { return handle_ != nullptr; }
~PluginLoader();
PluginLoader(PluginLoader&&) noexcept;
PluginLoader& operator=(PluginLoader&&) noexcept;
PluginLoader(const PluginLoader&) = delete;
PluginLoader& operator=(const PluginLoader&) = delete;
IPlugin* operator->() noexcept { return plugin_; }
[[nodiscard]] IPlugin* plugin() noexcept { return plugin_; }
[[nodiscard]] const IPlugin* plugin() const noexcept
{
return plugin_;
}
[[nodiscard]] const PluginInfo& info() const noexcept
{
return info_;
}
[[nodiscard]] bool loaded() const noexcept
{
return handle_ != nullptr;
}
// Hot-reload: copies current .so to a temp file (fresh inode), loads
// it, transfers state, then destroys old instance and swaps handles.
// State transfer prefers the v2 serialize/deserialize protocol (old
// serializes, new deserializes with the old schema version); falls
// back to void_plugin_transfer_state; else no transfer.
[[nodiscard]] std::expected<void, LoadError> reload();
IPlugin* operator->() noexcept { return plugin_; }
private:
PluginLoader() = default;
// Hot-reload: copies current .so to a temp file (fresh inode),
// loads it, transfers state, then destroys old instance and swaps
// handles. State transfer prefers the v2 serialize/deserialize
// protocol (old serializes, new deserializes with the old schema
// version); falls back to void_plugin_transfer_state; else no
// transfer.
[[nodiscard]] std::expected<void, LoadError> reload();
// Moves plugin state old -> new during a reload (v2 serialize/
// deserialize, else transfer_state). Returns false only if the new
// instance rejects the state.
friend bool transfer_plugin_state(const PluginLoader& from,
PluginLoader& to);
private:
void* handle_ {};
IPlugin* plugin_ {};
destroy_fn destroy_ {};
transfer_fn transfer_ {};
ready_fn ready_ {};
state_version_fn state_version_{};
serialize_fn serialize_ {};
free_string_fn free_string_ {};
deserialize_fn deserialize_ {};
PluginInfo info_ {};
std::filesystem::path path_;
PluginLoader() = default;
[[nodiscard]] std::expected<void, LoadError>
load_from(const std::filesystem::path& path);
// Moves plugin state old -> new during a reload (v2 serialize/
// deserialize, else transfer_state). Returns false only if the new
// instance rejects the state.
friend bool transfer_plugin_state(const PluginLoader& from,
PluginLoader& to);
void destroy_current() noexcept;
};
void* handle_{};
IPlugin* plugin_{};
destroy_fn destroy_{};
transfer_fn transfer_{};
ready_fn ready_{};
state_version_fn state_version_{};
serialize_fn serialize_{};
free_string_fn free_string_{};
deserialize_fn deserialize_{};
PluginInfo info_{};
std::filesystem::path path_;
[[nodiscard]] std::expected<void, LoadError>
load_from(const std::filesystem::path& path);
void destroy_current() noexcept;
};
} // namespace Void::Plugin
+30 -2
View File
@@ -49,6 +49,11 @@ namespace Void::Plugin
[[nodiscard]] explicit operator bool() const noexcept;
[[nodiscard]] const PluginInfo& info() const noexcept;
/// Resolve an optional symbol from the exact shared object pinned
/// by this handle. The returned address remains valid while the
/// handle is alive, even if the manager concurrently reloads the
/// plugin.
[[nodiscard]] void* raw_symbol(const char* symbol) const noexcept;
private:
@@ -86,6 +91,17 @@ namespace Void::Plugin
// name argument is the registry name (IPlugin::name()).
std::function<std::string(std::string_view plugin_name)>
config_provider;
// Host-specific contract checked after plugin activation and before
// publication. A failed validation aborts load/reload
// transactionally.
std::function<bool(IPlugin&, const PluginInfo&)> instance_validator;
// Binary-level contract checked immediately after the shared object
// is opened and identified, before configuration, activation, state
// transfer, or publication. Hosts can inspect optional exported
// symbols through the pinned handle. A rejection is transactional:
// initial loads are discarded and reloads keep the current
// instance.
std::function<bool(const PluginHandle&)> candidate_validator;
};
// Identifies an on_reloaded observer for remove_on_reloaded.
@@ -137,6 +153,16 @@ namespace Void::Plugin
/// it alive until they drop.
std::expected<void, LoadError> reload(std::string_view name);
/// Replace `name` from an immutable new library path. The candidate
/// must report the same plugin name. It is configured, receives the
/// old state, activates and passes host validation before one
/// atomic publication. On any error the current instance, source
/// path and watcher remain unchanged. Pinned old handles remain
/// valid.
std::expected<void, LoadError>
replace(std::string_view name,
const std::filesystem::path& newPath);
/// Begin watching the plugin's file; reload automatically when
/// it changes (debounced). Reload failures are logged and the
/// old instance is kept.
@@ -188,11 +214,13 @@ namespace Void::Plugin
struct Entry {
std::filesystem::path path;
std::atomic<std::shared_ptr<detail::Instance>> current;
bool watched{false};
};
Entry* find(std::string_view name) const;
std::expected<void, LoadError> reload_locked(Entry& entry,
std::string_view name);
std::expected<void, LoadError>
reload_locked(Entry& entry, std::string_view name,
const std::filesystem::path& sourcePath);
std::vector<std::function<void(std::string_view)>>
reload_callbacks_locked() const;
+139
View File
@@ -0,0 +1,139 @@
#pragma once
#include <Void/Data/Json.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Plugin/Plugin.hpp>
#include <Void/Service/Registry.hpp>
#include <Void/Text/Semver.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace Void::Plugin
{
inline constexpr std::uint32_t MODULE_DESCRIPTOR_VERSION = 1;
enum class ActivationPolicy : std::uint8_t {
Reloadable,
RestartRequired,
InstallerRequired,
};
struct ModuleDependency {
std::string module_id;
std::string version_range;
std::string abi_hash;
bool optional{false};
[[nodiscard]] bool accepts(const Semver::Version& version) const
{
const auto range = Semver::VersionRange::parse(version_range);
return range.has_value() && range->contains(version);
}
};
struct ModuleReadiness {
bool ready{false};
std::string detail;
};
struct ModuleHost {
Service::ServiceRegistry& services;
};
class IModule : public IPlugin
{
public:
[[nodiscard]] virtual Result::Result<void>
activate(ModuleHost& host)
{
static_cast<void>(host);
on_load();
return {};
}
[[nodiscard]] virtual Result::Result<void>
quiesce(std::chrono::steady_clock::time_point deadline)
{
static_cast<void>(deadline);
return {};
}
[[nodiscard]] virtual Json::Value checkpoint() const
{
return Json::object();
}
[[nodiscard]] virtual Result::Result<void>
restore(const Json::Value& state)
{
static_cast<void>(state);
return {};
}
[[nodiscard]] virtual ModuleReadiness readiness() const
{
return {.ready = true, .detail = {}};
}
[[nodiscard]] virtual Result::Result<void> deactivate()
{
on_unload();
return {};
}
};
using module_factory_fn = std::unique_ptr<IModule> (*)();
struct ModuleDescriptor {
std::size_t struct_size{sizeof(ModuleDescriptor)};
std::uint32_t descriptor_version{MODULE_DESCRIPTOR_VERSION};
std::string module_id;
Semver::Version component_version;
std::string abi_hash;
Json::Value abi_contract{Json::object()};
std::vector<ModuleDependency> dependencies;
ActivationPolicy activation_policy{
ActivationPolicy::RestartRequired};
module_factory_fn create{};
[[nodiscard]] Result::Result<void> validate() const
{
if (struct_size < sizeof(ModuleDescriptor)) {
return Result::fail("module descriptor is truncated");
}
if (descriptor_version != MODULE_DESCRIPTOR_VERSION) {
return Result::fail(
"unsupported module descriptor version");
}
if (module_id.empty()) {
return Result::fail("module id is required");
}
if (abi_hash.empty() || !abi_contract.is_object()) {
return Result::fail(
"module ABI hash and object contract are required");
}
if (create == nullptr) {
return Result::fail("module factory is required");
}
for (const auto& dependency : dependencies) {
if (dependency.module_id.empty() ||
!Semver::VersionRange::parse(
dependency.version_range)) {
return Result::fail(
"module dependency id or version range is invalid");
}
}
return {};
}
};
using module_query_fn = const ModuleDescriptor* (*)();
} // namespace Void::Plugin
+60 -17
View File
@@ -7,6 +7,7 @@
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <unordered_map>
#include <utility>
@@ -25,29 +26,57 @@ namespace Void::Resilience
public:
using Clock = TokenBucket::Clock;
using TimePoint = TokenBucket::TimePoint;
// `capacity` is the burst size; `refill_per_sec` the sustained rate.
// The clock is shared with every bucket so tests stay deterministic.
// `capacity` is the burst size; `refill_per_sec` the sustained
// rate. `max_keys == 0` keeps the historic unbounded behaviour.
// Otherwise new keys are rejected at capacity until cleanup/reset
// frees space. The clock is shared with every bucket so tests stay
// deterministic.
explicit KeyedRateLimiter(double capacity, double refill_per_sec,
Clock clock = default_clock())
Clock clock = default_clock(),
std::size_t max_keys = 0)
: capacity_{capacity}, rate_{refill_per_sec},
clock_{std::move(clock)}
clock_{std::move(clock)}, max_keys_{max_keys}
{
if (max_keys_ > 0) {
map_.reserve(max_keys_);
}
}
// Consume `tokens` for `key`. Returns false (without consuming) when
// the key's bucket is exhausted.
// 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)
{
return allow_at(key, clock_(), tokens);
}
[[nodiscard]] bool allow_at(const Key& key, TimePoint now,
double tokens = 1.0)
{
std::lock_guard lock{mu_};
return entry(key).bucket->try_acquire(tokens);
Entry* value = entry(key, now);
return value != nullptr &&
value->bucket->try_acquire_at(now, tokens);
}
// Tokens currently available to `key` (creates the bucket if new).
[[nodiscard]] double remaining(const Key& key)
{
return remaining_at(key, clock_()).value_or(0.0);
}
// A missing optional means the key could not be created because the
// configured key cap is full.
[[nodiscard]] std::optional<double> remaining_at(const Key& key,
TimePoint now)
{
std::lock_guard lock{mu_};
return entry(key).bucket->available();
Entry* value = entry(key, now);
if (value == nullptr) {
return std::nullopt;
}
return value->bucket->available_at(now);
}
// Forget a key's bucket (its next use starts full).
@@ -57,15 +86,27 @@ namespace Void::Resilience
map_.erase(key);
}
void reset()
{
std::lock_guard lock{mu_};
map_.clear();
}
// 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();
return cleanup_at(clock_(), max_age);
}
std::size_t cleanup_at(TimePoint now,
std::chrono::steady_clock::duration max_age)
{
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) {
if (now >= it->second.last_seen &&
now - it->second.last_seen >= max_age) {
it = map_.erase(it);
++removed;
} else {
@@ -90,19 +131,20 @@ namespace Void::Resilience
}
struct Entry {
// TokenBucket owns a std::mutex (non-movable), so hold it by
// pointer to keep Entry movable for the hash map.
// 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)
Entry* entry(const Key& key, TimePoint now)
{
const auto now = std::chrono::steady_clock::now();
auto it = map_.find(key);
if (it == map_.end()) {
it = map_
.emplace(key,
if (max_keys_ > 0 && map_.size() >= max_keys_) {
return nullptr;
}
it = map_.emplace(key,
Entry{std::make_unique<TokenBucket>(
capacity_, rate_, clock_),
now})
@@ -110,12 +152,13 @@ namespace Void::Resilience
} else {
it->second.last_seen = now;
}
return it->second;
return &it->second;
}
double capacity_;
double rate_;
Clock clock_;
std::size_t max_keys_;
mutable std::mutex mu_;
std::unordered_map<Key, Entry, Hash> map_;
};
+42 -16
View File
@@ -37,7 +37,45 @@ namespace Void::Resilience
[[nodiscard]] bool try_acquire(double tokens = 1.0)
{
std::lock_guard lock{mu_};
refill();
refill(clock_());
return try_acquire_locked(tokens);
}
// Explicit-time variant for callers that need a single
// deterministic clock value across several coordinated buckets.
[[nodiscard]] bool try_acquire_at(TimePoint now,
double tokens = 1.0)
{
std::lock_guard lock{mu_};
refill(now);
return try_acquire_locked(tokens);
}
// Current token count after refilling for elapsed time.
[[nodiscard]] double available() { return available_at(clock_()); }
[[nodiscard]] double available_at(TimePoint now)
{
std::lock_guard lock{mu_};
refill(now);
return tokens_;
}
void reset() { reset_at(clock_()); }
void reset_at(TimePoint now)
{
std::lock_guard lock{mu_};
tokens_ = capacity_;
last_ = now;
}
[[nodiscard]] double capacity() const noexcept { return capacity_; }
private:
[[nodiscard]] bool try_acquire_locked(double tokens)
{
if (tokens_ >= tokens) {
tokens_ -= tokens;
return true;
@@ -45,27 +83,15 @@ namespace Void::Resilience
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()
void refill(TimePoint now)
{
const auto now = clock_();
const std::chrono::duration<double> elapsed = now - last_;
const std::chrono::duration<double> elapsed =
now > last_ ? now - last_ : TimePoint::duration::zero();
last_ = now;
tokens_ =
std::min(capacity_, tokens_ + elapsed.count() * rate_);
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <array>
#include <cstddef>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Security
{
/// Cost presets supplied by libsodium for Argon2id password hashing.
/// Moderate is the default for stored account passwords; Interactive is
/// useful where latency and memory are constrained, including tests.
enum class PasswordHashStrength { Interactive, Moderate, Sensitive };
inline constexpr std::size_t default_token_entropy_bytes = 32;
inline constexpr std::size_t secret_key_bytes = 32;
inline constexpr std::size_t secret_nonce_bytes = 24;
inline constexpr std::size_t secret_authentication_bytes = 16;
using SecretKey = std::array<unsigned char, secret_key_bytes>;
/// Generate a URL-safe, unpadded token containing `entropy_bytes` of
/// cryptographically secure randomness.
[[nodiscard]] Void::Result::Result<std::string>
random_token(std::size_t entropy_bytes = default_token_entropy_bytes);
/// Produce a deterministic lowercase hexadecimal BLAKE2b-256 digest.
/// Store this digest instead of the bearer token itself.
[[nodiscard]] Void::Result::Result<std::string>
hash_token(std::string_view token);
/// Verify a token digest without data-dependent comparison timing.
/// Malformed digests are treated as a non-match.
[[nodiscard]] Void::Result::Result<bool>
verify_token(std::string_view token, std::string_view encoded_hash);
/// Hash a password using libsodium's Argon2id encoded-string format.
/// The returned string contains the algorithm, parameters, salt, and hash.
[[nodiscard]] Void::Result::Result<std::string> hash_password(
std::string_view password,
PasswordHashStrength strength = PasswordHashStrength::Moderate);
/// Verify a password against a libsodium Argon2id encoded hash.
/// Malformed hashes are treated as a non-match.
[[nodiscard]] Void::Result::Result<bool>
verify_password(std::string_view password,
std::string_view encoded_hash);
/// Generate a cryptographically random key for local secret encryption.
[[nodiscard]] Void::Result::Result<SecretKey> random_secret_key();
/// Encrypt and authenticate bytes. The returned portable envelope is
/// nonce || ciphertext || authentication tag.
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
seal_secret(std::span<const unsigned char> plaintext,
const SecretKey& key);
/// Authenticate and decrypt an envelope produced by seal_secret.
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
open_secret(std::span<const unsigned char> envelope,
const SecretKey& key);
} // namespace Void::Security
+172 -48
View File
@@ -5,7 +5,10 @@
#include <Void/Service/Registry.hpp>
#include <Void/Service/Service.hpp>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <string_view>
#include <type_traits>
@@ -17,8 +20,8 @@ namespace Void::Service
/// extern "C" Void::Service::IService* void_plugin_service(void* inst);
/// It returns the IService subobject of the plugin's service object
/// (which must derive the host interface I, and I must derive
/// IService). The host recovers I* by static_cast — no dynamic_cast, so
/// it is robust across RTLD_LOCAL plugin boundaries.
/// IService). The host verifies the exported subobject with dynamic_cast;
/// host and provider must therefore share RTTI identity for I.
using service_factory_fn = IService* (*)(void* instance);
inline constexpr const char* kServiceSymbol = "void_plugin_service";
@@ -32,23 +35,28 @@ namespace Void::Service
/// callers never see a freed object.
///
/// Requires: I derives Void::Service::IService; the plugin's service
/// type derives I; the plugin exports void_plugin_service.
/// type derives I; the plugin exports void_plugin_service. RTTI identity
/// for I must be shared by host and provider, just like PluginManager's
/// host-specific instance_validator interfaces.
template <typename I> class PluginServiceBinding
{
public:
static_assert(std::is_base_of_v<IService, I>,
"plugin service interface must derive IService");
using Validator =
std::function<bool(const std::shared_ptr<I>& service)>;
PluginServiceBinding(Plugin::PluginManager& manager,
ServiceRegistry& registry, std::string name)
: m_manager(&manager), m_registry(&registry),
m_name(std::move(name))
ServiceRegistry& registry, std::string name,
Validator validator = {})
: m_state(std::make_shared<State>(
manager, registry, std::move(name), std::move(validator)))
{
}
// The reload callback captures `this`; the binding must
// deregister it before dying and therefore cannot move.
// Lifecycle registration cannot be transferred while callbacks may
// be in flight.
PluginServiceBinding(const PluginServiceBinding&) = delete;
PluginServiceBinding&
operator=(const PluginServiceBinding&) = delete;
@@ -56,65 +64,181 @@ namespace Void::Service
~PluginServiceBinding() { disable_hot_reload(); }
/// Resolve the current instance's service and (re)register it.
[[nodiscard]] bool bind()
{
auto handle = m_manager->acquire(m_name);
if (!handle) {
return false;
}
auto* fn = reinterpret_cast<service_factory_fn>(
m_manager->raw_symbol(m_name, kServiceSymbol));
if (fn == nullptr) {
return false;
}
IService* base = fn(handle.get());
if (base == nullptr) {
return false;
}
I* iface = static_cast<I*>(base); // I : IService
// Keep the plugin instance (and its mapped .so) alive for
// as long as the registry holds this service.
auto owner = std::make_shared<Plugin::PluginHandle>(handle);
std::shared_ptr<I> pinned(std::move(owner), iface);
m_registry->provide<I>(std::move(pinned));
Void::Log::debug("Service.Plugin",
"bound service from plugin '{}'", m_name);
return true;
}
[[nodiscard]] bool bind() noexcept { return m_state->bind(); }
/// Auto-rebind on hot reload (debounced file watching). The
/// manager keeps old instances alive while pinned, so the swap
/// is seamless. Idempotent.
void enable_hot_reload()
{
std::lock_guard lifecycleLock{m_lifecycleMutex};
if (m_reload_id != 0) {
return;
}
m_reload_id =
m_manager->on_reloaded([this](std::string_view name) {
if (name == m_name) {
(void)bind();
}
});
m_manager->watch(m_name);
m_state->set_hot_reload_enabled(true);
try {
std::weak_ptr<State> weakState{m_state};
m_reload_id = m_state->manager().on_reloaded(
[weakState](std::string_view name) noexcept {
if (auto state = weakState.lock()) {
state->rebind(name);
}
});
m_state->manager().watch(m_state->name());
} catch (...) {
m_state->set_hot_reload_enabled(false);
if (m_reload_id != 0) {
m_state->manager().remove_on_reloaded(m_reload_id);
m_reload_id = 0;
}
throw;
}
}
/// Stop observing reloads (the file watch itself is shared and
/// stays). Idempotent; called by the destructor.
void disable_hot_reload()
void disable_hot_reload() noexcept
{
if (m_reload_id != 0) {
m_manager->remove_on_reloaded(m_reload_id);
m_reload_id = 0;
try {
std::lock_guard lifecycleLock{m_lifecycleMutex};
m_state->set_hot_reload_enabled(false);
if (m_reload_id != 0) {
m_state->manager().remove_on_reloaded(m_reload_id);
m_reload_id = 0;
}
} catch (...) {
// Destruction must remain noexcept. The weak callback
// cannot keep State alive after m_state is released even if
// observer removal itself reports a failure.
}
}
private:
Plugin::PluginManager* m_manager;
ServiceRegistry* m_registry;
std::string m_name;
class State
{
public:
State(Plugin::PluginManager& manager,
ServiceRegistry& registry, std::string name,
Validator validator)
: m_manager(&manager), m_registry(&registry),
m_name(std::move(name)),
m_validator(std::move(validator))
{
}
[[nodiscard]] bool bind() noexcept
{
try {
std::lock_guard lock{m_mutex};
return bind_locked();
} catch (...) {
return false;
}
}
void rebind(std::string_view name) noexcept
{
if (name != m_name) {
return;
}
try {
std::lock_guard lock{m_mutex};
if (m_hotReloadEnabled) {
(void)bind_locked();
}
} catch (...) {
}
}
void set_hot_reload_enabled(bool enabled)
{
std::lock_guard lock{m_mutex};
m_hotReloadEnabled = enabled;
}
[[nodiscard]] Plugin::PluginManager&
manager() const noexcept
{
return *m_manager;
}
[[nodiscard]] const std::string& name() const noexcept
{
return m_name;
}
private:
[[nodiscard]] bool bind_locked() noexcept
{
try {
auto handle = m_manager->acquire(m_name);
if (!handle) {
return false;
}
auto* factory =
reinterpret_cast<service_factory_fn>(
handle.raw_symbol(kServiceSymbol));
if (factory == nullptr) {
return false;
}
IService* base = factory(handle.get());
if (base == nullptr) {
return false;
}
I* iface = dynamic_cast<I*>(base);
if (iface == nullptr) {
Void::Log::warn(
"Service.Plugin",
"plugin '{}' exported an incompatible "
"service interface",
m_name);
return false;
}
// Pin the exact instance and shared object that
// supplied the factory and service subobject.
auto owner = std::make_shared<Plugin::PluginHandle>(
std::move(handle));
std::shared_ptr<I> pinned(std::move(owner), iface);
if (m_validator && !m_validator(pinned)) {
Void::Log::warn(
"Service.Plugin",
"plugin '{}' service validation failed",
m_name);
return false;
}
m_registry->provide<I>(std::move(pinned));
Void::Log::debug("Service.Plugin",
"bound service from plugin '{}'",
m_name);
return true;
} catch (const std::exception& error) {
Void::Log::warn(
"Service.Plugin",
"binding service from plugin '{}' threw: {}",
m_name, error.what());
} catch (...) {
Void::Log::warn(
"Service.Plugin",
"binding service from plugin '{}' threw",
m_name);
}
return false;
}
Plugin::PluginManager* m_manager;
ServiceRegistry* m_registry;
std::string m_name;
Validator m_validator;
std::mutex m_mutex;
bool m_hotReloadEnabled{false};
};
std::shared_ptr<State> m_state;
std::mutex m_lifecycleMutex;
Plugin::ReloadCallbackId m_reload_id{0};
};
+165
View File
@@ -0,0 +1,165 @@
#pragma once
#include <Void/Service/Service.hpp>
#include <cstdint>
#include <string>
#include <string_view>
#include <utility>
namespace Void::ShortUrl::V1
{
inline constexpr std::string_view kServiceId{"void.short-url"};
inline constexpr std::uint32_t kServiceVersion{1};
enum class ErrorCode : std::uint32_t {
none = 0,
invalid_request,
unsupported,
not_found,
expired,
conflict,
unauthorized,
rate_limited,
timeout,
unavailable,
provider_error,
internal_error,
invalid_url,
revoked,
storage,
response_too_large,
};
struct Error {
ErrorCode code{ErrorCode::none};
std::string message;
std::uint32_t retry_after_seconds{0};
[[nodiscard]] bool ok() const noexcept
{
return code == ErrorCode::none;
}
[[nodiscard]] explicit operator bool() const noexcept
{
return !ok();
}
};
struct ShortenRequest {
std::string target_url;
std::string custom_key;
std::int64_t expires_at_unix_seconds{0};
};
struct ShortenResult {
std::string short_url;
std::string key;
std::int64_t expires_at_unix_seconds{0};
Error error;
[[nodiscard]] bool ok() const noexcept
{
return error.ok() && !short_url.empty();
}
[[nodiscard]] explicit operator bool() const noexcept
{
return ok();
}
};
enum class HealthStatus : std::uint32_t {
unknown = 0,
healthy,
degraded,
unhealthy,
};
struct Health {
HealthStatus status{HealthStatus::unknown};
std::string message;
};
struct ResolveRequest {
std::string key;
};
struct ResolveResult {
std::string target_url;
std::int64_t expires_at_unix_seconds{0};
Error error;
[[nodiscard]] bool ok() const noexcept
{
return error.ok() && !target_url.empty();
}
[[nodiscard]] explicit operator bool() const noexcept
{
return ok();
}
};
class IShortener : public Service::IService
{
public:
~IShortener() override = default;
[[nodiscard]] std::string_view service_name() const final
{
return kServiceId;
}
[[nodiscard]] virtual std::uint32_t service_version() const noexcept
{
return kServiceVersion;
}
[[nodiscard]] virtual std::string_view
provider_id() const noexcept = 0;
[[nodiscard]] virtual Health health() const = 0;
[[nodiscard]] virtual ShortenResult
shorten(const ShortenRequest& request) = 0;
[[nodiscard]] virtual bool supports_resolve() const noexcept
{
return false;
}
[[nodiscard]] virtual ResolveResult resolve(const ResolveRequest&)
{
return {
.target_url = {},
.expires_at_unix_seconds = 0,
.error =
{
.code = ErrorCode::unsupported,
.message =
"this shortener does not support resolution",
},
};
}
};
} // namespace Void::ShortUrl::V1
namespace Void::ShortUrl
{
using V1::Error;
using V1::ErrorCode;
using V1::Health;
using V1::HealthStatus;
using V1::IShortener;
using V1::ResolveRequest;
using V1::ResolveResult;
using V1::ShortenRequest;
using V1::ShortenResult;
inline constexpr auto kServiceId = V1::kServiceId;
inline constexpr auto kServiceVersion = V1::kServiceVersion;
} // namespace Void::ShortUrl
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <memory>
#include <optional>
#include <vector>
namespace Void::Process
{
/// Converts process signals into synchronous, deterministic waits.
/// Construct this before worker threads so the selected signals inherit a
/// blocked mask. A watcher must be destroyed on the thread that created it.
class SignalWatcher
{
public:
/// An empty signal list watches SIGINT and SIGTERM.
[[nodiscard]] static Void::Result::Result<SignalWatcher>
create(std::vector<int> signals = {});
~SignalWatcher();
SignalWatcher(SignalWatcher&&) noexcept;
SignalWatcher& operator=(SignalWatcher&&) noexcept;
SignalWatcher(const SignalWatcher&) = delete;
SignalWatcher& operator=(const SignalWatcher&) = delete;
/// Wait for a configured signal. A zero timeout performs a poll;
/// milliseconds::max() waits indefinitely.
[[nodiscard]] Void::Result::Result<std::optional<int>>
wait(std::chrono::milliseconds timeout =
std::chrono::milliseconds::max());
[[nodiscard]] Void::Result::Result<std::optional<int>> poll();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit SignalWatcher(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Process
+201 -106
View File
@@ -6,121 +6,216 @@
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Encoding::Base64
{
namespace Detail
{
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
namespace Detail
{
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
constexpr std::string_view alphabet_url =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
constexpr std::string_view alphabet_url =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
[[nodiscard]] constexpr std::array<std::int8_t, 256>
make_decode_table(std::string_view alpha) noexcept
{
std::array<std::int8_t, 256> t{};
t.fill(-1);
for (std::size_t i = 0; i < 64; ++i) {
t[static_cast<unsigned char>(alpha[i])] = static_cast<std::int8_t>(i);
}
t[static_cast<unsigned char>('=')] = -2; // padding sentinel
return t;
}
} // namespace Detail
[[nodiscard]] constexpr std::array<std::int8_t, 256>
make_decode_table(std::string_view alpha) noexcept
{
std::array<std::int8_t, 256> t{};
t.fill(-1);
for (std::size_t i = 0; i < 64; ++i) {
t[static_cast<unsigned char>(alpha[i])] =
static_cast<std::int8_t>(i);
}
t[static_cast<unsigned char>('=')] = -2; // padding sentinel
return t;
}
} // namespace Detail
/// Encode bytes to standard Base64 (with padding).
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
{
const auto& alpha = Detail::alphabet;
std::string out;
out.reserve(((data.size() + 2) / 3) * 4);
std::size_t i = 0;
for (; i + 2 < data.size(); i += 3) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
const auto c = static_cast<std::uint8_t>(data[i + 2]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[((b & 15) << 2) | (c >> 6)];
out += alpha[c & 63];
}
if (data.size() - i == 2) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[(b & 15) << 2];
out += '=';
} else if (data.size() - i == 1) {
const auto a = static_cast<std::uint8_t>(data[i]);
out += alpha[a >> 2];
out += alpha[(a & 3) << 4];
out += '=';
out += '=';
}
return out;
}
/// Encode bytes to standard Base64 (with padding).
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
{
const auto& alpha = Detail::alphabet;
std::string out;
out.reserve(((data.size() + 2) / 3) * 4);
std::size_t i = 0;
for (; i + 2 < data.size(); i += 3) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
const auto c = static_cast<std::uint8_t>(data[i + 2]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[((b & 15) << 2) | (c >> 6)];
out += alpha[c & 63];
}
if (data.size() - i == 2) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[(b & 15) << 2];
out += '=';
} else if (data.size() - i == 1) {
const auto a = static_cast<std::uint8_t>(data[i]);
out += alpha[a >> 2];
out += alpha[(a & 3) << 4];
out += '=';
out += '=';
}
return out;
}
/// Encode a string_view to standard Base64.
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Encode an unsigned-byte view without forcing callers to reinterpret
/// their binary buffers as text.
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
{
return encode(std::as_bytes(data));
}
/// Encode to URL-safe Base64 (no padding).
[[nodiscard]] inline std::string encode_url(std::string_view s)
{
const auto& alpha = Detail::alphabet_url;
auto data = std::as_bytes(std::span{s.data(), s.size()});
std::string out;
out.reserve(((data.size() + 2) / 3) * 4);
std::size_t i = 0;
for (; i + 2 < data.size(); i += 3) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
const auto c = static_cast<std::uint8_t>(data[i + 2]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[((b & 15) << 2) | (c >> 6)];
out += alpha[c & 63];
}
if (data.size() - i == 2) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[(b & 15) << 2];
} else if (data.size() - i == 1) {
const auto a = static_cast<std::uint8_t>(data[i]);
out += alpha[a >> 2];
out += alpha[(a & 3) << 4];
}
return out;
}
/// Encode a string_view to standard Base64.
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode standard Base64 (with or without padding). Returns nullopt on error.
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
{
static constexpr auto table = Detail::make_decode_table(Detail::alphabet);
std::string out;
out.reserve((s.size() / 4) * 3);
int buf = 0, bits = 0;
for (unsigned char c : s) {
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') continue;
const std::int8_t v = table[c];
if (v == -2) break; // padding
if (v == -1) return std::nullopt;
buf = (buf << 6) | v;
bits += 6;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((buf >> bits) & 0xFF);
}
}
return out;
}
/// Encode to URL-safe Base64 (no padding).
[[nodiscard]] inline std::string encode_url(std::string_view s)
{
const auto& alpha = Detail::alphabet_url;
auto data = std::as_bytes(std::span{s.data(), s.size()});
std::string out;
out.reserve(((data.size() + 2) / 3) * 4);
std::size_t i = 0;
for (; i + 2 < data.size(); i += 3) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
const auto c = static_cast<std::uint8_t>(data[i + 2]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[((b & 15) << 2) | (c >> 6)];
out += alpha[c & 63];
}
if (data.size() - i == 2) {
const auto a = static_cast<std::uint8_t>(data[i]);
const auto b = static_cast<std::uint8_t>(data[i + 1]);
out += alpha[a >> 2];
out += alpha[((a & 3) << 4) | (b >> 4)];
out += alpha[(b & 15) << 2];
} else if (data.size() - i == 1) {
const auto a = static_cast<std::uint8_t>(data[i]);
out += alpha[a >> 2];
out += alpha[(a & 3) << 4];
}
return out;
}
/// Decode canonical URL-safe Base64 without padding. Returns nullopt for
/// padding, invalid characters, impossible lengths, or non-zero trailing
/// bits.
[[nodiscard]] inline std::optional<std::string>
decode_url(std::string_view s)
{
static constexpr auto table =
Detail::make_decode_table(Detail::alphabet_url);
if (s.size() % 4 == 1 || s.find('=') != std::string_view::npos) {
return std::nullopt;
}
std::string out;
out.reserve((s.size() * 3) / 4);
std::uint32_t buffer = 0;
int bits = 0;
for (const char encoded : s) {
const auto character = static_cast<unsigned char>(encoded);
const std::int8_t value = table[character];
if (value < 0) {
return std::nullopt;
}
buffer = (buffer << 6) | static_cast<std::uint32_t>(value);
bits += 6;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((buffer >> bits) & 0xFFU);
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
}
if (bits != 0 && buffer != 0) {
return std::nullopt;
}
return out;
}
/// Decode standard Base64 (with or without padding). Returns nullopt on
/// error.
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
{
static constexpr auto table =
Detail::make_decode_table(Detail::alphabet);
std::string out;
out.reserve((s.size() / 4) * 3);
std::uint32_t buffer = 0;
int bits = 0;
std::size_t symbols = 0;
std::size_t padding = 0;
bool saw_padding = false;
for (const char encoded : s) {
const auto character = static_cast<unsigned char>(encoded);
if (character == ' ' || character == '\n' || character == '\r' ||
character == '\t') {
continue;
}
if (character == '=') {
saw_padding = true;
if (++padding > 2) {
return std::nullopt;
}
continue;
}
if (saw_padding) {
return std::nullopt;
}
const std::int8_t value = table[character];
if (value < 0) {
return std::nullopt;
}
buffer = (buffer << 6) | static_cast<std::uint32_t>(value);
++symbols;
bits += 6;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((buffer >> bits) & 0xFFU);
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
}
const std::size_t remainder = symbols % 4;
if (remainder == 1) {
return std::nullopt;
}
const std::size_t expected_padding = remainder == 0 ? 0 : 4 - remainder;
if (padding != 0 && padding != expected_padding) {
return std::nullopt;
}
if (bits != 0 && buffer != 0) {
return std::nullopt;
}
return out;
}
/// Decode standard Base64 into an explicitly binary buffer. This is the
/// preferred overload for protocol, cryptographic, and file-format data.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_bytes(std::string_view s)
{
const auto decoded = decode(s);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
} // namespace Void::Encoding::Base64
+86 -54
View File
@@ -5,67 +5,99 @@
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Encoding::Hex
{
/// Encode bytes to lowercase hex string.
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
{
constexpr std::string_view digits = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (auto b : data) {
const auto v = static_cast<std::uint8_t>(b);
out += digits[v >> 4];
out += digits[v & 0xF];
}
return out;
}
/// Encode bytes to lowercase hex string.
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
{
constexpr std::string_view digits = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (auto b : data) {
const auto v = static_cast<std::uint8_t>(b);
out += digits[v >> 4];
out += digits[v & 0xF];
}
return out;
}
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Encode an unsigned-byte view without treating binary data as text.
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
{
return encode(std::as_bytes(data));
}
/// Decode hex string to bytes. Returns nullopt on invalid input.
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
{
if (s.size() % 2 != 0) return std::nullopt;
auto hex_val = [](char c) -> std::optional<std::uint8_t> {
if (c >= '0' && c <= '9') return static_cast<std::uint8_t>(c - '0');
if (c >= 'a' && c <= 'f') return static_cast<std::uint8_t>(c - 'a' + 10);
if (c >= 'A' && c <= 'F') return static_cast<std::uint8_t>(c - 'A' + 10);
return std::nullopt;
};
std::string out;
out.reserve(s.size() / 2);
for (std::size_t i = 0; i < s.size(); i += 2) {
auto hi = hex_val(s[i]);
auto lo = hex_val(s[i + 1]);
if (!hi || !lo) return std::nullopt;
out += static_cast<char>((*hi << 4) | *lo);
}
return out;
}
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Uppercase hex encoding.
[[nodiscard]] inline std::string encode_upper(std::span<const std::byte> data)
{
constexpr std::string_view digits = "0123456789ABCDEF";
std::string out;
out.reserve(data.size() * 2);
for (auto b : data) {
const auto v = static_cast<std::uint8_t>(b);
out += digits[v >> 4];
out += digits[v & 0xF];
}
return out;
}
/// Decode hex string to bytes. Returns nullopt on invalid input.
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
{
if (s.size() % 2 != 0) {
return std::nullopt;
}
auto hex_val = [](char c) -> std::optional<std::uint8_t> {
if (c >= '0' && c <= '9') {
return static_cast<std::uint8_t>(c - '0');
}
if (c >= 'a' && c <= 'f') {
return static_cast<std::uint8_t>(c - 'a' + 10);
}
if (c >= 'A' && c <= 'F') {
return static_cast<std::uint8_t>(c - 'A' + 10);
}
return std::nullopt;
};
std::string out;
out.reserve(s.size() / 2);
for (std::size_t i = 0; i < s.size(); i += 2) {
auto hi = hex_val(s[i]);
auto lo = hex_val(s[i + 1]);
if (!hi || !lo) {
return std::nullopt;
}
out += static_cast<char>((*hi << 4) | *lo);
}
return out;
}
[[nodiscard]] inline std::string encode_upper(std::string_view s)
{
return encode_upper(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode hexadecimal text into an explicitly binary buffer.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_bytes(std::string_view s)
{
const auto decoded = decode(s);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
/// Uppercase hex encoding.
[[nodiscard]] inline std::string
encode_upper(std::span<const std::byte> data)
{
constexpr std::string_view digits = "0123456789ABCDEF";
std::string out;
out.reserve(data.size() * 2);
for (auto b : data) {
const auto v = static_cast<std::uint8_t>(b);
out += digits[v >> 4];
out += digits[v & 0xF];
}
return out;
}
[[nodiscard]] inline std::string encode_upper(std::string_view s)
{
return encode_upper(std::as_bytes(std::span{s.data(), s.size()}));
}
} // namespace Void::Encoding::Hex
+571 -101
View File
@@ -1,132 +1,602 @@
#pragma once
#include <charconv>
#include <compare>
#include <cstdlib>
#include <format>
#include <limits>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Semver
{
// ── Version ───────────────────────────────────────────────────────────────────
namespace Detail
{
[[nodiscard]] constexpr bool is_digit(char value) noexcept
{
return value >= '0' && value <= '9';
}
struct Version
{
unsigned major{0};
unsigned minor{0};
unsigned patch{0};
std::string pre_release; // e.g. "alpha.1"
std::string build; // e.g. "20240101"
[[nodiscard]] constexpr bool
is_identifier_character(char value) noexcept
{
return is_digit(value) || (value >= 'A' && value <= 'Z') ||
(value >= 'a' && value <= 'z') || value == '-';
}
[[nodiscard]] std::string to_string() const
{
std::string s = std::format("{}.{}.{}", major, minor, patch);
if (!pre_release.empty()) { s += '-'; s += pre_release; }
if (!build.empty()) { s += '+'; s += build; }
return s;
}
[[nodiscard]] inline bool
is_numeric(std::string_view identifier) noexcept
{
if (identifier.empty()) {
return false;
}
for (const char value : identifier) {
if (!is_digit(value)) {
return false;
}
}
return true;
}
// Precedence comparison per semver spec (build metadata ignored).
[[nodiscard]] std::strong_ordering
operator<=>(const Version& o) const noexcept
{
if (auto c = major <=> o.major; c != 0) return c;
if (auto c = minor <=> o.minor; c != 0) return c;
if (auto c = patch <=> o.patch; c != 0) return c;
// No pre-release > has pre-release
const bool l_pre = !pre_release.empty();
const bool r_pre = !o.pre_release.empty();
if (!l_pre && r_pre) return std::strong_ordering::greater;
if (l_pre && !r_pre) return std::strong_ordering::less;
// Both have pre-release — lexicographic (simplified)
if (auto c = pre_release <=> o.pre_release; c != 0) {
return c < 0 ? std::strong_ordering::less
: std::strong_ordering::greater;
}
return std::strong_ordering::equal;
}
[[nodiscard]] inline std::strong_ordering
compare_identifier(std::string_view left,
std::string_view right) noexcept
{
const bool left_numeric = is_numeric(left);
const bool right_numeric = is_numeric(right);
if (left_numeric && right_numeric) {
if (left.size() != right.size()) {
return left.size() < right.size()
? std::strong_ordering::less
: std::strong_ordering::greater;
}
return left <=> right;
}
if (left_numeric != right_numeric) {
return left_numeric ? std::strong_ordering::less
: std::strong_ordering::greater;
}
return left <=> right;
}
[[nodiscard]] bool operator==(const Version& o) const noexcept
{
return major == o.major && minor == o.minor && patch == o.patch &&
pre_release == o.pre_release;
}
[[nodiscard]] inline std::strong_ordering
compare_prerelease(std::string_view left,
std::string_view right) noexcept
{
std::size_t left_begin = 0;
std::size_t right_begin = 0;
for (;;) {
const auto left_end = left.find('.', left_begin);
const auto right_end = right.find('.', right_begin);
const auto left_id =
left.substr(left_begin, left_end == std::string_view::npos
? std::string_view::npos
: left_end - left_begin);
const auto right_id = right.substr(
right_begin, right_end == std::string_view::npos
? std::string_view::npos
: right_end - right_begin);
if (const auto comparison =
compare_identifier(left_id, right_id);
comparison != 0) {
return comparison;
}
const bool left_done = left_end == std::string_view::npos;
const bool right_done = right_end == std::string_view::npos;
if (left_done || right_done) {
if (left_done == right_done) {
return std::strong_ordering::equal;
}
return left_done ? std::strong_ordering::less
: std::strong_ordering::greater;
}
left_begin = left_end + 1;
right_begin = right_end + 1;
}
}
// Is this version compatible with `required`? (same major, >= minor.patch)
[[nodiscard]] bool compatible_with(const Version& required) const noexcept
{
if (major != required.major) return false;
return (*this <=> required) >= 0;
}
[[nodiscard]] inline bool
valid_identifiers(std::string_view value,
bool reject_numeric_leading_zero) noexcept
{
if (value.empty()) {
return false;
}
std::size_t begin = 0;
for (;;) {
const auto end = value.find('.', begin);
const auto identifier =
value.substr(begin, end == std::string_view::npos
? std::string_view::npos
: end - begin);
if (identifier.empty()) {
return false;
}
for (const char character : identifier) {
if (!is_identifier_character(character)) {
return false;
}
}
if (reject_numeric_leading_zero && identifier.size() > 1 &&
identifier.front() == '0' && is_numeric(identifier)) {
return false;
}
if (end == std::string_view::npos) {
return true;
}
begin = end + 1;
}
}
[[nodiscard]] bool is_stable() const noexcept
{
return major >= 1 && pre_release.empty();
}
[[nodiscard]] inline bool parse_component(std::string_view value,
unsigned& output) noexcept
{
if (value.empty() || (value.size() > 1 && value.front() == '0')) {
return false;
}
unsigned long long parsed = 0;
const auto [end, error] = std::from_chars(
value.data(), value.data() + value.size(), parsed);
if (error != std::errc{} || end != value.data() + value.size() ||
parsed > std::numeric_limits<unsigned>::max()) {
return false;
}
output = static_cast<unsigned>(parsed);
return true;
}
[[nodiscard]] Version bumped_major() const noexcept
{
return {major + 1, 0, 0};
}
[[nodiscard]] constexpr std::string_view
trim(std::string_view value) noexcept
{
while (!value.empty() &&
(value.front() == ' ' || value.front() == '\t' ||
value.front() == '\r' || value.front() == '\n')) {
value.remove_prefix(1);
}
while (!value.empty() &&
(value.back() == ' ' || value.back() == '\t' ||
value.back() == '\r' || value.back() == '\n')) {
value.remove_suffix(1);
}
return value;
}
} // namespace Detail
[[nodiscard]] Version bumped_minor() const noexcept
{
return {major, minor + 1, 0};
}
struct Version {
unsigned major{0};
unsigned minor{0};
unsigned patch{0};
std::string pre_release;
std::string build;
[[nodiscard]] Version bumped_patch() const noexcept
{
return {major, minor, patch + 1};
}
};
[[nodiscard]] std::string to_string() const
{
std::string value =
std::format("{}.{}.{}", major, minor, patch);
if (!pre_release.empty()) {
value += '-';
value += pre_release;
}
if (!build.empty()) {
value += '+';
value += build;
}
return value;
}
// ── Parsing ───────────────────────────────────────────────────────────────────
[[nodiscard]] std::strong_ordering
operator<=>(const Version& other) const noexcept
{
if (const auto comparison = major <=> other.major;
comparison != 0) {
return comparison;
}
if (const auto comparison = minor <=> other.minor;
comparison != 0) {
return comparison;
}
if (const auto comparison = patch <=> other.patch;
comparison != 0) {
return comparison;
}
if (pre_release.empty() != other.pre_release.empty()) {
return pre_release.empty() ? std::strong_ordering::greater
: std::strong_ordering::less;
}
if (pre_release.empty()) {
return std::strong_ordering::equal;
}
return Detail::compare_prerelease(pre_release,
other.pre_release);
}
[[nodiscard]] inline std::optional<Version> parse(std::string_view s)
{
Version v;
[[nodiscard]] bool operator==(const Version& other) const noexcept
{
return major == other.major && minor == other.minor &&
patch == other.patch && pre_release == other.pre_release;
}
auto parse_uint = [](std::string_view sv, unsigned& out) -> bool {
if (sv.empty()) return false;
out = 0;
for (char c : sv) {
if (c < '0' || c > '9') return false;
out = out * 10 + static_cast<unsigned>(c - '0');
}
return true;
};
[[nodiscard]] bool
compatible_with(const Version& required) const noexcept
{
return major == required.major && (*this <=> required) >= 0;
}
// Optional leading 'v'
if (!s.empty() && (s[0] == 'v' || s[0] == 'V')) s.remove_prefix(1);
[[nodiscard]] bool is_stable() const noexcept
{
return major >= 1 && pre_release.empty();
}
// Split build metadata first
const auto plus = s.find('+');
if (plus != std::string_view::npos) {
v.build = std::string{s.substr(plus + 1)};
s = s.substr(0, plus);
}
[[nodiscard]] Version bumped_major() const noexcept
{
return Version{.major = major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
}
// Split pre-release
const auto dash = s.find('-');
if (dash != std::string_view::npos) {
v.pre_release = std::string{s.substr(dash + 1)};
s = s.substr(0, dash);
}
[[nodiscard]] Version bumped_minor() const noexcept
{
return Version{.major = major,
.minor = minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
}
// Major.minor.patch
const auto d1 = s.find('.');
if (d1 == std::string_view::npos) return std::nullopt;
if (!parse_uint(s.substr(0, d1), v.major)) return std::nullopt;
s = s.substr(d1 + 1);
[[nodiscard]] Version bumped_patch() const noexcept
{
return Version{.major = major,
.minor = minor,
.patch = patch + 1,
.pre_release = {},
.build = {}};
}
};
const auto d2 = s.find('.');
if (d2 == std::string_view::npos) return std::nullopt;
if (!parse_uint(s.substr(0, d2), v.minor)) return std::nullopt;
if (!parse_uint(s.substr(d2 + 1), v.patch)) return std::nullopt;
namespace Detail
{
[[nodiscard]] inline std::optional<Version>
parse_version(std::string_view value, bool allow_v_prefix)
{
if (allow_v_prefix && !value.empty() &&
(value.front() == 'v' || value.front() == 'V')) {
value.remove_prefix(1);
}
if (value.empty()) {
return std::nullopt;
}
return v;
}
Version version;
const auto plus = value.find('+');
if (plus != std::string_view::npos) {
if (value.find('+', plus + 1) != std::string_view::npos) {
return std::nullopt;
}
const auto metadata = value.substr(plus + 1);
if (!valid_identifiers(metadata, false)) {
return std::nullopt;
}
version.build = std::string{metadata};
value = value.substr(0, plus);
}
const auto dash = value.find('-');
if (dash != std::string_view::npos) {
const auto prerelease = value.substr(dash + 1);
if (!valid_identifiers(prerelease, true)) {
return std::nullopt;
}
version.pre_release = std::string{prerelease};
value = value.substr(0, dash);
}
const auto first_dot = value.find('.');
if (first_dot == std::string_view::npos) {
return std::nullopt;
}
const auto second_dot = value.find('.', first_dot + 1);
if (second_dot == std::string_view::npos ||
value.find('.', second_dot + 1) != std::string_view::npos) {
return std::nullopt;
}
if (!parse_component(value.substr(0, first_dot), version.major) ||
!parse_component(
value.substr(first_dot + 1, second_dot - first_dot - 1),
version.minor) ||
!parse_component(value.substr(second_dot + 1), version.patch)) {
return std::nullopt;
}
return version;
}
} // namespace Detail
/// Parse SemVer while retaining the historic optional `v` prefix.
[[nodiscard]] inline std::optional<Version> parse(std::string_view value)
{
return Detail::parse_version(value, true);
}
/// Parse exactly according to SemVer 2.0.0 (no leading `v`).
[[nodiscard]] inline std::optional<Version>
parse_strict(std::string_view value)
{
return Detail::parse_version(value, false);
}
class VersionRange
{
public:
[[nodiscard]] static std::optional<VersionRange>
parse(std::string_view expression)
{
VersionRange result;
expression = Detail::trim(expression);
if (expression.empty() || expression == "*") {
result.m_alternatives.emplace_back();
return result;
}
std::size_t clause_begin = 0;
for (;;) {
const auto separator = expression.find("||", clause_begin);
const auto clause_text = Detail::trim(expression.substr(
clause_begin, separator == std::string_view::npos
? std::string_view::npos
: separator - clause_begin));
if (clause_text.empty()) {
return std::nullopt;
}
Clause clause;
std::size_t token_begin = 0;
while (token_begin < clause_text.size()) {
while (token_begin < clause_text.size() &&
(clause_text[token_begin] == ' ' ||
clause_text[token_begin] == '\t')) {
++token_begin;
}
if (token_begin == clause_text.size()) {
break;
}
auto token_end =
clause_text.find_first_of(" \t", token_begin);
if (token_end == std::string_view::npos) {
token_end = clause_text.size();
}
if (!append_token(
clause,
clause_text.substr(token_begin,
token_end - token_begin))) {
return std::nullopt;
}
token_begin = token_end;
}
result.m_alternatives.push_back(std::move(clause));
if (separator == std::string_view::npos) {
break;
}
clause_begin = separator + 2;
}
return result;
}
[[nodiscard]] bool contains(const Version& version) const noexcept
{
for (const auto& clause : m_alternatives) {
bool matches = true;
for (const auto& comparator : clause) {
if (!comparator.matches(version)) {
matches = false;
break;
}
}
if (matches) {
return true;
}
}
return false;
}
private:
enum class Operation {
Equal,
Greater,
GreaterEqual,
Less,
LessEqual
};
struct Comparator {
Operation operation{Operation::Equal};
Version version;
[[nodiscard]] bool
matches(const Version& candidate) const noexcept
{
const auto comparison = candidate <=> version;
switch (operation) {
case Operation::Equal:
return comparison == 0;
case Operation::Greater:
return comparison > 0;
case Operation::GreaterEqual:
return comparison >= 0;
case Operation::Less:
return comparison < 0;
case Operation::LessEqual:
return comparison <= 0;
}
return false;
}
};
using Clause = std::vector<Comparator>;
std::vector<Clause> m_alternatives;
[[nodiscard]] static bool append_token(Clause& clause,
std::string_view token)
{
if (token == "*") {
return true;
}
if (token.starts_with('^') || token.starts_with('~')) {
const char kind = token.front();
token.remove_prefix(1);
const auto lower = parse_strict(token);
if (!lower) {
return false;
}
Version upper;
if (kind == '~') {
if (lower->minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major,
.minor = lower->minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->major > 0) {
if (lower->major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->minor > 0) {
if (lower->minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = 0,
.minor = lower->minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else {
if (lower->patch ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = 0,
.minor = 0,
.patch = lower->patch + 1,
.pre_release = {},
.build = {}};
}
clause.push_back({Operation::GreaterEqual, *lower});
clause.push_back({Operation::Less, std::move(upper)});
return true;
}
if (token.find_first_of("xX*") != std::string_view::npos) {
return append_wildcard(clause, token);
}
Operation operation = Operation::Equal;
if (token.starts_with(">=")) {
operation = Operation::GreaterEqual;
token.remove_prefix(2);
} else if (token.starts_with("<=")) {
operation = Operation::LessEqual;
token.remove_prefix(2);
} else if (token.starts_with('>')) {
operation = Operation::Greater;
token.remove_prefix(1);
} else if (token.starts_with('<')) {
operation = Operation::Less;
token.remove_prefix(1);
} else if (token.starts_with('=')) {
token.remove_prefix(1);
}
const auto version = parse_strict(token);
if (!version) {
return false;
}
clause.push_back({operation, *version});
return true;
}
[[nodiscard]] static bool append_wildcard(Clause& clause,
std::string_view token)
{
const auto first_dot = token.find('.');
if (first_dot == std::string_view::npos) {
return token == "x" || token == "X" || token == "*";
}
const auto second_dot = token.find('.', first_dot + 1);
unsigned major = 0;
if (!Detail::parse_component(token.substr(0, first_dot),
major)) {
return false;
}
const auto minor_text = token.substr(
first_dot + 1, second_dot == std::string_view::npos
? std::string_view::npos
: second_dot - first_dot - 1);
if (minor_text == "x" || minor_text == "X" ||
minor_text == "*") {
if (second_dot != std::string_view::npos) {
return false;
}
if (major == std::numeric_limits<unsigned>::max()) {
return false;
}
clause.push_back(
{Operation::GreaterEqual, Version{.major = major,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}}});
clause.push_back(
{Operation::Less, Version{.major = major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}}});
return true;
}
unsigned minor = 0;
if (!Detail::parse_component(minor_text, minor) ||
second_dot == std::string_view::npos) {
return false;
}
const auto patch_text = token.substr(second_dot + 1);
if (patch_text != "x" && patch_text != "X" &&
patch_text != "*") {
return false;
}
if (minor == std::numeric_limits<unsigned>::max()) {
return false;
}
clause.push_back(
{Operation::GreaterEqual, Version{.major = major,
.minor = minor,
.patch = 0,
.pre_release = {},
.build = {}}});
clause.push_back({Operation::Less, Version{.major = major,
.minor = minor + 1,
.patch = 0,
.pre_release = {},
.build = {}}});
return true;
}
};
[[nodiscard]] inline std::optional<VersionRange>
parse_range(std::string_view expression)
{
return VersionRange::parse(expression);
}
} // namespace Void::Semver
+5 -2
View File
@@ -103,7 +103,10 @@ template <typename T>
inline void do_not_optimize(T& val) noexcept
{
#if defined(__GNUC__) || defined(__clang__)
asm volatile("" : "+r,m"(val) : : "memory");
// A memory operand works for every object type and remains accepted by
// GCC 16, which rejects the old mixed "+r,m" alternative constraint for
// some scalar instantiations.
asm volatile("" : "+m"(val) : : "memory");
#else
volatile T* p = &val;
(void)*p;
@@ -114,7 +117,7 @@ template <typename T>
inline void do_not_optimize(const T& val) noexcept
{
#if defined(__GNUC__) || defined(__clang__)
asm volatile("" : : "r,m"(val) : "memory");
asm volatile("" : : "m"(val) : "memory");
#else
volatile const T* p = &val;
(void)*p;
+196
View File
@@ -0,0 +1,196 @@
#pragma once
#include <Void/Crypto/Crypto.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
namespace Void::Update
{
struct Compatibility {
std::unordered_map<std::string, Semver::VersionRange>
versionContracts;
std::unordered_map<std::string, std::string> exactContracts;
};
struct Release {
std::string component;
std::string artifactId;
std::string channel;
Semver::Version version;
std::string cohort;
std::string platform;
std::string architecture;
std::string url;
std::uint64_t size{0};
std::string sha256;
std::string packageType;
Compatibility compatibility;
std::string releaseManifestSha256;
};
struct Feed {
std::uint32_t schemaVersion{1};
std::string feedId;
std::uint64_t sequence{0};
std::chrono::system_clock::time_point generatedAt;
std::chrono::system_clock::time_point expiresAt;
std::vector<Release> releases;
};
struct FeedEnvelope {
std::uint32_t schemaVersion{1};
std::string keyId;
std::string payload;
Crypto::Digest signature;
};
using Ed25519PublicKey =
std::array<std::byte, Crypto::Ed25519PublicKeySize>;
using Keyring = std::unordered_map<std::string, Ed25519PublicKey>;
struct VerificationPolicy {
std::size_t maxEnvelopeBytes{5 * 1024 * 1024};
std::size_t maxPayloadBytes{4 * 1024 * 1024};
std::size_t maxReleases{10'000};
std::optional<std::uint64_t> minimumSequence;
std::chrono::system_clock::time_point now{
std::chrono::system_clock::now()};
bool requireUnexpired{true};
};
struct VerifiedFeed {
Feed feed;
std::string keyId;
std::string signedPayload;
};
/// A signature-verified payload whose schema-specific parsing is left to
/// the caller. This is useful for signed discovery documents that are not
/// legacy aggregate feeds.
struct VerifiedEnvelope {
std::uint32_t schemaVersion{0};
std::string keyId;
std::string signedPayload;
};
struct ComponentArtifact {
std::string name;
std::string url;
std::string sha256;
std::uint64_t size{0};
std::string manifestSha256;
std::string packageType;
};
struct ComponentCatalogEntry {
std::string componentId;
std::optional<std::string> pluginId;
std::string kind;
Semver::Version componentVersion;
std::string activation;
std::map<std::string, std::string> dependencyConstraints;
std::map<std::string, Semver::VersionRange> dependencies;
std::uint64_t sequence{0};
std::string latestUrl;
std::string artifactSha256;
};
struct ComponentCatalog {
std::uint32_t schemaVersion{2};
std::string channel;
std::uint64_t sequence{0};
std::chrono::system_clock::time_point generatedAt;
std::chrono::system_clock::time_point expiresAt;
Semver::Version productVersion;
std::vector<ComponentCatalogEntry> components;
};
struct ComponentRelease {
std::uint32_t schemaVersion{2};
std::string channel;
std::uint64_t sequence{0};
std::chrono::system_clock::time_point generatedAt;
std::chrono::system_clock::time_point expiresAt;
Semver::Version productVersion;
std::string componentId;
std::optional<std::string> pluginId;
std::string kind;
Semver::Version componentVersion;
std::string sourceSha;
std::string sourceTreeHash;
std::optional<std::string> abiHash;
std::string artifactIdentity;
std::string activation;
std::string platform;
std::string architecture;
std::string toolchainContract;
std::map<std::string, std::string> dependencyConstraints;
std::map<std::string, Semver::VersionRange> dependencies;
ComponentArtifact artifact;
};
struct Environment {
std::unordered_map<std::string, Semver::Version> versionContracts;
std::unordered_map<std::string, std::string> exactContracts;
std::string platform;
std::string architecture;
};
struct SelectionRequest {
std::string component;
std::string artifactId;
std::string channel;
Environment environment;
std::optional<Semver::Version> currentVersion;
std::optional<std::string> requiredCohort;
bool allowDowngrade{false};
bool includeCurrent{false};
};
/// Parse and validate an unsigned payload. Trust and activation policy is a
/// caller concern; all structural, size, expiry and replay checks still
/// run.
[[nodiscard]] Void::Result::Result<Feed>
parseFeedPayload(std::string_view payload,
const VerificationPolicy& policy = {});
/// Verify the envelope signature before parsing the signed payload.
[[nodiscard]] Void::Result::Result<VerifiedFeed>
verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys,
const VerificationPolicy& policy = {});
/// Verify and decode a signed envelope without assuming a payload schema.
[[nodiscard]] Void::Result::Result<VerifiedEnvelope>
verifyEnvelope(std::string_view envelopeJson, const Keyring& keys,
const VerificationPolicy& policy = {});
[[nodiscard]] Void::Result::Result<ComponentCatalog>
parseComponentCatalogPayload(std::string_view payload,
const VerificationPolicy& policy = {});
[[nodiscard]] Void::Result::Result<ComponentRelease>
parseComponentReleasePayload(std::string_view payload,
const VerificationPolicy& policy = {});
/// Validate that a catalog and its fetched releases form one complete,
/// dependency-compatible transaction.
[[nodiscard]] Void::Result::Result<void> validateComponentSet(
const ComponentCatalog& catalog,
const std::map<std::string, ComponentRelease>& releases);
/// Select the greatest compatible version, independent of feed order.
[[nodiscard]] std::optional<Release>
selectRelease(const Feed& feed, const SelectionRequest& request);
} // namespace Void::Update
+4
View File
@@ -0,0 +1,4 @@
#pragma once
#include <Void/Update/Feed.hpp>
#include <Void/Update/VersionStore.hpp>
+102
View File
@@ -0,0 +1,102 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <vector>
namespace Void::Update
{
struct PendingActivation {
std::optional<Semver::Version> previousVersion;
Semver::Version candidateVersion;
/// Health-log generation observed before activation. A later
/// healthy event for the candidate is the durable commit marker
/// used to reconcile an activation journal left behind by a
/// post-commit cleanup failure.
std::uint64_t healthGeneration{};
};
/// Immutable version directory store with a relative `current` symlink and
/// a durable activation journal. An uncommitted activation is rolled back
/// by reconcile(), making candidate health checks an explicit commit
/// boundary.
///
/// The crash-durability and cross-process locking guarantees are provided
/// by the POSIX implementation. The current Windows fallback is functional
/// but does not yet provide equivalent crash durability or process locking.
class VersionStore
{
public:
explicit VersionStore(std::filesystem::path root);
[[nodiscard]] Void::Result::Result<void> initialize();
[[nodiscard]] Void::Result::Result<std::filesystem::path>
prepare(const Semver::Version& version);
[[nodiscard]] Void::Result::Result<void>
publish(const Semver::Version& version,
const std::filesystem::path& stagingDirectory);
[[nodiscard]] Void::Result::Result<void>
activate(const Semver::Version& version);
/// Idempotently accept the candidate. A durable healthy-history
/// event is the commit point; activation-journal cleanup after that
/// point cannot be reported as a reversible failure.
[[nodiscard]] Void::Result::Result<void> commit();
/// Idempotently restore the previous version. The journal is
/// retained until restoration succeeds. A candidate whose commit
/// marker is newer than the journal baseline is finalized instead
/// of rolled back.
[[nodiscard]] Void::Result::Result<void> rollback();
[[nodiscard]] Void::Result::Result<void> reconcile();
/// Record a successful activation performed by an external
/// lifecycle owner. The published version must be a real immediate
/// directory. Every call appends a durable healthy event and
/// refreshes retention order. It rejects stores with an internal
/// activation journal so it cannot implicitly commit activate().
/// This method does not initialize the store or create staging.
[[nodiscard]] Void::Result::Result<void>
recordHealthy(const Semver::Version& version);
/// Record a failed external activation unless this version's
/// current publication lifecycle is already known healthy. A
/// retired and later republished SemVer starts a new lifecycle.
/// This method does not initialize the store or create staging.
[[nodiscard]] Void::Result::Result<void>
recordFailed(const Semver::Version& version);
/// Return real, currently published versions whose current
/// lifecycle is known healthy, newest durable healthy event first.
/// Missing, symlinked, failed, retired, and unknown publications
/// are excluded.
[[nodiscard]]
Void::Result::Result<std::vector<Semver::Version>>
healthyPublishedVersions() const;
/// Remove structurally valid, published version directories except
/// the active version, an in-flight activation's candidate and
/// previous version, and the requested number of most recently
/// committed healthy versions. Unknown publication state is
/// retained conservatively. Symlinks and the staging tree are never
/// traversed or removed. Returns the versions that were quarantined
/// and removed.
[[nodiscard]]
Void::Result::Result<std::vector<Semver::Version>>
prune(std::size_t retainedPreviousVersions);
[[nodiscard]] Void::Result::Result<std::optional<Semver::Version>>
currentVersion() const;
[[nodiscard]] Void::Result::Result<std::optional<PendingActivation>>
pendingActivation() const;
[[nodiscard]] const std::filesystem::path& root() const noexcept;
[[nodiscard]] std::filesystem::path
versionPath(const Semver::Version& version) const;
private:
std::filesystem::path m_root;
};
} // namespace Void::Update
-5
View File
@@ -1,5 +0,0 @@
where possible for logger add colors, also add configurable patterns(like threadId, service\custom, time level, etc) and allow user to change their positions and apperance, and allow user define custom, also allow for file logger, have ability to
split by levels into differen files(have one file which gonna output all levels), add saving to history. I wanna that state machine\fsm is class which should be inherited, states should be define as class\struct inside class which inherited base class
of fsm\state machine, then user should write realisation how each state should behave and each state should return or another state, or fail, or success. You should make only one realisation FSM, it should async by default, have ability to nest other
state machines to enter to them and wait their result, fsm should be dynamic(this means not all states always gonna be, some of them can be optional on specific conditions). Also i wanna that your create service\manager which can be used as
archistrator of FSM. Also define base class for services with interfaces which allow to call them, without directly depending on them
+652
View File
@@ -0,0 +1,652 @@
#include <Void/Archive/Archive.hpp>
#include <array>
#include <atomic>
#include <cerrno>
#include <cstring>
#include <format>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <archive.h>
#include <archive_entry.h>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#else
#include <fstream>
#endif
namespace Void::Archive
{
namespace
{
using ArchiveHandle =
std::unique_ptr<archive, decltype(&archive_read_free)>;
[[nodiscard]] Void::Result::Error
archive_error(archive *reader, std::string_view operation)
{
const char *message = archive_error_string(reader);
return Void::Result::Error{std::format(
"Archive::extract: {}: {}", operation,
message == nullptr ? "unknown archive error" : message)};
}
[[nodiscard]] std::optional<std::filesystem::path>
safe_relative_path(std::string_view rawPath, bool directory)
{
if (rawPath.empty() ||
rawPath.find('\\') != std::string_view::npos) {
return std::nullopt;
}
if (rawPath.back() == '/') {
if (!directory) {
return std::nullopt;
}
rawPath.remove_suffix(1);
if (rawPath.empty() || rawPath.back() == '/') {
return std::nullopt;
}
}
if (rawPath.front() == '/' ||
rawPath.find("//") != std::string_view::npos) {
return std::nullopt;
}
const std::filesystem::path path{rawPath};
if (path.empty() || path.is_absolute() || path.has_root_name() ||
path.lexically_normal() != path) {
return std::nullopt;
}
for (const auto &component : path) {
if (component.empty() || component == "." ||
component == "..") {
return std::nullopt;
}
}
return path;
}
#ifndef _WIN32
class FileDescriptor
{
public:
explicit FileDescriptor(int descriptor = -1) noexcept
: m_descriptor(descriptor)
{
}
~FileDescriptor() { reset(); }
FileDescriptor(FileDescriptor &&other) noexcept
: m_descriptor(std::exchange(other.m_descriptor, -1))
{
}
FileDescriptor &operator=(FileDescriptor &&other) noexcept
{
if (this != &other) {
reset(std::exchange(other.m_descriptor, -1));
}
return *this;
}
FileDescriptor(const FileDescriptor &) = delete;
FileDescriptor &operator=(const FileDescriptor &) = delete;
[[nodiscard]] int get() const noexcept { return m_descriptor; }
[[nodiscard]] explicit operator bool() const noexcept
{
return m_descriptor >= 0;
}
[[nodiscard]] int release() noexcept
{
return std::exchange(m_descriptor, -1);
}
void reset(int descriptor = -1) noexcept
{
if (m_descriptor >= 0) {
(void)::close(m_descriptor);
}
m_descriptor = descriptor;
}
private:
int m_descriptor{-1};
};
constexpr int directoryOpenFlags =
O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW;
constexpr std::size_t maximumTemporaryAttempts = 128;
std::atomic<std::uint64_t> temporaryCounter{0};
[[nodiscard]] Void::Result::Result<FileDescriptor>
open_destination(const std::filesystem::path &destination)
{
FileDescriptor descriptor{
::open(destination.c_str(), directoryOpenFlags)};
if (!descriptor) {
return Void::Result::fail(
std::format("Archive::extract: open destination '{}': {}",
destination.string(), std::strerror(errno)));
}
return descriptor;
}
[[nodiscard]] Void::Result::Result<FileDescriptor>
open_parent_directory(int rootDescriptor,
const std::filesystem::path &relativeParent,
const std::filesystem::path &displayRoot)
{
FileDescriptor current{
::openat(rootDescriptor, ".", directoryOpenFlags)};
if (!current) {
return Void::Result::fail(std::format(
"Archive::extract: duplicate destination '{}': {}",
displayRoot.string(), std::strerror(errno)));
}
std::filesystem::path displayPath = displayRoot;
for (const auto &component : relativeParent) {
const std::string name{component.native()};
displayPath /= component;
int descriptor =
::openat(current.get(), name.c_str(), directoryOpenFlags);
if (descriptor < 0 && errno == ENOENT) {
if (::mkdirat(current.get(), name.c_str(), 0755) != 0 &&
errno != EEXIST) {
return Void::Result::fail(std::format(
"Archive::extract: cannot create directory '{}': "
"{}",
displayPath.string(), std::strerror(errno)));
}
descriptor = ::openat(current.get(), name.c_str(),
directoryOpenFlags);
}
if (descriptor < 0) {
return Void::Result::fail(std::format(
"Archive::extract: unsafe parent '{}': {}",
displayPath.string(), std::strerror(errno)));
}
current = FileDescriptor{descriptor};
}
return current;
}
[[nodiscard]] Void::Result::Result<void> create_directory_entry(
int rootDescriptor, const std::filesystem::path &relative,
const std::filesystem::path &displayRoot, bool overwrite)
{
auto openedParent = open_parent_directory(
rootDescriptor, relative.parent_path(), displayRoot);
if (!openedParent) {
return std::unexpected{openedParent.error()};
}
auto parent = std::move(*openedParent);
const std::string name{relative.filename().native()};
const auto displayPath = displayRoot / relative;
if (::mkdirat(parent.get(), name.c_str(), 0755) == 0) {
return {};
}
if (errno != EEXIST) {
return Void::Result::fail(std::format(
"Archive::extract: cannot create directory '{}': {}",
displayPath.string(), std::strerror(errno)));
}
if (!overwrite) {
return Void::Result::fail(std::format(
"Archive::extract: destination '{}' already exists",
displayPath.string()));
}
FileDescriptor existing{
::openat(parent.get(), name.c_str(), directoryOpenFlags)};
if (!existing) {
return Void::Result::fail(std::format(
"Archive::extract: destination '{}' is not a real "
"directory",
displayPath.string()));
}
return {};
}
[[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, int rootDescriptor,
const std::filesystem::path &relative,
const std::filesystem::path &displayRoot,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted, bool executable)
{
auto openedParent = open_parent_directory(
rootDescriptor, relative.parent_path(), displayRoot);
if (!openedParent) {
return std::unexpected{openedParent.error()};
}
auto parent = std::move(*openedParent);
const std::string outputName{relative.filename().native()};
const auto displayPath = displayRoot / relative;
FileDescriptor descriptor;
std::string temporaryName;
for (std::size_t attempt = 0; attempt < maximumTemporaryAttempts;
++attempt) {
const auto sequence =
temporaryCounter.fetch_add(1, std::memory_order_relaxed);
temporaryName =
std::format(".void-archive-{}-{}",
static_cast<long long>(::getpid()), sequence);
const int opened = ::openat(parent.get(), temporaryName.c_str(),
O_WRONLY | O_CREAT | O_EXCL |
O_CLOEXEC | O_NOFOLLOW,
executable ? 0755 : 0644);
if (opened >= 0) {
descriptor = FileDescriptor{opened};
break;
}
if (errno != EEXIST) {
return Void::Result::fail(std::format(
"Archive::extract: create temporary file for '{}': {}",
displayPath.string(), std::strerror(errno)));
}
}
if (!descriptor) {
return Void::Result::fail(std::format(
"Archive::extract: cannot allocate temporary file for '{}'",
displayPath.string()));
}
auto removeTemporary = [&]() noexcept {
descriptor.reset();
if (!temporaryName.empty()) {
(void)::unlinkat(parent.get(), temporaryName.c_str(), 0);
temporaryName.clear();
}
};
auto fail = [&](std::string message)
-> Void::Result::Result<std::uint64_t> {
removeTemporary();
return Void::Result::fail(std::move(message));
};
std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0;
for (;;) {
const auto count =
archive_read_data(reader, buffer.data(), buffer.size());
if (count == 0) {
break;
}
if (count < 0) {
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
if (amount > options.maxFileBytes - fileBytes ||
amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) {
return fail(
"Archive::extract: extracted size exceeds policy");
}
std::size_t written = 0;
while (written < static_cast<std::size_t>(count)) {
const auto result = ::write(
descriptor.get(),
reinterpret_cast<const char *>(buffer.data()) + written,
static_cast<std::size_t>(count) - written);
if (result < 0 && errno == EINTR) {
continue;
}
if (result <= 0) {
const int error = errno;
return fail(std::format(
"Archive::extract: write '{}': {}",
displayPath.string(), std::strerror(error)));
}
written += static_cast<std::size_t>(result);
}
fileBytes += amount;
}
if (::fsync(descriptor.get()) != 0) {
const int error = errno;
return fail(std::format("Archive::extract: fsync '{}': {}",
displayPath.string(),
std::strerror(error)));
}
const int rawDescriptor = descriptor.release();
if (::close(rawDescriptor) != 0) {
const int error = errno;
return fail(std::format("Archive::extract: close '{}': {}",
displayPath.string(),
std::strerror(error)));
}
if (options.overwriteExisting) {
struct stat status{};
if (::fstatat(parent.get(), outputName.c_str(), &status,
AT_SYMLINK_NOFOLLOW) == 0) {
if (!S_ISREG(status.st_mode)) {
return fail(std::format(
"Archive::extract: destination '{}' is not a "
"regular file",
displayPath.string()));
}
} else if (errno != ENOENT) {
const int error = errno;
return fail(std::format(
"Archive::extract: inspect destination '{}': {}",
displayPath.string(), std::strerror(error)));
}
if (::renameat(parent.get(), temporaryName.c_str(),
parent.get(), outputName.c_str()) != 0) {
const int error = errno;
return fail(std::format(
"Archive::extract: publish '{}': {}",
displayPath.string(), std::strerror(error)));
}
temporaryName.clear();
} else {
if (::linkat(parent.get(), temporaryName.c_str(), parent.get(),
outputName.c_str(), 0) != 0) {
const int error = errno;
return fail(std::format(
"Archive::extract: publish '{}': {}",
displayPath.string(), std::strerror(error)));
}
int unlinkResult = 0;
do {
unlinkResult =
::unlinkat(parent.get(), temporaryName.c_str(), 0);
} while (unlinkResult != 0 && errno == EINTR);
if (unlinkResult != 0 && errno != ENOENT) {
const int error = errno;
return fail(std::format(
"Archive::extract: remove temporary file for '{}': {}",
displayPath.string(), std::strerror(error)));
}
temporaryName.clear();
}
return fileBytes;
}
#else
[[nodiscard]] Void::Result::Result<void>
safe_parents(const std::filesystem::path &root,
const std::filesystem::path &relativeParent)
{
std::filesystem::path current = root;
for (const auto &component : relativeParent) {
current /= component;
std::error_code error;
const auto status =
std::filesystem::symlink_status(current, error);
if (!error &&
status.type() != std::filesystem::file_type::not_found) {
if (std::filesystem::is_symlink(status) ||
!std::filesystem::is_directory(status)) {
return Void::Result::fail(
std::format("Archive::extract: unsafe parent '{}'",
current.string()));
}
continue;
}
if (error && error != std::errc::no_such_file_or_directory) {
return Void::Result::fail(
std::format("Archive::extract: cannot inspect '{}': {}",
current.string(), error.message()));
}
error.clear();
std::filesystem::create_directory(current, error);
if (error) {
return Void::Result::fail(
std::format("Archive::extract: cannot create '{}': {}",
current.string(), error.message()));
}
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
create_directory_entry(const std::filesystem::path &path,
bool overwrite)
{
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (!error &&
status.type() != std::filesystem::file_type::not_found) {
if (std::filesystem::is_symlink(status) ||
!std::filesystem::is_directory(status) || !overwrite) {
return Void::Result::fail(std::format(
"Archive::extract: destination '{}' already exists",
path.string()));
}
return {};
}
error.clear();
std::filesystem::create_directory(path, error);
if (error) {
return Void::Result::fail(std::format(
"Archive::extract: cannot create directory '{}': {}",
path.string(), error.message()));
}
return {};
}
[[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, const std::filesystem::path &path,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted)
{
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
if (!error &&
status.type() != std::filesystem::file_type::not_found &&
(std::filesystem::is_symlink(status) ||
!std::filesystem::is_regular_file(status))) {
return Void::Result::fail(std::format(
"Archive::extract: destination '{}' is not a regular file",
path.string()));
}
if (!options.overwriteExisting && !error &&
status.type() != std::filesystem::file_type::not_found) {
return Void::Result::fail(std::format(
"Archive::extract: destination '{}' already exists",
path.string()));
}
std::ofstream output{path, std::ios::binary | std::ios::trunc};
if (!output) {
return Void::Result::fail(std::format(
"Archive::extract: create '{}' failed", path.string()));
}
auto fail = [&](std::string message)
-> Void::Result::Result<std::uint64_t> {
output.close();
std::error_code removeError;
std::filesystem::remove(path, removeError);
return Void::Result::fail(std::move(message));
};
std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0;
for (;;) {
const auto count =
archive_read_data(reader, buffer.data(), buffer.size());
if (count == 0) {
break;
}
if (count < 0) {
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
if (amount > options.maxFileBytes - fileBytes ||
amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) {
return fail(
"Archive::extract: extracted size exceeds policy");
}
output.write(reinterpret_cast<const char *>(buffer.data()),
count);
if (!output) {
return fail("Archive::extract: write failed");
}
fileBytes += amount;
}
return fileBytes;
}
#endif
} // namespace
Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path &archivePath,
const std::filesystem::path &destination,
const ExtractionOptions &options)
{
if (options.maxEntries == 0 || options.maxFileBytes == 0 ||
options.maxTotalBytes == 0) {
return Void::Result::fail(
"Archive::extract: extraction limits must be positive");
}
std::error_code error;
std::filesystem::create_directories(destination, error);
if (error) {
return Void::Result::fail(
std::format("Archive::extract: cannot create destination: {}",
error.message()));
}
#ifndef _WIN32
auto root = open_destination(destination);
if (!root) {
return std::unexpected{root.error()};
}
#else
const auto root = std::filesystem::canonical(destination, error);
if (error || std::filesystem::is_symlink(
std::filesystem::symlink_status(destination, error))) {
return Void::Result::fail(
"Archive::extract: destination must be a real directory");
}
#endif
ArchiveHandle reader{archive_read_new(), &archive_read_free};
if (!reader) {
return Void::Result::fail(
"Archive::extract: cannot allocate archive reader");
}
archive_read_support_filter_zstd(reader.get());
archive_read_support_filter_none(reader.get());
archive_read_support_format_tar(reader.get());
#ifdef _WIN32
const int opened = archive_read_open_filename_w(
reader.get(), archivePath.c_str(), 64 * 1024);
#else
const int opened = archive_read_open_filename(
reader.get(), archivePath.c_str(), 64 * 1024);
#endif
if (opened != ARCHIVE_OK) {
return std::unexpected{archive_error(reader.get(), "open archive")};
}
ExtractionResult result;
std::set<std::filesystem::path> seen;
archive_entry *entry = nullptr;
for (;;) {
const int status = archive_read_next_header(reader.get(), &entry);
if (status == ARCHIVE_EOF) {
break;
}
if (status != ARCHIVE_OK) {
return std::unexpected{
archive_error(reader.get(), "read header")};
}
if (++result.entries > options.maxEntries) {
return Void::Result::fail(
"Archive::extract: entry count exceeds policy");
}
const char *rawPath = archive_entry_pathname(entry);
if (rawPath == nullptr) {
return Void::Result::fail(
"Archive::extract: entry has no path");
}
if (archive_entry_hardlink(entry) != nullptr ||
archive_entry_symlink(entry) != nullptr) {
return Void::Result::fail(
"Archive::extract: links are not allowed");
}
const auto type = archive_entry_filetype(entry);
if (type != AE_IFDIR && type != AE_IFREG) {
return Void::Result::fail(
"Archive::extract: special files are not allowed");
}
auto relative = safe_relative_path(rawPath, type == AE_IFDIR);
if (!relative || !seen.insert(*relative).second) {
return Void::Result::fail(std::format(
"Archive::extract: unsafe or duplicate path '{}'",
rawPath));
}
#ifdef _WIN32
if (auto parents = safe_parents(root, relative->parent_path());
!parents) {
return std::unexpected{parents.error()};
}
const auto output = root / *relative;
#endif
if (type == AE_IFDIR) {
#ifndef _WIN32
auto created =
create_directory_entry(root->get(), *relative, destination,
options.overwriteExisting);
#else
auto created =
create_directory_entry(output, options.overwriteExisting);
#endif
if (!created) {
return std::unexpected{created.error()};
}
continue;
}
const auto declared = archive_entry_size(entry);
if (declared < 0 ||
static_cast<std::uint64_t>(declared) > options.maxFileBytes ||
static_cast<std::uint64_t>(declared) >
options.maxTotalBytes - result.bytes) {
return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy");
}
#ifndef _WIN32
const bool executable = (archive_entry_perm(entry) & 0111) != 0;
auto extracted =
extract_regular(reader.get(), root->get(), *relative,
destination, options, result.bytes, executable);
#else
auto extracted =
extract_regular(reader.get(), output, options, result.bytes);
#endif
if (!extracted) {
return std::unexpected{extracted.error()};
}
result.bytes += *extracted;
}
return result;
}
} // namespace Void::Archive
+4
View File
@@ -0,0 +1,4 @@
void_add_module(Archive
INTERNAL_DEPS Functional
EXTERNAL_DEPS LibArchive::LibArchive
)
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Binary
INTERNAL_DEPS Functional
)
+257
View File
@@ -0,0 +1,257 @@
#include <Void/Crypto/Crypto.hpp>
#include <array>
#include <format>
#include <fstream>
#include <utility>
#include <openssl/err.h>
#include <openssl/evp.h>
namespace Void::Crypto
{
namespace
{
[[nodiscard]] const EVP_MD*
algorithm_impl(HashAlgorithm algorithm) noexcept
{
switch (algorithm) {
case HashAlgorithm::Sha1:
return EVP_sha1();
case HashAlgorithm::Sha256:
return EVP_sha256();
case HashAlgorithm::Sha512:
return EVP_sha512();
}
return nullptr;
}
[[nodiscard]] std::string openssl_error(std::string_view operation)
{
const unsigned long code = ERR_get_error();
if (code == 0) {
return std::string{operation};
}
std::array<char, 256> buffer{};
ERR_error_string_n(code, buffer.data(), buffer.size());
return std::format("{}: {}", operation, buffer.data());
}
} // namespace
struct Hasher::Impl {
EVP_MD_CTX* context{nullptr};
const EVP_MD* algorithm{nullptr};
bool finalized{false};
~Impl() { EVP_MD_CTX_free(context); }
};
Hasher::Hasher(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
Hasher::~Hasher() = default;
Hasher::Hasher(Hasher&&) noexcept = default;
Hasher& Hasher::operator=(Hasher&&) noexcept = default;
Void::Result::Result<Hasher> Hasher::create(HashAlgorithm algorithm)
{
auto impl = std::make_unique<Impl>();
impl->algorithm = algorithm_impl(algorithm);
if (impl->algorithm == nullptr) {
return Void::Result::fail("Crypto::Hasher: unsupported algorithm");
}
impl->context = EVP_MD_CTX_new();
if (impl->context == nullptr) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: EVP_MD_CTX_new failed"));
}
if (EVP_DigestInit_ex(impl->context, impl->algorithm, nullptr) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: digest initialization failed"));
}
return Hasher{std::move(impl)};
}
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::update: hasher is finalized or moved-from");
}
if (!data.empty() &&
EVP_DigestUpdate(m_impl->context, data.data(), data.size()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::update failed"));
}
return {};
}
Void::Result::Result<void> Hasher::update(std::string_view data)
{
return update(std::as_bytes(std::span{data.data(), data.size()}));
}
Void::Result::Result<Digest> Hasher::finalize()
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::finalize: hasher is finalized or moved-from");
}
const int digest_size = EVP_MD_get_size(m_impl->algorithm);
if (digest_size <= 0) {
return Void::Result::fail(
"Crypto::Hasher::finalize: invalid digest size");
}
Digest digest(static_cast<std::size_t>(digest_size));
unsigned int written = 0;
if (EVP_DigestFinal_ex(m_impl->context,
reinterpret_cast<unsigned char*>(digest.data()),
&written) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::finalize failed"));
}
m_impl->finalized = true;
digest.resize(written);
return digest;
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
-> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm);
if (!hasher) {
return std::unexpected{hasher.error()};
}
if (auto updated = hasher->update(data); !updated) {
return std::unexpected{updated.error()};
}
return hasher->finalize();
}
auto hash(HashAlgorithm algorithm, std::string_view data)
-> Void::Result::Result<Digest>
{
return hash(algorithm,
std::as_bytes(std::span{data.data(), data.size()}));
}
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
std::ifstream input{path, std::ios::binary};
if (!input.is_open()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: cannot open '{}'", path.string()));
}
auto hasher = Hasher::create(algorithm);
if (!hasher) {
return std::unexpected{hasher.error()};
}
std::array<char, 64 * 1024> buffer{};
while (input) {
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0) {
const auto bytes = std::as_bytes(
std::span{buffer.data(), static_cast<std::size_t>(count)});
if (auto updated = hasher->update(bytes); !updated) {
return std::unexpected{updated.error()};
}
}
}
if (input.bad()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: I/O error reading '{}'", path.string()));
}
return hasher->finalize();
}
Void::Result::Result<Digest> sha1(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Sha1, data);
}
Void::Result::Result<Digest> sha1(std::string_view data)
{
return hash(HashAlgorithm::Sha1, data);
}
Void::Result::Result<Digest> sha256(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Sha256, data);
}
Void::Result::Result<Digest> sha256(std::string_view data)
{
return hash(HashAlgorithm::Sha256, data);
}
Void::Result::Result<Digest> sha512(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Sha512, data);
}
Void::Result::Result<Digest> sha512(std::string_view data)
{
return hash(HashAlgorithm::Sha512, data);
}
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
{
return hashFile(HashAlgorithm::Sha1, path);
}
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
{
return hashFile(HashAlgorithm::Sha256, path);
}
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
{
return hashFile(HashAlgorithm::Sha512, path);
}
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte>
signature,
std::span<const std::byte>
publicKey)
{
if (signature.size() != Ed25519SignatureSize) {
return Void::Result::fail(
std::format("Crypto::verifyEd25519: signature must be {} bytes",
Ed25519SignatureSize));
}
if (publicKey.size() != Ed25519PublicKeySize) {
return Void::Result::fail(std::format(
"Crypto::verifyEd25519: public key must be {} bytes",
Ed25519PublicKeySize));
}
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
Key key{EVP_PKEY_new_raw_public_key(
EVP_PKEY_ED25519, nullptr,
reinterpret_cast<const unsigned char*>(publicKey.data()),
publicKey.size()),
&EVP_PKEY_free};
if (!key) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: invalid public key"));
}
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: EVP_MD_CTX_new failed"));
}
if (EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr,
key.get()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: initialization failed"));
}
const int result = EVP_DigestVerify(
context.get(),
reinterpret_cast<const unsigned char*>(signature.data()),
signature.size(),
reinterpret_cast<const unsigned char*>(message.data()),
message.size());
if (result < 0) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519 failed"));
}
return result == 1;
}
} // namespace Void::Crypto
+4
View File
@@ -0,0 +1,4 @@
void_add_module(Crypto
INTERNAL_DEPS Functional
EXTERNAL_DEPS OpenSSL::Crypto
)
+690
View File
@@ -0,0 +1,690 @@
#include <Void/Net/Server.hpp>
#include <algorithm>
#include <cctype>
#include <set>
#include <system_error>
namespace Void::Net
{
namespace
{
[[nodiscard]] bool
equal_ascii_case_insensitive(std::string_view left,
std::string_view right) noexcept
{
return left.size() == right.size() &&
std::ranges::equal(left, right, [](char lhs, char rhs) {
return std::tolower(static_cast<unsigned char>(lhs)) ==
std::tolower(static_cast<unsigned char>(rhs));
});
}
[[nodiscard]] std::optional<std::string_view>
find_header(const std::vector<Header>& headers,
std::string_view name) noexcept
{
for (const auto& header : headers) {
if (equal_ascii_case_insensitive(header.name, name)) {
return header.value;
}
}
return std::nullopt;
}
[[nodiscard]] std::string_view path_only(std::string_view path) noexcept
{
const auto end = path.find_first_of("?#");
return path.substr(0, end);
}
[[nodiscard]] std::vector<std::string> split_path(std::string_view path)
{
std::vector<std::string> segments;
std::size_t begin = path.starts_with('/') ? 1 : 0;
while (begin < path.size()) {
const auto end = path.find('/', begin);
const auto segment = path.substr(begin, end - begin);
if (!segment.empty()) {
segments.emplace_back(segment);
}
if (end == std::string_view::npos) {
break;
}
begin = end + 1;
}
return segments;
}
[[nodiscard]] bool valid_parameter_name(std::string_view name) noexcept
{
return !name.empty() && std::ranges::all_of(name, [](char value) {
const auto c = static_cast<unsigned char>(value);
return std::isalnum(c) != 0 || value == '_';
});
}
[[nodiscard]] Void::Result::Result<std::vector<std::string>>
compile_pattern(std::string_view pattern)
{
if (pattern.empty() || !pattern.starts_with('/') ||
pattern.find_first_of("?#") != std::string_view::npos) {
return Void::Result::fail(
"Net::Router: route patterns must be absolute URL paths");
}
auto segments = split_path(pattern);
std::set<std::string, std::less<>> names;
for (std::size_t index = 0; index < segments.size(); ++index) {
const auto& segment = segments[index];
if (!segment.starts_with(':') && !segment.starts_with('*')) {
continue;
}
const auto name = std::string_view{segment}.substr(1);
if (!valid_parameter_name(name)) {
return Void::Result::fail(
"Net::Router: invalid route parameter name");
}
if (!names.emplace(name).second) {
return Void::Result::fail(
"Net::Router: duplicate route parameter name");
}
if (segment.starts_with('*') && index + 1 != segments.size()) {
return Void::Result::fail(
"Net::Router: catch-all parameter must be final");
}
}
return segments;
}
[[nodiscard]] std::optional<RouteParameters>
match_route(const std::vector<std::string>& pattern,
const std::vector<std::string>& path)
{
RouteParameters parameters;
std::size_t path_index = 0;
for (const auto& segment : pattern) {
if (segment.starts_with('*')) {
std::string value;
for (; path_index < path.size(); ++path_index) {
if (!value.empty()) {
value += '/';
}
value += path[path_index];
}
parameters.emplace(segment.substr(1), std::move(value));
return parameters;
}
if (path_index >= path.size()) {
return std::nullopt;
}
if (segment.starts_with(':')) {
parameters.emplace(segment.substr(1), path[path_index]);
} else if (segment != path[path_index]) {
return std::nullopt;
}
++path_index;
}
if (path_index != path.size()) {
return std::nullopt;
}
return parameters;
}
[[nodiscard]] int segment_specificity(std::string_view segment) noexcept
{
if (segment.starts_with('*')) {
return 0;
}
if (segment.starts_with(':')) {
return 1;
}
return 2;
}
[[nodiscard]] bool
more_specific(const std::vector<std::string>& candidate,
const std::vector<std::string>& current) noexcept
{
const auto shared = std::min(candidate.size(), current.size());
for (std::size_t index = 0; index < shared; ++index) {
const auto candidate_rank =
segment_specificity(candidate[index]);
const auto current_rank = segment_specificity(current[index]);
if (candidate_rank != current_rank) {
return candidate_rank > current_rank;
}
}
return candidate.size() > current.size();
}
[[nodiscard]] bool
same_route_shape(const std::vector<std::string>& left,
const std::vector<std::string>& right) noexcept
{
if (left.size() != right.size()) {
return false;
}
for (std::size_t index = 0; index < left.size(); ++index) {
const auto left_rank = segment_specificity(left[index]);
const auto right_rank = segment_specificity(right[index]);
if (left_rank != right_rank ||
(left_rank == 2 && left[index] != right[index])) {
return false;
}
}
return true;
}
[[nodiscard]] int hex_value(char value) noexcept
{
if (value >= '0' && value <= '9') {
return value - '0';
}
if (value >= 'a' && value <= 'f') {
return value - 'a' + 10;
}
if (value >= 'A' && value <= 'F') {
return value - 'A' + 10;
}
return -1;
}
[[nodiscard]] Void::Result::Result<std::string>
decode_url_path(std::string_view request_path)
{
const auto path = path_only(request_path);
if (path.empty() || !path.starts_with('/')) {
return Void::Result::fail(
"Net::StaticFileResolver: request path must be absolute");
}
std::string decoded;
decoded.reserve(path.size());
for (std::size_t index = 0; index < path.size(); ++index) {
unsigned char value = static_cast<unsigned char>(path[index]);
if (value == '%') {
if (index + 2 >= path.size()) {
return Void::Result::fail("Net::StaticFileResolver: "
"invalid percent encoding");
}
const auto high = hex_value(path[index + 1]);
const auto low = hex_value(path[index + 2]);
if (high < 0 || low < 0) {
return Void::Result::fail("Net::StaticFileResolver: "
"invalid percent encoding");
}
value = static_cast<unsigned char>((high << 4) | low);
index += 2;
}
if (value < 0x20 || value == 0x7f || value == '\\') {
return Void::Result::fail(
"Net::StaticFileResolver: unsafe path character");
}
decoded += static_cast<char>(value);
}
return decoded;
}
[[nodiscard]] bool
path_is_within(const std::filesystem::path& root,
const std::filesystem::path& candidate) noexcept
{
auto root_part = root.begin();
auto candidate_part = candidate.begin();
for (; root_part != root.end(); ++root_part, ++candidate_part) {
if (candidate_part == candidate.end() ||
*root_part != *candidate_part) {
return false;
}
}
return true;
}
[[nodiscard]] std::string
lowercase_extension(const std::filesystem::path& path)
{
auto extension = path.extension().string();
std::ranges::transform(
extension, extension.begin(), [](char value) {
return static_cast<char>(
std::tolower(static_cast<unsigned char>(value)));
});
return extension;
}
} // namespace
std::optional<std::string_view>
ServerRequest::header(std::string_view name) const noexcept
{
return find_header(headers, name);
}
std::optional<std::string_view>
ServerResponse::header(std::string_view name) const noexcept
{
return find_header(headers, name);
}
Void::Result::Result<void> Router::add(Method method, std::string pattern,
RouteHandler handler)
{
if (!handler) {
return Void::Result::fail("Net::Router: route handler is empty");
}
auto segments = compile_pattern(pattern);
if (!segments) {
return Void::Result::fail(std::move(segments).error());
}
std::unique_lock lock{mutex_};
const auto duplicate =
std::ranges::find_if(routes_, [&](const Route& route) {
return route.method == method &&
same_route_shape(route.segments, *segments);
});
if (duplicate != routes_.end()) {
return Void::Result::fail("Net::Router: duplicate route");
}
routes_.push_back(Route{method, std::move(pattern),
std::move(*segments), std::move(handler)});
return {};
}
Void::Result::Result<std::optional<ServerResponse>>
Router::dispatch(ServerRequest request) const
{
if (request.path.empty() || !request.path.starts_with('/')) {
return Void::Result::fail(
"Net::Router: request path must be absolute");
}
const auto path = split_path(path_only(request.path));
RouteHandler handler;
RouteParameters parameters;
{
std::shared_lock lock{mutex_};
const Route* best_route = nullptr;
for (const auto& route : routes_) {
if (route.method != request.method) {
continue;
}
auto matched = match_route(route.segments, path);
if (!matched) {
continue;
}
if (best_route == nullptr ||
more_specific(route.segments, best_route->segments)) {
best_route = &route;
parameters = std::move(*matched);
}
}
if (best_route != nullptr) {
handler = best_route->handler;
}
}
if (!handler) {
return std::optional<ServerResponse>{};
}
request.parameters = std::move(parameters);
auto response = handler(request);
if (!response) {
return Void::Result::fail(std::move(response).error());
}
return std::optional<ServerResponse>{std::move(*response)};
}
std::size_t Router::size() const
{
std::shared_lock lock{mutex_};
return routes_.size();
}
std::string_view content_type_for(const std::filesystem::path& path)
{
const auto extension = lowercase_extension(path);
if (extension == ".html" || extension == ".htm") {
return "text/html; charset=utf-8";
}
if (extension == ".css") {
return "text/css; charset=utf-8";
}
if (extension == ".js" || extension == ".mjs") {
return "text/javascript; charset=utf-8";
}
if (extension == ".json" || extension == ".map") {
return "application/json; charset=utf-8";
}
if (extension == ".txt") {
return "text/plain; charset=utf-8";
}
if (extension == ".xml") {
return "application/xml; charset=utf-8";
}
if (extension == ".svg") {
return "image/svg+xml";
}
if (extension == ".png") {
return "image/png";
}
if (extension == ".jpg" || extension == ".jpeg") {
return "image/jpeg";
}
if (extension == ".gif") {
return "image/gif";
}
if (extension == ".webp") {
return "image/webp";
}
if (extension == ".ico") {
return "image/x-icon";
}
if (extension == ".wasm") {
return "application/wasm";
}
if (extension == ".woff") {
return "font/woff";
}
if (extension == ".woff2") {
return "font/woff2";
}
if (extension == ".ttf") {
return "font/ttf";
}
if (extension == ".mp3") {
return "audio/mpeg";
}
if (extension == ".ogg") {
return "audio/ogg";
}
if (extension == ".mp4") {
return "video/mp4";
}
if (extension == ".webm") {
return "video/webm";
}
return "application/octet-stream";
}
Void::Result::Result<StaticFileResolver>
StaticFileResolver::create(std::filesystem::path root,
std::string index_file)
{
if (index_file.empty() ||
std::filesystem::path{index_file}.filename() != index_file ||
index_file == "." || index_file == "..") {
return Void::Result::fail(
"Net::StaticFileResolver: index file must be one filename");
}
std::error_code error;
auto canonical_root = std::filesystem::weakly_canonical(root, error);
if (error || !std::filesystem::is_directory(canonical_root, error) ||
error) {
return Void::Result::fail(
"Net::StaticFileResolver: document root is not a directory");
}
return StaticFileResolver{std::move(canonical_root),
std::move(index_file)};
}
Void::Result::Result<std::optional<StaticFile>>
StaticFileResolver::resolve(std::string_view request_path) const
{
auto decoded = decode_url_path(request_path);
if (!decoded) {
return Void::Result::fail(std::move(decoded).error());
}
auto candidate = root_;
for (const auto& segment : split_path(*decoded)) {
if (segment == "." || segment == "..") {
return Void::Result::fail(
"Net::StaticFileResolver: path traversal rejected");
}
candidate /= segment;
}
std::error_code error;
candidate = std::filesystem::weakly_canonical(candidate, error);
if (error) {
return Void::Result::fail(
"Net::StaticFileResolver: path canonicalization failed");
}
if (!path_is_within(root_, candidate)) {
return Void::Result::fail(
"Net::StaticFileResolver: path escapes document root");
}
if (!std::filesystem::exists(candidate, error)) {
if (error) {
return Void::Result::fail(
"Net::StaticFileResolver: file status failed");
}
return std::optional<StaticFile>{};
}
if (std::filesystem::is_directory(candidate, error)) {
candidate = std::filesystem::weakly_canonical(
candidate / index_file_, error);
if (error || !path_is_within(root_, candidate)) {
return Void::Result::fail(
"Net::StaticFileResolver: unsafe index path");
}
}
if (!std::filesystem::is_regular_file(candidate, error)) {
if (error) {
return Void::Result::fail(
"Net::StaticFileResolver: file status failed");
}
return std::optional<StaticFile>{};
}
const auto size = std::filesystem::file_size(candidate, error);
if (error) {
return Void::Result::fail(
"Net::StaticFileResolver: file size failed");
}
const auto content_type = content_type_for(candidate);
return std::optional<StaticFile>{
StaticFile{std::move(candidate), content_type, size}};
}
WebSocketSessions::~WebSocketSessions() noexcept
{
try {
auto connections = take_all(true);
const WebSocketClose close{1001, "server shutdown"};
for (const auto& [id, connection] : connections) {
(void)id;
connection->close(close);
}
} catch (...) {
}
}
void WebSocketSessions::set_events(WebSocketEvents events)
{
std::lock_guard lock{mutex_};
events_ = std::move(events);
}
Void::Result::Result<bool>
WebSocketSessions::open(std::shared_ptr<WebSocketConnection> connection)
{
if (!connection) {
return Void::Result::fail(
"Net::WebSocketSessions: connection is null");
}
std::function<void(const std::shared_ptr<WebSocketConnection>&)> opened;
{
std::lock_guard lock{mutex_};
if (!accepting_) {
return false;
}
if (!connections_.emplace(connection->id(), connection).second) {
return false;
}
opened = events_.opened;
}
if (opened) {
opened(connection);
}
return true;
}
std::shared_ptr<WebSocketConnection>
WebSocketSessions::find(WebSocketConnectionId id) const
{
std::lock_guard lock{mutex_};
const auto found = connections_.find(id);
return found == connections_.end() ? nullptr : found->second;
}
bool WebSocketSessions::contains(WebSocketConnectionId id) const
{
std::lock_guard lock{mutex_};
return connections_.contains(id);
}
std::size_t WebSocketSessions::size() const
{
std::lock_guard lock{mutex_};
return connections_.size();
}
bool WebSocketSessions::receive_text(WebSocketConnectionId id,
std::string_view message) const
{
std::shared_ptr<WebSocketConnection> connection;
std::function<void(const std::shared_ptr<WebSocketConnection>&,
std::string_view)>
callback;
{
std::lock_guard lock{mutex_};
const auto found = connections_.find(id);
if (found == connections_.end()) {
return false;
}
connection = found->second;
callback = events_.text;
}
if (callback) {
callback(connection, message);
}
return true;
}
bool WebSocketSessions::receive_binary(
WebSocketConnectionId id, std::span<const std::byte> message) const
{
std::shared_ptr<WebSocketConnection> connection;
std::function<void(const std::shared_ptr<WebSocketConnection>&,
std::span<const std::byte>)>
callback;
{
std::lock_guard lock{mutex_};
const auto found = connections_.find(id);
if (found == connections_.end()) {
return false;
}
connection = found->second;
callback = events_.binary;
}
if (callback) {
callback(connection, message);
}
return true;
}
bool WebSocketSessions::fail(WebSocketConnectionId id,
const Void::Result::Error& error) const
{
std::function<void(WebSocketConnectionId, const Void::Result::Error&)>
callback;
{
std::lock_guard lock{mutex_};
if (!connections_.contains(id)) {
return false;
}
callback = events_.error;
}
if (callback) {
callback(id, error);
}
return true;
}
bool WebSocketSessions::disconnect(WebSocketConnectionId id,
WebSocketClose close)
{
return remove(id, close, false);
}
bool WebSocketSessions::close(WebSocketConnectionId id,
WebSocketClose close)
{
return remove(id, close, true);
}
std::size_t WebSocketSessions::shutdown(WebSocketClose close)
{
auto connections = take_all(true);
std::function<void(WebSocketConnectionId, const WebSocketClose&)>
closed;
{
std::lock_guard lock{mutex_};
closed = events_.closed;
}
for (const auto& [id, connection] : connections) {
(void)id;
connection->close(close);
}
if (closed) {
for (const auto& [id, connection] : connections) {
(void)connection;
closed(id, close);
}
}
return connections.size();
}
bool WebSocketSessions::remove(WebSocketConnectionId id,
const WebSocketClose& close,
bool close_transport)
{
std::shared_ptr<WebSocketConnection> connection;
std::function<void(WebSocketConnectionId, const WebSocketClose&)>
closed;
{
std::lock_guard lock{mutex_};
const auto found = connections_.find(id);
if (found == connections_.end()) {
return false;
}
connection = std::move(found->second);
connections_.erase(found);
closed = events_.closed;
}
if (close_transport) {
connection->close(close);
}
if (closed) {
closed(id, close);
}
return true;
}
WebSocketSessions::Connections
WebSocketSessions::take_all(bool stop_accepting)
{
std::lock_guard lock{mutex_};
if (stop_accepting) {
accepting_ = false;
}
Connections connections;
connections.swap(connections_);
return connections;
}
} // namespace Void::Net
+2
View File
@@ -2,6 +2,8 @@ void_add_module(Net
INTERNAL_DEPS Functional Text
EXTERNAL_DEPS
Boost::headers
Boost::beast
Boost::asio
Boost::url
OpenSSL::SSL
OpenSSL::Crypto
+247 -220
View File
@@ -1,9 +1,9 @@
#include <Void/Log/Log.hpp>
#include <Void/Plugin/Loader.hpp>
#include <Void/Log/Log.hpp>
#if defined(__unix__) || defined(__APPLE__)
# include <dlfcn.h>
# define VOID_HAS_DLOPEN 1
#include <dlfcn.h>
#define VOID_HAS_DLOPEN 1
#endif
#include <filesystem>
@@ -13,254 +13,281 @@
namespace Void::Plugin
{
std::string_view to_string(LoadError e) noexcept
{
switch (e) {
case LoadError::FileNotFound: return "file not found";
case LoadError::DlopenFailed: return "dlopen failed";
case LoadError::SymbolMissing: return "required symbol missing";
case LoadError::AbiMismatch: return "ABI version mismatch";
case LoadError::CreateFailed: return "plugin create() returned null";
case LoadError::NotSupported: return "platform does not support dlopen";
case LoadError::StateRejected: return "new instance rejected state";
case LoadError::ActivationFailed: return "plugin activation failed";
case LoadError::UnknownPlugin: return "no plugin registered under name";
}
return "unknown";
}
std::string_view to_string(LoadError e) noexcept
{
switch (e) {
case LoadError::FileNotFound:
return "file not found";
case LoadError::DlopenFailed:
return "dlopen failed";
case LoadError::SymbolMissing:
return "required symbol missing";
case LoadError::AbiMismatch:
return "ABI version mismatch";
case LoadError::CreateFailed:
return "plugin create() returned null";
case LoadError::NotSupported:
return "platform does not support dlopen";
case LoadError::StateRejected:
return "new instance rejected state";
case LoadError::ActivationFailed:
return "plugin activation failed";
case LoadError::UnknownPlugin:
return "no plugin registered under name";
case LoadError::NameMismatch:
return "replacement plugin name mismatch";
}
return "unknown";
}
// ── internal helpers ──────────────────────────────────────────────────────────
// ── internal helpers
// ──────────────────────────────────────────────────────────
void PluginLoader::destroy_current() noexcept
{
void PluginLoader::destroy_current() noexcept
{
#ifdef VOID_HAS_DLOPEN
if (plugin_) {
plugin_->on_unload();
if (destroy_) destroy_(plugin_);
plugin_ = nullptr;
}
if (handle_) {
dlclose(handle_);
handle_ = nullptr;
}
destroy_ = nullptr;
transfer_ = nullptr;
ready_ = nullptr;
state_version_ = nullptr;
serialize_ = nullptr;
free_string_ = nullptr;
deserialize_ = nullptr;
if (plugin_) {
plugin_->on_unload();
if (destroy_) {
destroy_(plugin_);
}
plugin_ = nullptr;
}
if (handle_) {
dlclose(handle_);
handle_ = nullptr;
}
destroy_ = nullptr;
transfer_ = nullptr;
ready_ = nullptr;
state_version_ = nullptr;
serialize_ = nullptr;
free_string_ = nullptr;
deserialize_ = nullptr;
#endif
}
}
// Move plugin state old -> new across a reload. Prefers the v2
// serialize/deserialize protocol (survives layout changes between
// versions); falls back to the raw transfer_state hook; else no-op.
// Returns false only when the new instance actively rejects the state.
bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to)
{
if (!from.plugin_ || !to.plugin_) {
return true;
}
if (from.serialize_ && to.deserialize_) {
const std::uint32_t from_version =
from.state_version_ ? from.state_version_() : 0;
const char* json = from.serialize_(from.plugin_);
if (json != nullptr) {
const int rc = to.deserialize_(to.plugin_, json, from_version);
if (from.free_string_) {
from.free_string_(json);
}
if (rc != 0) {
Void::Log::warn("Plugin",
"deserialize_state rejected state "
"(from v{}, rc={})",
from_version, rc);
return false;
}
Void::Log::debug("Plugin",
"state transferred via v2 protocol (v{})",
from_version);
return true;
}
}
if (to.transfer_) {
to.transfer_(from.plugin_, to.plugin_);
Void::Log::debug("Plugin", "state transferred via transfer_state");
}
return true;
}
// Move plugin state old -> new across a reload. Prefers the v2
// serialize/deserialize protocol (survives layout changes between
// versions); falls back to the raw transfer_state hook; else no-op.
// Returns false only when the new instance actively rejects the state.
bool transfer_plugin_state(const PluginLoader& from, PluginLoader& to)
{
if (!from.plugin_ || !to.plugin_) {
return true;
}
if (from.serialize_ && to.deserialize_) {
const std::uint32_t from_version =
from.state_version_ ? from.state_version_() : 0;
const char* json = from.serialize_(from.plugin_);
if (json != nullptr) {
const int rc = to.deserialize_(to.plugin_, json, from_version);
if (from.free_string_) {
from.free_string_(json);
}
if (rc != 0) {
Void::Log::warn("Plugin",
"deserialize_state rejected state "
"(from v{}, rc={})",
from_version, rc);
return false;
}
Void::Log::debug("Plugin",
"state transferred via v2 protocol (v{})",
from_version);
return true;
}
}
if (to.transfer_) {
to.transfer_(from.plugin_, to.plugin_);
Void::Log::debug("Plugin", "state transferred via transfer_state");
}
return true;
}
std::expected<void, LoadError>
PluginLoader::load_from(const std::filesystem::path& path)
{
std::expected<void, LoadError>
PluginLoader::load_from(const std::filesystem::path& path)
{
#ifdef VOID_HAS_DLOPEN
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
if (!h) return std::unexpected{LoadError::DlopenFailed};
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
if (!h) {
return std::unexpected{LoadError::DlopenFailed};
}
const auto sym_info = reinterpret_cast<info_fn> (dlsym(h, kInfoSymbol));
const auto sym_create = reinterpret_cast<create_fn> (dlsym(h, kCreateSymbol));
const auto sym_destroy = reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
const auto sym_info = reinterpret_cast<info_fn>(dlsym(h, kInfoSymbol));
const auto sym_create =
reinterpret_cast<create_fn>(dlsym(h, kCreateSymbol));
const auto sym_destroy =
reinterpret_cast<destroy_fn>(dlsym(h, kDestroySymbol));
if (!sym_info || !sym_create || !sym_destroy) {
dlclose(h);
return std::unexpected{LoadError::SymbolMissing};
}
if (!sym_info || !sym_create || !sym_destroy) {
dlclose(h);
return std::unexpected{LoadError::SymbolMissing};
}
const PluginInfo info = sym_info();
if (info.abi_version != ABI_VERSION) {
dlclose(h);
return std::unexpected{LoadError::AbiMismatch};
}
const PluginInfo info = sym_info();
if (info.abi_version != ABI_VERSION) {
dlclose(h);
return std::unexpected{LoadError::AbiMismatch};
}
void* raw = sym_create();
if (!raw) {
dlclose(h);
return std::unexpected{LoadError::CreateFailed};
}
void* raw = sym_create();
if (!raw) {
dlclose(h);
return std::unexpected{LoadError::CreateFailed};
}
handle_ = h;
plugin_ = static_cast<IPlugin*>(raw);
destroy_ = sym_destroy;
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
ready_ = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
state_version_ = reinterpret_cast<state_version_fn>(
dlsym(h, kStateVersionSymbol));
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
free_string_ = reinterpret_cast<free_string_fn>(
dlsym(h, kFreeStringSymbol));
deserialize_ = reinterpret_cast<deserialize_fn>(
dlsym(h, kDeserializeSymbol));
info_ = info;
return {};
handle_ = h;
plugin_ = static_cast<IPlugin*>(raw);
destroy_ = sym_destroy;
transfer_ = reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
ready_ = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
state_version_ =
reinterpret_cast<state_version_fn>(dlsym(h, kStateVersionSymbol));
serialize_ = reinterpret_cast<serialize_fn>(dlsym(h, kSerializeSymbol));
free_string_ =
reinterpret_cast<free_string_fn>(dlsym(h, kFreeStringSymbol));
deserialize_ =
reinterpret_cast<deserialize_fn>(dlsym(h, kDeserializeSymbol));
info_ = info;
return {};
#else
(void)path;
return std::unexpected{LoadError::NotSupported};
(void)path;
return std::unexpected{LoadError::NotSupported};
#endif
}
}
// ── public API ────────────────────────────────────────────────────────────────
// ── public API
// ────────────────────────────────────────────────────────────────
std::expected<PluginLoader, LoadError>
PluginLoader::load(std::filesystem::path path)
{
if (!std::filesystem::exists(path))
return std::unexpected{LoadError::FileNotFound};
std::expected<PluginLoader, LoadError>
PluginLoader::load(std::filesystem::path path)
{
if (!std::filesystem::exists(path)) {
return std::unexpected{LoadError::FileNotFound};
}
PluginLoader ldr;
ldr.path_ = path;
PluginLoader ldr;
ldr.path_ = path;
if (auto r = ldr.load_from(path); !r) {
Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(),
to_string(r.error()));
return std::unexpected{r.error()};
}
if (auto r = ldr.load_from(path); !r) {
Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(),
to_string(r.error()));
return std::unexpected{r.error()};
}
try {
ldr.plugin_->on_load();
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) {
return std::unexpected{LoadError::ActivationFailed};
}
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
ldr.info_.name, ldr.info_.plugin_version);
return ldr;
}
try {
ldr.plugin_->on_load();
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if (ldr.ready_ && ldr.ready_(ldr.plugin_) != 0) {
return std::unexpected{LoadError::ActivationFailed};
}
Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(),
ldr.info_.name, ldr.info_.plugin_version);
return ldr;
}
PluginLoader::~PluginLoader() { destroy_current(); }
PluginLoader::~PluginLoader() { destroy_current(); }
PluginLoader::PluginLoader(PluginLoader&& o) noexcept
: handle_ {std::exchange(o.handle_, nullptr)}
, plugin_ {std::exchange(o.plugin_, nullptr)}
, destroy_ {std::exchange(o.destroy_, nullptr)}
, transfer_ {std::exchange(o.transfer_, nullptr)}
, ready_ {std::exchange(o.ready_, nullptr)}
, state_version_{std::exchange(o.state_version_, nullptr)}
, serialize_ {std::exchange(o.serialize_, nullptr)}
, free_string_ {std::exchange(o.free_string_, nullptr)}
, deserialize_ {std::exchange(o.deserialize_, nullptr)}
, info_ {o.info_}
, path_ {std::move(o.path_)}
{}
PluginLoader::PluginLoader(PluginLoader&& o) noexcept
: handle_{std::exchange(o.handle_, nullptr)},
plugin_{std::exchange(o.plugin_, nullptr)},
destroy_{std::exchange(o.destroy_, nullptr)},
transfer_{std::exchange(o.transfer_, nullptr)},
ready_{std::exchange(o.ready_, nullptr)},
state_version_{std::exchange(o.state_version_, nullptr)},
serialize_{std::exchange(o.serialize_, nullptr)},
free_string_{std::exchange(o.free_string_, nullptr)},
deserialize_{std::exchange(o.deserialize_, nullptr)}, info_{o.info_},
path_{std::move(o.path_)}
{
}
PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
{
if (this != &o) {
destroy_current();
handle_ = std::exchange(o.handle_, nullptr);
plugin_ = std::exchange(o.plugin_, nullptr);
destroy_ = std::exchange(o.destroy_, nullptr);
transfer_ = std::exchange(o.transfer_, nullptr);
ready_ = std::exchange(o.ready_, nullptr);
state_version_ = std::exchange(o.state_version_, nullptr);
serialize_ = std::exchange(o.serialize_, nullptr);
free_string_ = std::exchange(o.free_string_, nullptr);
deserialize_ = std::exchange(o.deserialize_, nullptr);
info_ = o.info_;
path_ = std::move(o.path_);
}
return *this;
}
PluginLoader& PluginLoader::operator=(PluginLoader&& o) noexcept
{
if (this != &o) {
destroy_current();
handle_ = std::exchange(o.handle_, nullptr);
plugin_ = std::exchange(o.plugin_, nullptr);
destroy_ = std::exchange(o.destroy_, nullptr);
transfer_ = std::exchange(o.transfer_, nullptr);
ready_ = std::exchange(o.ready_, nullptr);
state_version_ = std::exchange(o.state_version_, nullptr);
serialize_ = std::exchange(o.serialize_, nullptr);
free_string_ = std::exchange(o.free_string_, nullptr);
deserialize_ = std::exchange(o.deserialize_, nullptr);
info_ = o.info_;
path_ = std::move(o.path_);
}
return *this;
}
std::expected<void, LoadError> PluginLoader::reload()
{
std::expected<void, LoadError> PluginLoader::reload()
{
#ifdef VOID_HAS_DLOPEN
// Copy to a unique temp path so dlopen gets a fresh inode (bypasses the
// path-based cache) even if the file was replaced in-place.
const auto tmp = path_.parent_path()
/ (path_.filename().string() + ".void_hotswap");
// Copy to a unique temp path so dlopen gets a fresh inode (bypasses the
// path-based cache) even if the file was replaced in-place.
const auto tmp =
path_.parent_path() / (path_.filename().string() + ".void_hotswap");
{
std::error_code ec;
std::filesystem::copy_file(path_, tmp,
std::filesystem::copy_options::overwrite_existing, ec);
if (ec) return std::unexpected{LoadError::FileNotFound};
}
{
std::error_code ec;
std::filesystem::copy_file(
path_, tmp, std::filesystem::copy_options::overwrite_existing,
ec);
if (ec) {
return std::unexpected{LoadError::FileNotFound};
}
}
// Load new instance while old is still alive (for state transfer).
PluginLoader next;
next.path_ = path_;
if (auto r = next.load_from(tmp); !r) {
std::error_code ec;
std::filesystem::remove(tmp, ec);
Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old",
path_.string(), to_string(r.error()));
return r;
}
// Load new instance while old is still alive (for state transfer).
PluginLoader next;
next.path_ = path_;
if (auto r = next.load_from(tmp); !r) {
std::error_code ec;
std::filesystem::remove(tmp, ec);
Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old",
path_.string(), to_string(r.error()));
return r;
}
// Transfer state with both instances alive. A rejection aborts the
// reload and keeps the old instance.
if (!transfer_plugin_state(*this, next)) {
std::error_code ec;
std::filesystem::remove(tmp, ec);
Void::Log::warn("Plugin", "reload '{}' aborted: state rejected",
path_.string());
return std::unexpected{LoadError::StateRejected};
}
// Transfer state with both instances alive. A rejection aborts the
// reload and keeps the old instance.
if (!transfer_plugin_state(*this, next)) {
std::error_code ec;
std::filesystem::remove(tmp, ec);
Void::Log::warn("Plugin", "reload '{}' aborted: state rejected",
path_.string());
return std::unexpected{LoadError::StateRejected};
}
try {
next.plugin_->on_load();
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if (next.ready_ && next.ready_(next.plugin_) != 0) {
return std::unexpected{LoadError::ActivationFailed};
}
try {
next.plugin_->on_load();
} catch (...) {
std::error_code ec;
std::filesystem::remove(tmp, ec);
return std::unexpected{LoadError::ActivationFailed};
}
if (next.ready_ && next.ready_(next.plugin_) != 0) {
std::error_code ec;
std::filesystem::remove(tmp, ec);
return std::unexpected{LoadError::ActivationFailed};
}
// Activation succeeded; only now destroy old and install new.
destroy_current();
*this = std::move(next);
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
info_.name, info_.plugin_version);
// Activation succeeded; only now destroy old and install new.
destroy_current();
*this = std::move(next);
Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(),
info_.name, info_.plugin_version);
std::error_code ec;
std::filesystem::remove(tmp, ec);
return {};
std::error_code ec;
std::filesystem::remove(tmp, ec);
return {};
#else
return std::unexpected{LoadError::NotSupported};
return std::unexpected{LoadError::NotSupported};
#endif
}
}
} // namespace Void::Plugin
+113 -51
View File
@@ -78,6 +78,19 @@ namespace Void::Plugin
return m_pin->info;
}
void* PluginHandle::raw_symbol(const char* symbol) const noexcept
{
#ifdef VOID_HAS_DLOPEN
if (!m_pin || m_pin->handle == nullptr || symbol == nullptr) {
return nullptr;
}
return dlsym(m_pin->handle, symbol);
#else
(void)symbol;
return nullptr;
#endif
}
// ── loading helpers ───────────────────────────────────────────────────
namespace
@@ -122,8 +135,7 @@ namespace Void::Plugin
reinterpret_cast<transfer_fn>(dlsym(h, kTransferSymbol));
inst->configure =
reinterpret_cast<configure_fn>(dlsym(h, kConfigureSymbol));
inst->ready =
reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
inst->ready = reinterpret_cast<ready_fn>(dlsym(h, kReadySymbol));
inst->state_version = reinterpret_cast<state_version_fn>(
dlsym(h, kStateVersionSymbol));
inst->serialize =
@@ -183,10 +195,10 @@ namespace Void::Plugin
hotswap_copy(const std::filesystem::path& path)
{
static std::atomic<std::uint64_t> counter{0};
const auto tmp =
path.parent_path() /
(path.filename().string() + ".void_hotswap." +
std::to_string(counter.fetch_add(1, std::memory_order_relaxed)));
const auto tmp = path.parent_path() /
(path.filename().string() + ".void_hotswap." +
std::to_string(counter.fetch_add(
1, std::memory_order_relaxed)));
std::error_code ec;
std::filesystem::copy_file(
path, tmp, std::filesystem::copy_options::overwrite_existing,
@@ -242,6 +254,13 @@ namespace Void::Plugin
return std::unexpected{inst.error()};
}
std::string name{(*inst)->plugin->name()};
if (m_options.candidate_validator &&
!m_options.candidate_validator(PluginHandle{*inst})) {
Void::Log::warn("Plugin.Manager",
"load '{}' aborted: binary validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.config_provider && (*inst)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
(*inst)->configure((*inst)->plugin, config.c_str());
@@ -251,8 +270,11 @@ namespace Void::Plugin
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if ((*inst)->ready != nullptr &&
(*inst)->ready((*inst)->plugin) != 0) {
if ((*inst)->ready != nullptr && (*inst)->ready((*inst)->plugin) != 0) {
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.instance_validator &&
!m_options.instance_validator(*(*inst)->plugin, (*inst)->info)) {
return std::unexpected{LoadError::ActivationFailed};
}
@@ -334,7 +356,7 @@ namespace Void::Plugin
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
}
auto result = reload_locked(*entry, name);
auto result = reload_locked(*entry, name, entry->path);
if (!result.has_value()) {
return result;
}
@@ -347,14 +369,51 @@ namespace Void::Plugin
}
std::expected<void, LoadError>
PluginManager::reload_locked(Entry& entry, std::string_view name)
PluginManager::replace(std::string_view name,
const std::filesystem::path& newPath)
{
std::vector<std::function<void(std::string_view)>> callbacks;
bool restartWatcher = false;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
}
std::error_code error;
if (!std::filesystem::is_regular_file(newPath, error)) {
return std::unexpected{LoadError::FileNotFound};
}
auto result = reload_locked(*entry, name, newPath);
if (!result) {
return result;
}
restartWatcher = entry->watched;
if (restartWatcher) {
m_watcher.unwatch(entry->path);
}
entry->path = newPath;
callbacks = reload_callbacks_locked();
}
if (restartWatcher) {
watch(name);
}
for (const auto& callback : callbacks) {
callback(name);
}
return {};
}
std::expected<void, LoadError>
PluginManager::reload_locked(Entry& entry, std::string_view name,
const std::filesystem::path& sourcePath)
{
// Copy to a fresh inode so dlopen loads the new bytes instead of
// returning the still-open handle for this path. The caller must
// have installed the new file via atomic rename (a fresh inode of
// its own) — overwriting the mapped file in place corrupts the
// running instance's mapping (SIGBUS).
auto tmp = hotswap_copy(entry.path);
auto tmp = hotswap_copy(sourcePath);
if (!tmp.has_value()) {
return std::unexpected{tmp.error()};
}
@@ -367,6 +426,19 @@ namespace Void::Plugin
to_string(next.error()));
return std::unexpected{next.error()};
}
if ((*next)->plugin->name() != name) {
Void::Log::warn("Plugin.Manager",
"replace '{}' rejected: candidate reports '{}'",
name, (*next)->plugin->name());
return std::unexpected{LoadError::NameMismatch};
}
if (m_options.candidate_validator &&
!m_options.candidate_validator(PluginHandle{*next})) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: binary validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.config_provider && (*next)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
@@ -388,10 +460,16 @@ namespace Void::Plugin
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if ((*next)->ready != nullptr &&
(*next)->ready((*next)->plugin) != 0) {
if ((*next)->ready != nullptr && (*next)->ready((*next)->plugin) != 0) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: activation failed", name);
"reload '{}' aborted: activation failed", name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.instance_validator &&
!m_options.instance_validator(*(*next)->plugin, (*next)->info)) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: host validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
// Atomic swap. The old instance keeps living while any acquired
@@ -411,29 +489,30 @@ namespace Void::Plugin
return;
}
path = entry->path;
entry->watched = true;
}
const std::string name_str{name};
m_watcher.watch(
path, [this, name_str](const FileSystem::FileWatcher::Event& e) {
if (!e.exists) {
m_watcher.watch(path, [this, name_str](
const FileSystem::FileWatcher::Event& e) {
if (!e.exists) {
return;
}
std::vector<std::function<void(std::string_view)>> callbacks;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name_str);
if (entry == nullptr) {
return;
}
std::vector<std::function<void(std::string_view)>> callbacks;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name_str);
if (entry == nullptr) {
return;
}
if (!reload_locked(*entry, name_str).has_value()) {
return;
}
callbacks = reload_callbacks_locked();
if (!reload_locked(*entry, name_str, entry->path).has_value()) {
return;
}
for (const auto& cb : callbacks) {
cb(name_str);
}
});
callbacks = reload_callbacks_locked();
}
for (const auto& cb : callbacks) {
cb(name_str);
}
});
}
void PluginManager::unwatch(std::string_view name)
@@ -442,6 +521,7 @@ namespace Void::Plugin
auto* entry = find(name);
if (entry != nullptr) {
m_watcher.unwatch(entry->path);
entry->watched = false;
}
}
@@ -536,25 +616,7 @@ namespace Void::Plugin
void* PluginManager::raw_symbol(std::string_view name,
const char* symbol) const
{
#ifdef VOID_HAS_DLOPEN
std::shared_ptr<detail::Instance> inst;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return nullptr;
}
inst = entry->current.load(std::memory_order_acquire);
}
if (!inst || inst->handle == nullptr) {
return nullptr;
}
return dlsym(inst->handle, symbol);
#else
(void)name;
(void)symbol;
return nullptr;
#endif
return acquire(name).raw_symbol(symbol);
}
} // namespace Void::Plugin
+250
View File
@@ -0,0 +1,250 @@
#include <Void/Security/Security.hpp>
#include <sodium.h>
#include <array>
#include <cstring>
#include <limits>
#include <optional>
#include <vector>
namespace Void::Security
{
namespace
{
struct PasswordLimits {
unsigned long long operations;
std::size_t memory;
};
[[nodiscard]] Void::Result::Result<void> ensure_sodium()
{
static const bool initialized = sodium_init() >= 0;
if (!initialized) {
return Void::Result::fail(
"Security: libsodium initialization failed");
}
return {};
}
[[nodiscard]] std::optional<PasswordLimits>
password_limits(PasswordHashStrength strength) noexcept
{
switch (strength) {
case PasswordHashStrength::Interactive:
return PasswordLimits{crypto_pwhash_OPSLIMIT_INTERACTIVE,
crypto_pwhash_MEMLIMIT_INTERACTIVE};
case PasswordHashStrength::Moderate:
return PasswordLimits{crypto_pwhash_OPSLIMIT_MODERATE,
crypto_pwhash_MEMLIMIT_MODERATE};
case PasswordHashStrength::Sensitive:
return PasswordLimits{crypto_pwhash_OPSLIMIT_SENSITIVE,
crypto_pwhash_MEMLIMIT_SENSITIVE};
}
return std::nullopt;
}
[[nodiscard]] std::array<unsigned char, crypto_generichash_BYTES>
token_digest(std::string_view token) noexcept
{
std::array<unsigned char, crypto_generichash_BYTES> digest{};
(void)crypto_generichash(
digest.data(), digest.size(),
reinterpret_cast<const unsigned char*>(token.data()),
token.size(), nullptr, 0);
return digest;
}
} // namespace
Void::Result::Result<std::string> random_token(std::size_t entropy_bytes)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
if (entropy_bytes == 0) {
return Void::Result::fail(
"Security::random_token: entropy must be greater than zero");
}
if (entropy_bytes >
(std::numeric_limits<std::size_t>::max() - 2) / 4 * 3) {
return Void::Result::fail(
"Security::random_token: entropy size is too large");
}
std::vector<unsigned char> random(entropy_bytes);
randombytes_buf(random.data(), random.size());
const auto encoded_size = sodium_base64_ENCODED_LEN(
random.size(), sodium_base64_VARIANT_URLSAFE_NO_PADDING);
std::string encoded(encoded_size, '\0');
const auto* result = sodium_bin2base64(
encoded.data(), encoded.size(), random.data(), random.size(),
sodium_base64_VARIANT_URLSAFE_NO_PADDING);
sodium_memzero(random.data(), random.size());
if (result == nullptr) {
return Void::Result::fail(
"Security::random_token: base64 encoding failed");
}
encoded.resize(std::strlen(encoded.c_str()));
return encoded;
}
Void::Result::Result<std::string> hash_token(std::string_view token)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
const auto digest = token_digest(token);
std::array<char, crypto_generichash_BYTES * 2 + 1> encoded{};
(void)sodium_bin2hex(encoded.data(), encoded.size(), digest.data(),
digest.size());
return std::string{encoded.data(), encoded.size() - 1};
}
Void::Result::Result<bool> verify_token(std::string_view token,
std::string_view encoded_hash)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
constexpr auto encoded_length = crypto_generichash_BYTES * 2;
if (encoded_hash.size() != encoded_length) {
return false;
}
std::array<unsigned char, crypto_generichash_BYTES> expected{};
std::size_t decoded_length = 0;
if (sodium_hex2bin(expected.data(), expected.size(),
encoded_hash.data(), encoded_hash.size(), nullptr,
&decoded_length, nullptr) != 0 ||
decoded_length != expected.size()) {
return false;
}
const auto actual = token_digest(token);
return sodium_memcmp(actual.data(), expected.data(), actual.size()) ==
0;
}
Void::Result::Result<std::string>
hash_password(std::string_view password, PasswordHashStrength strength)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
if (password.size() > crypto_pwhash_PASSWD_MAX) {
return Void::Result::fail(
"Security::hash_password: password is too long");
}
const auto limits = password_limits(strength);
if (!limits) {
return Void::Result::fail(
"Security::hash_password: invalid strength");
}
std::array<char, crypto_pwhash_STRBYTES> encoded{};
if (crypto_pwhash_str_alg(
encoded.data(), password.data(),
static_cast<unsigned long long>(password.size()),
limits->operations, limits->memory,
crypto_pwhash_ALG_ARGON2ID13) != 0) {
return Void::Result::fail(
"Security::hash_password: Argon2id hashing failed");
}
return std::string{encoded.data()};
}
Void::Result::Result<bool> verify_password(std::string_view password,
std::string_view encoded_hash)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
if (password.size() > crypto_pwhash_PASSWD_MAX ||
encoded_hash.empty() ||
encoded_hash.find('\0') != std::string_view::npos) {
return false;
}
const std::string terminated_hash{encoded_hash};
return crypto_pwhash_str_verify(
terminated_hash.c_str(), password.data(),
static_cast<unsigned long long>(password.size())) == 0;
}
Void::Result::Result<SecretKey> random_secret_key()
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
static_assert(secret_key_bytes == crypto_secretbox_KEYBYTES);
SecretKey key{};
crypto_secretbox_keygen(key.data());
return key;
}
Void::Result::Result<std::vector<unsigned char>>
seal_secret(std::span<const unsigned char> plaintext,
const SecretKey& key)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
static_assert(secret_nonce_bytes == crypto_secretbox_NONCEBYTES);
static_assert(secret_authentication_bytes == crypto_secretbox_MACBYTES);
if (plaintext.size() > std::numeric_limits<std::size_t>::max() -
secret_nonce_bytes -
secret_authentication_bytes) {
return Void::Result::fail(
"Security::seal_secret: plaintext is too large");
}
std::vector<unsigned char> envelope(secret_nonce_bytes +
secret_authentication_bytes +
plaintext.size());
auto* nonce = envelope.data();
auto* ciphertext = nonce + secret_nonce_bytes;
randombytes_buf(nonce, secret_nonce_bytes);
if (crypto_secretbox_easy(
ciphertext, plaintext.data(),
static_cast<unsigned long long>(plaintext.size()), nonce,
key.data()) != 0) {
return Void::Result::fail(
"Security::seal_secret: encryption failed");
}
return envelope;
}
Void::Result::Result<std::vector<unsigned char>>
open_secret(std::span<const unsigned char> envelope,
const SecretKey& key)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
}
if (envelope.size() <
secret_nonce_bytes + secret_authentication_bytes) {
return Void::Result::fail(
"Security::open_secret: envelope is truncated");
}
const auto* nonce = envelope.data();
const auto* ciphertext = nonce + secret_nonce_bytes;
const auto ciphertext_size = envelope.size() - secret_nonce_bytes;
std::vector<unsigned char> plaintext(ciphertext_size -
secret_authentication_bytes);
if (crypto_secretbox_open_easy(
plaintext.data(), ciphertext,
static_cast<unsigned long long>(ciphertext_size), nonce,
key.data()) != 0) {
return Void::Result::fail(
"Security::open_secret: authentication failed");
}
return plaintext;
}
} // namespace Void::Security
+4
View File
@@ -0,0 +1,4 @@
void_add_module(Security
INTERNAL_DEPS Functional
EXTERNAL_DEPS Sodium::Sodium
)
+3
View File
@@ -0,0 +1,3 @@
void_add_module(ShortUrl
INTERNAL_DEPS Service
)
-1
View File
@@ -7,7 +7,6 @@
#include <fstream>
#include <sstream>
#define BOOST_STACKTRACE_USE_BACKTRACE
#include <boost/core/demangle.hpp>
#include <boost/stacktrace.hpp>
+12 -2
View File
@@ -1,7 +1,17 @@
if(WIN32 AND NOT CYGWIN)
set(_void_stacktrace_target Boost::stacktrace_windbg)
else()
set(_void_stacktrace_target Boost::stacktrace_addr2line)
endif()
void_add_module(Stacktrace
INTERNAL_DEPS Functional
EXTERNAL_DEPS Boost::stacktrace_backtrace
DEPS_WIN32 dbghelp
EXTERNAL_DEPS ${_void_stacktrace_target}
DEPS_UNIX dl
OPTIONS_UNIX -g -fno-omit-frame-pointer
)
if(BUILD_SHARED_LIBS)
target_compile_definitions(Void_Stacktrace
PRIVATE BOOST_STACKTRACE_DYN_LINK)
endif()
+146
View File
@@ -0,0 +1,146 @@
#include <Void/System/SignalWatcher.hpp>
#include <algorithm>
#include <cerrno>
#include <climits>
#include <csignal>
#include <cstring>
#include <format>
#include <utility>
#ifdef __linux__
#include <poll.h>
#include <pthread.h>
#include <sys/signalfd.h>
#include <unistd.h>
#endif
namespace Void::Process
{
struct SignalWatcher::Impl {
#ifdef __linux__
int descriptor{-1};
sigset_t previousMask{};
bool maskInstalled{false};
pthread_t owner{};
~Impl()
{
if (descriptor >= 0) {
::close(descriptor);
}
if (maskInstalled &&
pthread_equal(owner, pthread_self()) != 0) {
(void)::pthread_sigmask(
SIG_SETMASK, &previousMask, nullptr);
}
}
#else
~Impl() = default;
#endif
};
SignalWatcher::SignalWatcher(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
SignalWatcher::~SignalWatcher() = default;
SignalWatcher::SignalWatcher(SignalWatcher&&) noexcept = default;
SignalWatcher& SignalWatcher::operator=(SignalWatcher&&) noexcept = default;
Void::Result::Result<SignalWatcher>
SignalWatcher::create(std::vector<int> signals)
{
#ifdef __linux__
if (signals.empty()) {
signals = {SIGINT, SIGTERM};
}
sigset_t mask{};
if (::sigemptyset(&mask) != 0) {
return Void::Result::fail(
std::format("Process::SignalWatcher: sigemptyset failed: {}",
std::strerror(errno)));
}
for (const int signal : signals) {
if (signal <= 0 || signal == SIGKILL || signal == SIGSTOP ||
::sigaddset(&mask, signal) != 0) {
return Void::Result::fail(std::format(
"Process::SignalWatcher: signal {} cannot be watched",
signal));
}
}
auto impl = std::make_unique<Impl>();
impl->owner = ::pthread_self();
const int maskResult =
::pthread_sigmask(SIG_BLOCK, &mask, &impl->previousMask);
if (maskResult != 0) {
return Void::Result::fail(std::format(
"Process::SignalWatcher: pthread_sigmask failed: {}",
std::strerror(maskResult)));
}
impl->maskInstalled = true;
impl->descriptor = ::signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
if (impl->descriptor < 0) {
return Void::Result::fail(
std::format("Process::SignalWatcher: signalfd failed: {}",
std::strerror(errno)));
}
return SignalWatcher{std::move(impl)};
#else
(void)signals;
return Void::Result::fail(
"Process::SignalWatcher is currently supported only on Linux");
#endif
}
Void::Result::Result<std::optional<int>>
SignalWatcher::wait(std::chrono::milliseconds timeout)
{
#ifdef __linux__
if (!m_impl || m_impl->descriptor < 0) {
return Void::Result::fail(
"Process::SignalWatcher::wait: watcher is moved-from");
}
const int timeoutMs = timeout == std::chrono::milliseconds::max()
? -1
: static_cast<int>(std::clamp<std::int64_t>(
timeout.count(), 0, INT_MAX));
pollfd descriptor{m_impl->descriptor, POLLIN, 0};
int pollResult = 0;
do {
pollResult = ::poll(&descriptor, 1, timeoutMs);
} while (pollResult < 0 && errno == EINTR);
if (pollResult == 0) {
return std::optional<int>{};
}
if (pollResult < 0) {
return Void::Result::fail(
std::format("Process::SignalWatcher::wait: poll failed: {}",
std::strerror(errno)));
}
if ((descriptor.revents & POLLIN) == 0) {
return Void::Result::fail(
"Process::SignalWatcher::wait: signal descriptor closed");
}
signalfd_siginfo info{};
const auto readCount = ::read(m_impl->descriptor, &info, sizeof(info));
if (readCount != static_cast<ssize_t>(sizeof(info))) {
return Void::Result::fail(
std::format("Process::SignalWatcher::wait: read failed: {}",
std::strerror(errno)));
}
return std::optional<int>{static_cast<int>(info.ssi_signo)};
#else
(void)timeout;
return Void::Result::fail(
"Process::SignalWatcher is currently supported only on Linux");
#endif
}
Void::Result::Result<std::optional<int>> SignalWatcher::poll()
{
return wait(std::chrono::milliseconds{0});
}
} // namespace Void::Process
+1
View File
@@ -1,3 +1,4 @@
void_add_module(System
INTERNAL_DEPS Functional
EXTERNAL_DEPS Threads::Threads
)
+922
View File
@@ -0,0 +1,922 @@
#include <Void/Update/Feed.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Text/Base64.hpp>
#include <algorithm>
#include <cmath>
#include <concepts>
#include <format>
#include <limits>
#include <set>
#include <tuple>
namespace Void::Update
{
namespace
{
using JsonResult = Void::Result::Result<const Json::Value*>;
[[nodiscard]] JsonResult member(const Json::Value& object,
std::string_view name,
bool (*predicate)(const Json::Value&),
std::string_view expected)
{
const auto* value = object.find(name);
if (value == nullptr || !predicate(*value)) {
return Void::Result::fail(std::format(
"Update feed: '{}' must be {}", name, expected));
}
return value;
}
[[nodiscard]] bool is_array(const Json::Value& value) noexcept
{
return value.is_array();
}
[[nodiscard]] bool is_object(const Json::Value& value) noexcept
{
return value.is_object();
}
[[nodiscard]] bool is_string(const Json::Value& value) noexcept
{
return value.is_string();
}
[[nodiscard]] bool is_number(const Json::Value& value) noexcept
{
return value.is_number();
}
template <std::unsigned_integral T>
[[nodiscard]] Void::Result::Result<T>
unsigned_number(const Json::Value& object, std::string_view name)
{
auto value = member(object, name, is_number, "an unsigned integer");
if (!value) {
return std::unexpected{value.error()};
}
const double number = (*value)->as_number();
constexpr double maxSafeInteger = 9'007'199'254'740'991.0;
if (!std::isfinite(number) || number < 0 ||
std::floor(number) != number || number > maxSafeInteger ||
number > static_cast<double>(std::numeric_limits<T>::max())) {
return Void::Result::fail(std::format(
"Update feed: '{}' is outside its integer range", name));
}
return static_cast<T>(number);
}
[[nodiscard]] Void::Result::Result<std::string>
string_member(const Json::Value& object, std::string_view name)
{
auto value = member(object, name, is_string, "a string");
if (!value) {
return std::unexpected{value.error()};
}
return (*value)->as_string();
}
[[nodiscard]] bool valid_token(std::string_view value,
std::size_t maximum = 128) noexcept
{
if (value.empty() || value.size() > maximum) {
return false;
}
for (const char character : value) {
if (!((character >= 'a' && character <= 'z') ||
(character >= 'A' && character <= 'Z') ||
(character >= '0' && character <= '9') ||
character == '.' || character == '_' ||
character == '-')) {
return false;
}
}
return true;
}
[[nodiscard]] bool valid_sha256(std::string_view value) noexcept
{
if (value.size() != 64) {
return false;
}
return std::ranges::all_of(value, [](const char character) {
return (character >= '0' && character <= '9') ||
(character >= 'a' && character <= 'f');
});
}
[[nodiscard]] bool
valid_prefixed_hash(std::string_view value, std::string_view prefix,
std::size_t hexadecimalSize) noexcept
{
if (!value.starts_with(prefix)) {
return false;
}
const auto hexadecimal = value.substr(prefix.size());
return hexadecimal.size() == hexadecimalSize &&
std::ranges::all_of(hexadecimal, [](const char character) {
return (character >= '0' && character <= '9') ||
(character >= 'a' && character <= 'f');
});
}
[[nodiscard]] bool valid_hex(std::string_view value,
std::size_t size) noexcept
{
return value.size() == size &&
std::ranges::all_of(value, [](const char character) {
return (character >= 48 && character <= 57) ||
(character >= 97 && character <= 102);
});
}
[[nodiscard]] bool valid_package_type(std::string_view value) noexcept
{
return !value.empty() && value.size() <= 128 &&
std::ranges::all_of(value, [](const char character) {
return (character >= 'a' && character <= 'z') ||
(character >= '0' && character <= '9') ||
character == '.' || character == '-' ||
character == '_';
});
}
[[nodiscard]] std::optional<int>
decimal(std::string_view value) noexcept
{
int result = 0;
for (const char character : value) {
if (character < '0' || character > '9') {
return std::nullopt;
}
result = result * 10 + (character - '0');
}
return result;
}
[[nodiscard]] std::optional<std::chrono::system_clock::time_point>
parse_timestamp(std::string_view value) noexcept
{
if (value.size() < 20 || value[4] != '-' || value[7] != '-' ||
value[10] != 'T' || value[13] != ':' || value[16] != ':' ||
value.back() != 'Z') {
return std::nullopt;
}
const auto year = decimal(value.substr(0, 4));
const auto month = decimal(value.substr(5, 2));
const auto day = decimal(value.substr(8, 2));
const auto hour = decimal(value.substr(11, 2));
const auto minute = decimal(value.substr(14, 2));
const auto second = decimal(value.substr(17, 2));
if (!year || !month || !day || !hour || !minute || !second ||
*hour > 23 || *minute > 59 || *second > 59) {
return std::nullopt;
}
if (value.size() > 20) {
if (value.size() == 21 || value[19] != '.') {
return std::nullopt;
}
for (std::size_t index = 20; index + 1 < value.size();
++index) {
if (value[index] < '0' || value[index] > '9') {
return std::nullopt;
}
}
}
const std::chrono::year_month_day date{
std::chrono::year{*year},
std::chrono::month{static_cast<unsigned>(*month)},
std::chrono::day{static_cast<unsigned>(*day)}};
if (!date.ok()) {
return std::nullopt;
}
return std::chrono::sys_days{date} + std::chrono::hours{*hour} +
std::chrono::minutes{*minute} +
std::chrono::seconds{*second};
}
[[nodiscard]] Void::Result::Result<Compatibility>
parse_compatibility(const Json::Value& value)
{
if (!value.is_object()) {
return Void::Result::fail(
"Update feed: compatibility must be an object");
}
Compatibility result;
if (const auto* contracts = value.find("versionContracts")) {
if (!contracts->is_object()) {
return Void::Result::fail(
"Update feed: compatibility.versionContracts must be "
"an object");
}
for (const auto& [name, rangeValue] : contracts->as_object()) {
if (!valid_token(name, 256) || !rangeValue.is_string()) {
return Void::Result::fail(
"Update feed: invalid version contract");
}
auto range = Semver::parse_range(rangeValue.as_string());
if (!range) {
return Void::Result::fail(
std::format("Update feed: version contract '{}' "
"has an invalid range",
name));
}
result.versionContracts.emplace(name, std::move(*range));
}
}
if (const auto* contracts = value.find("exactContracts")) {
if (!contracts->is_object()) {
return Void::Result::fail(
"Update feed: compatibility.exactContracts must be an "
"object");
}
for (const auto& [name, contractValue] :
contracts->as_object()) {
if (!valid_token(name, 256) || !contractValue.is_string() ||
contractValue.as_string().empty() ||
contractValue.as_string().size() > 512) {
return Void::Result::fail(
"Update feed: invalid exact contract");
}
result.exactContracts.emplace(name,
contractValue.as_string());
}
}
return result;
}
[[nodiscard]] Void::Result::Result<Release>
parse_release(const Json::Value& value)
{
if (!value.is_object()) {
return Void::Result::fail(
"Update feed: release must be an object");
}
Release release;
auto component = string_member(value, "component");
if (!component || !valid_token(*component, 256)) {
return Void::Result::fail("Update feed: component is invalid");
}
release.component = std::move(*component);
release.artifactId = value.get_str("artifactId");
if (!release.artifactId.empty() &&
!valid_token(release.artifactId, 256)) {
return Void::Result::fail("Update feed: artifactId is invalid");
}
auto channel = string_member(value, "channel");
auto versionText = string_member(value, "version");
auto platform = string_member(value, "platform");
auto architecture = string_member(value, "arch");
auto url = string_member(value, "url");
auto size = unsigned_number<std::uint64_t>(value, "size");
auto sha256 = string_member(value, "sha256");
auto packageType = string_member(value, "packageType");
if (!channel || !versionText || !platform || !architecture ||
!url || !size || !sha256 || !packageType) {
return Void::Result::fail(
"Update feed: release has invalid required fields");
}
const auto cohort = value.get_str("cohort");
const auto manifestHash = value.get_str("releaseManifestSha256");
const bool urlIsBounded =
!url->empty() && url->size() <= 8192 &&
std::ranges::none_of(*url, [](const unsigned char character) {
return character < 0x20 || character == 0x7f;
});
if (!valid_token(*channel) ||
(!cohort.empty() && !valid_token(cohort, 256)) ||
!valid_token(*platform) || !valid_token(*architecture) ||
!urlIsBounded || *size == 0 || !valid_sha256(*sha256) ||
!valid_package_type(*packageType) ||
(!manifestHash.empty() && !valid_sha256(manifestHash))) {
return Void::Result::fail("Update feed: release contains an "
"unsafe or unsupported field");
}
auto version = Semver::parse_strict(*versionText);
if (!version) {
return Void::Result::fail(
"Update feed: release version is invalid SemVer");
}
release.channel = std::move(*channel);
release.version = std::move(*version);
release.cohort = cohort;
release.platform = std::move(*platform);
release.architecture = std::move(*architecture);
release.url = std::move(*url);
release.size = *size;
release.sha256 = std::move(*sha256);
release.packageType = std::move(*packageType);
release.releaseManifestSha256 = manifestHash;
const auto* compatibility = value.find("compatibility");
if (compatibility) {
auto parsedCompatibility = parse_compatibility(*compatibility);
if (!parsedCompatibility) {
return std::unexpected{parsedCompatibility.error()};
}
release.compatibility = std::move(*parsedCompatibility);
}
return release;
}
[[nodiscard]] Void::Result::Result<Feed>
parse_feed(std::string_view payload,
const VerificationPolicy& policy)
{
auto document = Json::parse(payload);
if (!document || !document->is_object()) {
return Void::Result::fail(
"Update feed: signed payload is not a JSON object");
}
auto schema =
unsigned_number<std::uint32_t>(*document, "schemaVersion");
auto feedId = string_member(*document, "feedId");
auto sequence =
unsigned_number<std::uint64_t>(*document, "sequence");
auto generated = string_member(*document, "generatedAt");
auto expires = string_member(*document, "expiresAt");
auto releasesValue =
member(*document, "releases", is_array, "an array");
if (!schema || !feedId || !sequence || !generated || !expires ||
!releasesValue) {
return Void::Result::fail(
"Update feed: invalid top-level fields");
}
if (*schema != 1 || !valid_token(*feedId, 256)) {
return Void::Result::fail(
"Update feed: unsupported schema or invalid feedId");
}
if (policy.minimumSequence &&
*sequence <= *policy.minimumSequence) {
return Void::Result::fail(
"Update feed: sequence is not newer than the replay floor");
}
const auto generatedAt = parse_timestamp(*generated);
const auto expiresAt = parse_timestamp(*expires);
if (!generatedAt || !expiresAt || *expiresAt <= *generatedAt) {
return Void::Result::fail(
"Update feed: timestamps are invalid");
}
if (policy.requireUnexpired && policy.now >= *expiresAt) {
return Void::Result::fail("Update feed: feed has expired");
}
const auto& values = (*releasesValue)->as_array();
if (values.size() > policy.maxReleases) {
return Void::Result::fail(
"Update feed: release count exceeds policy");
}
Feed feed{.schemaVersion = *schema,
.feedId = std::move(*feedId),
.sequence = *sequence,
.generatedAt = *generatedAt,
.expiresAt = *expiresAt};
std::set<std::tuple<std::string, std::string, std::string,
std::string, std::string, std::string>>
identities;
feed.releases.reserve(values.size());
for (const auto& value : values) {
auto release = parse_release(value);
if (!release) {
return std::unexpected{release.error()};
}
auto identity =
std::tuple{release->component, release->artifactId,
release->channel, release->version.to_string(),
release->platform, release->architecture};
if (!identities.insert(std::move(identity)).second) {
return Void::Result::fail(
"Update feed: ambiguous duplicate release identity");
}
feed.releases.push_back(std::move(*release));
}
return feed;
}
struct ComponentDocumentHeader {
std::string channel;
std::uint64_t sequence{0};
std::chrono::system_clock::time_point generatedAt;
std::chrono::system_clock::time_point expiresAt;
Semver::Version productVersion;
};
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
optional_token(const Json::Value& object, std::string_view name)
{
const auto* value = object.find(name);
if (value == nullptr || value->is_null()) {
return std::optional<std::string>{};
}
if (!value->is_string() || !valid_token(value->as_string(), 256)) {
return Void::Result::fail(std::format(
"Component feed: {} must be null or a safe token", name));
}
return std::optional<std::string>{value->as_string()};
}
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
optional_string(const Json::Value& object, std::string_view name)
{
const auto* value = object.find(name);
if (value == nullptr || value->is_null()) {
return std::optional<std::string>{};
}
if (!value->is_string()) {
return Void::Result::fail(std::format(
"Component feed: {} must be null or a string", name));
}
return std::optional<std::string>{value->as_string()};
}
[[nodiscard]] Void::Result::Result<
std::map<std::string, Semver::VersionRange>>
parse_dependencies(const Json::Value& object)
{
const auto* dependencies = object.find("dependencies");
if (dependencies == nullptr || !dependencies->is_object()) {
return Void::Result::fail(
"Component feed: dependencies must be an object");
}
std::map<std::string, Semver::VersionRange> result;
for (const auto& [component, value] : dependencies->as_object()) {
if (!valid_token(component, 256) || !value.is_string()) {
return Void::Result::fail(
"Component feed: dependency contains an unsafe field");
}
auto range = Semver::parse_range(value.as_string());
if (!range) {
return Void::Result::fail(std::format(
"Component feed: dependency {} has an invalid range",
component));
}
result.emplace(component, std::move(*range));
}
return result;
}
[[nodiscard]] Void::Result::Result<std::map<std::string, std::string>>
parse_dependency_constraints(const Json::Value& object)
{
const auto* dependencies = object.find("dependencies");
if (dependencies == nullptr || !dependencies->is_object()) {
return Void::Result::fail(
"Component feed: dependencies must be an object");
}
std::map<std::string, std::string> result;
for (const auto& [component, value] : dependencies->as_object()) {
if (!valid_token(component, 256) || !value.is_string() ||
value.as_string().empty() ||
value.as_string().size() > 512) {
return Void::Result::fail(
"Component feed: dependency contains an unsafe field");
}
result.emplace(component, value.as_string());
}
return result;
}
[[nodiscard]] Void::Result::Result<ComponentDocumentHeader>
parse_component_header(const Json::Value& document,
std::string_view expectedDocument,
const VerificationPolicy& policy)
{
auto schema =
unsigned_number<std::uint32_t>(document, "schemaVersion");
auto type = string_member(document, "document");
auto channel = string_member(document, "channel");
auto sequence =
unsigned_number<std::uint64_t>(document, "sequence");
auto generated = string_member(document, "generatedAt");
auto expires = string_member(document, "expiresAt");
auto productVersion = string_member(document, "productVersion");
if (!schema || !type || !channel || !sequence || !generated ||
!expires || !productVersion || *schema != 2 ||
*type != expectedDocument || !valid_token(*channel, 64)) {
return Void::Result::fail(
"Component feed: invalid discovery document header");
}
if (policy.minimumSequence &&
*sequence <= *policy.minimumSequence) {
return Void::Result::fail("Component feed: sequence is not "
"newer than the replay floor");
}
const auto generatedAt = parse_timestamp(*generated);
const auto expiresAt = parse_timestamp(*expires);
auto version = Semver::parse_strict(*productVersion);
if (!generatedAt || !expiresAt || *expiresAt <= *generatedAt ||
!version) {
return Void::Result::fail(
"Component feed: timestamp or product version is invalid");
}
if (policy.requireUnexpired && policy.now >= *expiresAt) {
return Void::Result::fail(
"Component feed: discovery document has expired");
}
return ComponentDocumentHeader{.channel = std::move(*channel),
.sequence = *sequence,
.generatedAt = *generatedAt,
.expiresAt = *expiresAt,
.productVersion =
std::move(*version)};
}
[[nodiscard]] bool bounded_url(std::string_view value) noexcept
{
return value.starts_with("https://") && value.size() <= 8192 &&
std::ranges::none_of(
value, [](const unsigned char character) {
return character < 0x20 || character == 0x7f;
});
}
[[nodiscard]] Void::Result::Result<ComponentCatalogEntry>
parse_catalog_entry(const Json::Value& value)
{
if (!value.is_object()) {
return Void::Result::fail(
"Component feed: catalog entry must be an object");
}
auto componentId = string_member(value, "componentId");
auto pluginId = optional_token(value, "pluginId");
auto kind = string_member(value, "kind");
auto versionText = string_member(value, "componentVersion");
auto activation = string_member(value, "activation");
auto sequence = unsigned_number<std::uint64_t>(value, "sequence");
auto latestUrl = string_member(value, "latestUrl");
auto artifactSha = string_member(value, "artifactSha256");
auto dependencyConstraints = parse_dependency_constraints(value);
auto dependencies = parse_dependencies(value);
if (!componentId || !pluginId || !kind || !versionText ||
!activation || !sequence || !latestUrl || !artifactSha ||
!dependencyConstraints || !dependencies ||
!valid_token(*componentId, 256) || !valid_token(*kind, 128) ||
!valid_token(*activation, 128) || !bounded_url(*latestUrl) ||
!valid_sha256(*artifactSha)) {
return Void::Result::fail(
"Component feed: catalog entry contains an unsafe field");
}
auto version = Semver::parse_strict(*versionText);
if (!version) {
return Void::Result::fail(
"Component feed: component version is invalid SemVer");
}
return ComponentCatalogEntry{
.componentId = std::move(*componentId),
.pluginId = std::move(*pluginId),
.kind = std::move(*kind),
.componentVersion = std::move(*version),
.activation = std::move(*activation),
.dependencyConstraints = std::move(*dependencyConstraints),
.dependencies = std::move(*dependencies),
.sequence = *sequence,
.latestUrl = std::move(*latestUrl),
.artifactSha256 = std::move(*artifactSha)};
}
[[nodiscard]] bool compatible(const Compatibility& compatibility,
const Environment& environment) noexcept
{
for (const auto& [name, range] : compatibility.versionContracts) {
const auto installed = environment.versionContracts.find(name);
if (installed == environment.versionContracts.end() ||
!range.contains(installed->second)) {
return false;
}
}
for (const auto& [name, value] : compatibility.exactContracts) {
const auto installed = environment.exactContracts.find(name);
if (installed == environment.exactContracts.end() ||
installed->second != value) {
return false;
}
}
return true;
}
} // namespace
Void::Result::Result<Feed>
parseFeedPayload(std::string_view payload,
const VerificationPolicy& policy)
{
if (payload.size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Update feed: payload exceeds policy size");
}
return parse_feed(payload, policy);
}
Void::Result::Result<VerifiedFeed>
verifyFeedEnvelope(std::string_view envelopeJson, const Keyring& keys,
const VerificationPolicy& policy)
{
auto envelope = verifyEnvelope(envelopeJson, keys, policy);
if (!envelope) {
return std::unexpected{envelope.error()};
}
if (envelope->schemaVersion != 1) {
return Void::Result::fail(
"Update feed: aggregate feed requires envelope schema 1");
}
auto feed = parseFeedPayload(envelope->signedPayload, policy);
if (!feed) {
return std::unexpected{feed.error()};
}
return VerifiedFeed{.feed = std::move(*feed),
.keyId = std::move(envelope->keyId),
.signedPayload =
std::move(envelope->signedPayload)};
}
Void::Result::Result<VerifiedEnvelope>
verifyEnvelope(std::string_view envelopeJson, const Keyring& keys,
const VerificationPolicy& policy)
{
if (envelopeJson.size() > policy.maxEnvelopeBytes) {
return Void::Result::fail(
"Update feed: envelope exceeds policy size");
}
auto envelope = Json::parse(envelopeJson);
if (!envelope || !envelope->is_object()) {
return Void::Result::fail(
"Update feed: envelope is not a JSON object");
}
auto schema =
unsigned_number<std::uint32_t>(*envelope, "schemaVersion");
auto keyId = string_member(*envelope, "keyId");
auto signatureText = string_member(*envelope, "signature");
if (!schema || !keyId || !signatureText ||
(*schema != 1 && *schema != 2 && *schema != 3) ||
!valid_token(*keyId, 256)) {
return Void::Result::fail("Update feed: invalid envelope fields");
}
auto payloadText = string_member(
*envelope, *schema == 3 ? "signedPayload" : "payload");
const Json::Value* displayedDocument = nullptr;
if (*schema == 3) {
auto document =
member(*envelope, "document", is_object, "an object");
if (!document) {
return std::unexpected{document.error()};
}
displayedDocument = *document;
}
if (!payloadText) {
return Void::Result::fail("Update feed: invalid envelope fields");
}
const auto key = keys.find(*keyId);
if (key == keys.end()) {
return Void::Result::fail(
"Update feed: envelope key is not trusted");
}
auto payload = Encoding::Base64::decode_url(*payloadText);
auto signature = Encoding::Base64::decode_url(*signatureText);
if (!payload || !signature ||
payload->size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Update feed: invalid or oversized envelope encoding");
}
if (*schema == 3) {
auto signedDocument = Json::parse(*payload);
if (!signedDocument || !signedDocument->is_object() ||
displayedDocument == nullptr ||
*displayedDocument != *signedDocument) {
return Void::Result::fail("Update feed: readable document "
"differs from signed payload");
}
}
const auto signatureBytes =
std::as_bytes(std::span{signature->data(), signature->size()});
const auto payloadBytes =
std::as_bytes(std::span{payload->data(), payload->size()});
auto valid =
Crypto::verifyEd25519(payloadBytes, signatureBytes, key->second);
if (!valid) {
return std::unexpected{valid.error()};
}
if (!*valid) {
return Void::Result::fail(
"Update feed: signature verification failed");
}
return VerifiedEnvelope{.schemaVersion = *schema,
.keyId = std::move(*keyId),
.signedPayload = std::move(*payload)};
}
Void::Result::Result<ComponentCatalog>
parseComponentCatalogPayload(std::string_view payload,
const VerificationPolicy& policy)
{
if (payload.size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Component feed: payload exceeds policy size");
}
auto document = Json::parse(payload);
if (!document || !document->is_object()) {
return Void::Result::fail(
"Component feed: catalog payload is not an object");
}
auto header = parse_component_header(
*document, "echoion-component-catalog", policy);
auto components = member(*document, "components", is_array, "an array");
if (!header || !components) {
return Void::Result::fail("Component feed: invalid catalog fields");
}
const auto& values = (*components)->as_array();
if (values.empty() || values.size() > policy.maxReleases) {
return Void::Result::fail(
"Component feed: catalog component count exceeds policy");
}
ComponentCatalog result{.channel = std::move(header->channel),
.sequence = header->sequence,
.generatedAt = header->generatedAt,
.expiresAt = header->expiresAt,
.productVersion =
std::move(header->productVersion)};
std::set<std::string> identities;
result.components.reserve(values.size());
for (const auto& value : values) {
auto entry = parse_catalog_entry(value);
if (!entry) {
return std::unexpected{entry.error()};
}
if (entry->sequence != result.sequence ||
!identities.insert(entry->componentId).second) {
return Void::Result::fail("Component feed: catalog has a "
"sequence mismatch or duplicate");
}
result.components.push_back(std::move(*entry));
}
return result;
}
Void::Result::Result<ComponentRelease>
parseComponentReleasePayload(std::string_view payload,
const VerificationPolicy& policy)
{
if (payload.size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Component feed: payload exceeds policy size");
}
auto document = Json::parse(payload);
if (!document || !document->is_object()) {
return Void::Result::fail(
"Component feed: release payload is not an object");
}
auto header = parse_component_header(
*document, "echoion-component-release", policy);
auto componentId = string_member(*document, "componentId");
auto pluginId = optional_token(*document, "pluginId");
auto kind = string_member(*document, "kind");
auto componentVersion = string_member(*document, "componentVersion");
auto sourceSha = string_member(*document, "sourceSha");
auto sourceTreeHash = string_member(*document, "sourceTreeHash");
auto abiHash = optional_string(*document, "abiHash");
auto artifactIdentity = string_member(*document, "artifactIdentity");
auto activation = string_member(*document, "activation");
auto platform = string_member(*document, "platform");
auto architecture = string_member(*document, "architecture");
auto toolchainContract = string_member(*document, "toolchainContract");
auto dependencyConstraints = parse_dependency_constraints(*document);
auto dependencies = parse_dependencies(*document);
const auto* artifactValue = document->find("artifact");
if (!header || !componentId || !pluginId || !kind ||
!componentVersion || !sourceSha || !sourceTreeHash || !abiHash ||
!artifactIdentity || !activation || !platform || !architecture ||
!toolchainContract || !dependencyConstraints || !dependencies ||
artifactValue == nullptr || !artifactValue->is_object() ||
!valid_token(*componentId, 256) || !valid_token(*kind, 128) ||
!valid_token(*artifactIdentity, 256) ||
!valid_token(*activation, 128) || !valid_token(*platform, 64) ||
!valid_token(*architecture, 64) ||
!valid_token(*toolchainContract, 256) ||
!valid_hex(*sourceSha, 40) ||
!valid_prefixed_hash(*sourceTreeHash, "git-sha1:", 40) ||
(*abiHash && !valid_prefixed_hash(**abiHash, "sha256:", 64))) {
return Void::Result::fail(
"Component feed: release contains an unsafe field");
}
auto version = Semver::parse_strict(*componentVersion);
auto artifactName = string_member(*artifactValue, "name");
auto artifactUrl = string_member(*artifactValue, "url");
auto artifactSha = string_member(*artifactValue, "sha256");
auto artifactSize =
unsigned_number<std::uint64_t>(*artifactValue, "size");
auto manifestSha = string_member(*artifactValue, "manifestSha256");
auto packageType = string_member(*artifactValue, "packageType");
if (!version || !artifactName || !artifactUrl || !artifactSha ||
!artifactSize || !manifestSha || !packageType ||
!valid_token(*artifactName, 256) || !bounded_url(*artifactUrl) ||
!valid_sha256(*artifactSha) || *artifactSize == 0 ||
!valid_sha256(*manifestSha) || !valid_package_type(*packageType)) {
return Void::Result::fail(
"Component feed: release artifact contains an unsafe field");
}
return ComponentRelease{
.channel = std::move(header->channel),
.sequence = header->sequence,
.generatedAt = header->generatedAt,
.expiresAt = header->expiresAt,
.productVersion = std::move(header->productVersion),
.componentId = std::move(*componentId),
.pluginId = std::move(*pluginId),
.kind = std::move(*kind),
.componentVersion = std::move(*version),
.sourceSha = std::move(*sourceSha),
.sourceTreeHash = std::move(*sourceTreeHash),
.abiHash = std::move(*abiHash),
.artifactIdentity = std::move(*artifactIdentity),
.activation = std::move(*activation),
.platform = std::move(*platform),
.architecture = std::move(*architecture),
.toolchainContract = std::move(*toolchainContract),
.dependencyConstraints = std::move(*dependencyConstraints),
.dependencies = std::move(*dependencies),
.artifact = {.name = std::move(*artifactName),
.url = std::move(*artifactUrl),
.sha256 = std::move(*artifactSha),
.size = *artifactSize,
.manifestSha256 = std::move(*manifestSha),
.packageType = std::move(*packageType)}};
}
Void::Result::Result<void> validateComponentSet(
const ComponentCatalog& catalog,
const std::map<std::string, ComponentRelease>& releases)
{
if (catalog.components.size() != releases.size()) {
return Void::Result::fail(
"Component set: release count does not match the catalog");
}
for (const auto& entry : catalog.components) {
const auto release = releases.find(entry.componentId);
if (release == releases.end()) {
return Void::Result::fail(std::format(
"Component set: release {} is missing", entry.componentId));
}
const auto& value = release->second;
if (value.componentId != entry.componentId ||
value.componentVersion != entry.componentVersion ||
value.productVersion != catalog.productVersion ||
value.channel != catalog.channel ||
value.sequence != catalog.sequence ||
value.artifact.sha256 != entry.artifactSha256 ||
value.activation != entry.activation ||
value.pluginId != entry.pluginId || value.kind != entry.kind ||
value.dependencyConstraints != entry.dependencyConstraints ||
value.dependencies.size() != entry.dependencies.size()) {
return Void::Result::fail(std::format(
"Component set: release {} does not match the catalog",
entry.componentId));
}
for (const auto& [dependencyId, range] : value.dependencies) {
const auto dependency = releases.find(dependencyId);
const auto catalogRange = entry.dependencies.find(dependencyId);
if (dependency == releases.end() ||
catalogRange == entry.dependencies.end() ||
!range.contains(dependency->second.componentVersion) ||
!catalogRange->second.contains(
dependency->second.componentVersion)) {
return Void::Result::fail(std::format(
"Component set: dependency {} of {} is incompatible",
dependencyId, entry.componentId));
}
}
}
return {};
}
std::optional<Release> selectRelease(const Feed& feed,
const SelectionRequest& request)
{
const Release* selected = nullptr;
for (const auto& release : feed.releases) {
if (release.component != request.component ||
release.artifactId != request.artifactId ||
release.channel != request.channel ||
release.platform != request.environment.platform ||
release.architecture != request.environment.architecture ||
(request.requiredCohort &&
release.cohort != *request.requiredCohort) ||
!compatible(release.compatibility, request.environment)) {
continue;
}
if (request.currentVersion) {
const auto comparison =
release.version <=> *request.currentVersion;
if (comparison == 0 && !request.includeCurrent) {
continue;
}
if (comparison < 0 && !request.allowDowngrade) {
continue;
}
}
if (selected == nullptr || release.version > selected->version) {
selected = &release;
}
}
if (selected == nullptr) {
return std::nullopt;
}
return *selected;
}
} // namespace Void::Update
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Update
INTERNAL_DEPS Crypto Data Functional System Text
)
+23
View File
@@ -80,7 +80,30 @@ if(_all_generated)
endif()
endforeach()
# A few fixtures construct archives and signatures through the upstream C
# APIs directly. Those are test implementation dependencies, not part of
# the public interface of Void's shared modules.
if(TARGET LibArchive::LibArchive)
target_link_libraries(VoidTests PRIVATE LibArchive::LibArchive)
endif()
if(TARGET OpenSSL::Crypto)
target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto)
endif()
add_test(NAME VoidTests COMMAND VoidTests)
add_test(NAME VoidInstalledComponentConsumers
COMMAND ${CMAKE_COMMAND}
-DVOID_BUILD_DIR=${CMAKE_BINARY_DIR}
-DVOID_TEST_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/package
-DVOID_TEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/package-consumer
-DVOID_CXX_COMPILER=${CMAKE_CXX_COMPILER}
-DVOID_CTEST_COMMAND=${CMAKE_CTEST_COMMAND}
-DVOID_BUILD_CONFIG=$<CONFIG>
-P ${CMAKE_CURRENT_SOURCE_DIR}/package/InstalledComponents.cmake
)
set_tests_properties(VoidInstalledComponentConsumers PROPERTIES
DEPENDS VoidTests)
endif()
# ── Test-support libraries ────────────────────────────────────────────────────
+88
View File
@@ -10,7 +10,10 @@
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
@@ -147,4 +150,89 @@ Void::Testing::Test internal_service_reload_migrates_and_swaps()
Void::Testing::expect_eq(v2->accumulate(0), 40); // state migrated
}
// A validator rejection during the automatic reload callback must preserve
// the last accepted service instead of publishing the rejected candidate.
Void::Testing::Test plugin_service_reload_validation_preserves_last_good()
{
Void::FileSystem::TempDir tmp{"void_svcplugin_validate"};
const auto so = tmp.path() / "calc.so";
std::filesystem::copy_file(VOID_SERVICE_V1_PATH, so);
Void::Service::ServiceRegistry registry;
Void::Plugin::PluginManager plugins;
Void::Testing::expect(plugins.load(so).has_value());
Void::Service::PluginServiceBinding<VoidTest::ICalc> binding{
plugins, registry, "CalcPlugin",
[](const std::shared_ptr<VoidTest::ICalc>& service) {
return service->version() == 1;
}};
Void::Testing::expect(binding.bind());
binding.enable_hot_reload();
install(VOID_SERVICE_V2_PATH, so);
Void::Testing::expect(plugins.reload("CalcPlugin").has_value());
auto service = registry.get<VoidTest::ICalc>();
Void::Testing::expect(service != nullptr);
Void::Testing::expect_eq(service->version(), 1);
}
// PluginManager intentionally invokes a copied callback list outside its
// mutex. Destroying a binding after that copy must make its callback inert.
Void::Testing::Test plugin_service_callback_is_safe_after_binding_destruction()
{
Void::FileSystem::TempDir tmp{"void_svcplugin_lifetime"};
const auto so = tmp.path() / "calc.so";
std::filesystem::copy_file(VOID_SERVICE_V1_PATH, so);
Void::Service::ServiceRegistry registry;
Void::Plugin::PluginManager plugins;
Void::Testing::expect(plugins.load(so).has_value());
std::mutex gateMutex;
std::condition_variable gateChanged;
bool callbackEntered = false;
bool releaseCallback = false;
const auto blocker = plugins.on_reloaded([&](std::string_view) {
std::unique_lock lock{gateMutex};
callbackEntered = true;
gateChanged.notify_all();
gateChanged.wait(lock, [&] { return releaseCallback; });
});
auto binding =
std::make_unique<Void::Service::PluginServiceBinding<VoidTest::ICalc>>(
plugins, registry, "CalcPlugin");
Void::Testing::expect(binding->bind());
binding->enable_hot_reload();
install(VOID_SERVICE_V2_PATH, so);
std::atomic<bool> reloadSucceeded{false};
std::thread reloader{[&] {
reloadSucceeded.store(plugins.reload("CalcPlugin").has_value(),
std::memory_order_release);
}};
bool callbackWasObserved = false;
{
std::unique_lock lock{gateMutex};
callbackWasObserved = gateChanged.wait_for(
lock, std::chrono::seconds{5}, [&] { return callbackEntered; });
}
binding.reset();
{
std::lock_guard lock{gateMutex};
releaseCallback = true;
}
gateChanged.notify_all();
reloader.join();
plugins.remove_on_reloaded(blocker);
Void::Testing::expect(callbackWasObserved);
Void::Testing::expect(reloadSucceeded.load(std::memory_order_acquire));
auto service = registry.get<VoidTest::ICalc>();
Void::Testing::expect(service != nullptr);
Void::Testing::expect_eq(service->version(), 1);
}
#endif // service plugins available
+24
View File
@@ -0,0 +1,24 @@
cmake_minimum_required(VERSION 4.0)
project(VoidAuditedConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS
Archive
Binary
Crypto
Plugin
System
Update
)
add_executable(void_audited_consumer main.cpp)
target_link_libraries(void_audited_consumer PRIVATE
Void::Archive
Void::Binary
Void::Crypto
Void::Plugin
Void::System
Void::Update
)
enable_testing()
add_test(NAME VoidAuditedConsumer COMMAND void_audited_consumer)
+28
View File
@@ -0,0 +1,28 @@
#include <Void/Archive/Archive.hpp>
#include <Void/Binary/Reader.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Plugin/Loader.hpp>
#include <Void/Plugin/Manager.hpp>
#include <Void/System/SignalWatcher.hpp>
#include <Void/Update/Update.hpp>
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
int main()
{
const std::array bytes{std::byte{0x01}, std::byte{0x02}};
Void::Binary::Reader reader{bytes};
const auto value = reader.read<std::uint16_t>(std::endian::big);
const auto digest = Void::Crypto::sha256(bytes);
const Void::Archive::ExtractionOptions limits{};
const Void::Update::VerificationPolicy policy{};
const Void::Plugin::PluginManager::Options plugins{};
return value && *value == 0x0102 && digest && !digest->empty() &&
limits.maxEntries > 0 && policy.maxReleases > 0 &&
plugins.debounce_polls > 0
? 0
: 1;
}
+10
View File
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidBinaryConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Binary)
add_executable(void_binary_consumer main.cpp)
target_link_libraries(void_binary_consumer PRIVATE Void::Binary)
enable_testing()
add_test(NAME VoidBinaryConsumer COMMAND void_binary_consumer)
+14
View File
@@ -0,0 +1,14 @@
#include <Void/Binary/Reader.hpp>
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
int main()
{
const std::array bytes{std::byte{0x01}, std::byte{0x02}};
Void::Binary::Reader reader{bytes};
const auto value = reader.read<std::uint16_t>(std::endian::big);
return value && *value == 0x0102 ? 0 : 1;
}
+20
View File
@@ -0,0 +1,20 @@
cmake_minimum_required(VERSION 4.0)
project(VoidExternalConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS
Net
Security
Sqlite
Stacktrace
)
add_executable(void_external_consumer main.cpp)
target_link_libraries(void_external_consumer PRIVATE
Void::Net
Void::Security
Void::Sqlite
Void::Stacktrace
)
enable_testing()
add_test(NAME VoidExternalConsumer COMMAND void_external_consumer)
+19
View File
@@ -0,0 +1,19 @@
#include <Void/Net/Url.hpp>
#include <Void/Security/Security.hpp>
#include <Void/Sqlite/Sqlite.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <string>
int main()
{
const auto url = Void::Net::Url::parse("https://example.invalid/path");
const auto token = Void::Security::hash_token("void-consumer-token");
auto database = Void::Sqlite::Database::open(":memory:");
const auto frames = Void::Stacktrace::capture_stacktrace(0, 1);
return url && url->target == "/path" && token && !token->empty() &&
database && frames.size() <= 1
? 0
: 1;
}
+61
View File
@@ -0,0 +1,61 @@
cmake_minimum_required(VERSION 4.0)
foreach(required IN ITEMS VOID_BUILD_DIR VOID_TEST_SOURCE_DIR VOID_TEST_ROOT
VOID_CXX_COMPILER VOID_CTEST_COMMAND)
if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
message(FATAL_ERROR "${required} is required")
endif()
endforeach()
file(REMOVE_RECURSE "${VOID_TEST_ROOT}")
set(install_prefix "${VOID_TEST_ROOT}/install")
set(install_command "${CMAKE_COMMAND}" --install "${VOID_BUILD_DIR}"
--prefix "${install_prefix}")
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
list(APPEND install_command --config "${VOID_BUILD_CONFIG}")
endif()
execute_process(COMMAND ${install_command} COMMAND_ERROR_IS_FATAL ANY)
function(run_consumer name)
set(source_dir "${VOID_TEST_SOURCE_DIR}/${name}")
set(build_dir "${VOID_TEST_ROOT}/${name}")
execute_process(
COMMAND "${CMAKE_COMMAND}" -S "${source_dir}" -B "${build_dir}"
"-DCMAKE_PREFIX_PATH=${install_prefix}"
"-DCMAKE_CXX_COMPILER=${VOID_CXX_COMPILER}"
${ARGN}
COMMAND_ERROR_IS_FATAL ANY)
set(build_command "${CMAKE_COMMAND}" --build "${build_dir}")
set(test_command "${VOID_CTEST_COMMAND}" --test-dir "${build_dir}"
--output-on-failure)
if(DEFINED VOID_BUILD_CONFIG AND NOT VOID_BUILD_CONFIG STREQUAL "")
list(APPEND build_command --config "${VOID_BUILD_CONFIG}")
list(APPEND test_command -C "${VOID_BUILD_CONFIG}")
endif()
execute_process(COMMAND ${build_command} COMMAND_ERROR_IS_FATAL ANY)
execute_process(COMMAND ${test_command} COMMAND_ERROR_IS_FATAL ANY)
endfunction()
# A header-only component must remain independently consumable even when every
# optional external package is explicitly unavailable.
run_consumer(Binary
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE)
# Exercise the transitive dependency closure for every newly extracted runtime
# module while proving unrelated Sodium and SQLite dependencies are not loaded.
run_consumer(Audited
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
# Compiled shared modules keep their third-party implementation dependencies
# private, but every installed runtime library must remain linkable and
# executable from a clean consumer project.
run_consumer(External)
+253
View File
@@ -0,0 +1,253 @@
#include <Void/Archive/Archive.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <array>
#include <atomic>
#include <filesystem>
#include <fstream>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <archive.h>
#include <archive_entry.h>
namespace
{
struct ArchiveEntry {
std::string_view path;
std::string_view contents;
unsigned int type{AE_IFREG};
std::string_view link;
};
void write_archive(const std::filesystem::path &path,
std::span<const ArchiveEntry>
entries)
{
using Writer = std::unique_ptr<archive, decltype(&archive_write_free)>;
using Entry =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
Writer writer{archive_write_new(), &archive_write_free};
Void::Testing::require(static_cast<bool>(writer));
Void::Testing::require(archive_write_add_filter_zstd(writer.get()) ==
ARCHIVE_OK);
Void::Testing::require(archive_write_set_format_pax_restricted(
writer.get()) == ARCHIVE_OK);
#ifdef _WIN32
Void::Testing::require(archive_write_open_filename_w(
writer.get(), path.c_str()) == ARCHIVE_OK);
#else
Void::Testing::require(archive_write_open_filename(
writer.get(), path.c_str()) == ARCHIVE_OK);
#endif
for (const auto &specification : entries) {
Entry entry{archive_entry_new(), &archive_entry_free};
const std::string entryPath{specification.path};
archive_entry_set_pathname(entry.get(), entryPath.c_str());
archive_entry_set_filetype(entry.get(), specification.type);
archive_entry_set_perm(
entry.get(), specification.type == AE_IFDIR ? 0755 : 0644);
if (specification.type == AE_IFREG) {
archive_entry_set_size(
entry.get(),
static_cast<la_int64_t>(specification.contents.size()));
}
if (!specification.link.empty()) {
const std::string link{specification.link};
archive_entry_set_symlink(entry.get(), link.c_str());
}
Void::Testing::require(
archive_write_header(writer.get(), entry.get()) == ARCHIVE_OK);
std::size_t offset = 0;
while (offset < specification.contents.size()) {
const auto count = archive_write_data(
writer.get(), specification.contents.data() + offset,
specification.contents.size() - offset);
Void::Testing::require(count > 0);
offset += static_cast<std::size_t>(count);
}
Void::Testing::require(archive_write_finish_entry(writer.get()) ==
ARCHIVE_OK);
}
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
}
void write_archive(const std::filesystem::path &path,
std::string_view entryPath, std::string_view contents,
unsigned int type = AE_IFREG, std::string_view link = {})
{
const std::array entries{ArchiveEntry{entryPath, contents, type, link}};
write_archive(path, entries);
}
[[nodiscard]] bool
extraction_file_visible(const std::filesystem::path &destination)
{
std::error_code error;
if (std::filesystem::exists(destination / "anchor", error)) {
return true;
}
error.clear();
for (std::filesystem::directory_iterator iterator{destination, error};
!error && iterator != std::filesystem::directory_iterator{};
iterator.increment(error)) {
if (iterator->path().filename().string().starts_with(
".void-archive-")) {
return true;
}
}
return false;
}
} // namespace
Void::Testing::Test archive_extracts_bounded_tar_zstd()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "package.tar.zst";
const auto destination = temporary / "output";
write_archive(source, "bin/tool", "payload");
auto extracted = Void::Archive::extract(source, destination);
Void::Testing::require(extracted.has_value());
Void::Testing::expect_eq(extracted->entries, std::size_t{1});
Void::Testing::expect_eq(extracted->bytes, std::uint64_t{7});
std::ifstream input{destination / "bin/tool"};
std::string contents;
input >> contents;
Void::Testing::expect_eq(contents, std::string{"payload"});
}
Void::Testing::Test archive_accepts_explicit_directory_entries()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "directory.tar.zst";
const auto destination = temporary / "output";
const std::array entries{ArchiveEntry{"bin/", {}, AE_IFDIR},
ArchiveEntry{"bin/tool", "payload"}};
write_archive(source, entries);
auto extracted = Void::Archive::extract(source, destination);
Void::Testing::require(extracted.has_value());
Void::Testing::expect_eq(extracted->entries, std::size_t{2});
Void::Testing::expect_eq(extracted->bytes, std::uint64_t{7});
Void::Testing::expect(std::filesystem::is_directory(destination / "bin"));
std::ifstream input{destination / "bin/tool"};
std::string contents;
input >> contents;
Void::Testing::expect_eq(contents, std::string{"payload"});
}
Void::Testing::Test archive_rejects_traversal_and_links()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto traversal = temporary / "traversal.tar.zst";
write_archive(traversal, "../escape", "bad");
Void::Testing::expect(
!Void::Archive::extract(traversal, temporary / "out1").has_value());
Void::Testing::expect(
!std::filesystem::exists(temporary.path() / "escape"));
const auto symlink = temporary / "symlink.tar.zst";
write_archive(symlink, "link", {}, AE_IFLNK, "/tmp/escape");
Void::Testing::expect(
!Void::Archive::extract(symlink, temporary / "out2").has_value());
const auto trailingFile = temporary / "trailing-file.tar.zst";
write_archive(trailingFile, "file/", "bad");
Void::Testing::expect(
!Void::Archive::extract(trailingFile, temporary / "out3").has_value());
}
Void::Testing::Test archive_rejects_symlink_parent()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "parent-link.tar.zst";
const auto destination = temporary / "output";
const auto outside = temporary / "outside";
std::filesystem::create_directories(destination);
std::filesystem::create_directories(outside);
std::filesystem::create_directory_symlink(outside, destination / "parent");
write_archive(source, "parent/escape", "bad");
Void::Testing::expect(
!Void::Archive::extract(source, destination).has_value());
Void::Testing::expect(!std::filesystem::exists(outside / "escape"));
#else
Void::Testing::expect(true);
#endif
}
Void::Testing::Test archive_pins_destination_during_path_swap()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "swap.tar.zst";
const auto destination = temporary / "output";
const auto displaced = temporary / "displaced";
const auto outside = temporary / "outside";
std::filesystem::create_directories(destination);
std::filesystem::create_directories(outside);
const std::string largePayload(32U * 1024U * 1024U, 'x');
const std::array entries{ArchiveEntry{"anchor", largePayload},
ArchiveEntry{"second", "safe"}};
write_archive(source, entries);
std::atomic_bool extractionFinished{false};
std::atomic_bool swapped{false};
std::jthread attacker{[&] {
while (!extractionFinished.load(std::memory_order_acquire)) {
if (!extraction_file_visible(destination)) {
std::this_thread::yield();
continue;
}
std::error_code error;
std::filesystem::rename(destination, displaced, error);
if (error) {
return;
}
std::filesystem::create_directory_symlink(outside, destination,
error);
if (error) {
std::error_code restoreError;
std::filesystem::rename(displaced, destination, restoreError);
return;
}
swapped.store(true, std::memory_order_release);
return;
}
}};
auto extracted = Void::Archive::extract(source, destination);
extractionFinished.store(true, std::memory_order_release);
attacker.join();
Void::Testing::require(swapped.load(std::memory_order_acquire));
Void::Testing::require(extracted.has_value());
Void::Testing::expect(!std::filesystem::exists(outside / "second"));
Void::Testing::expect(std::filesystem::exists(displaced / "second"));
#else
Void::Testing::expect(true);
#endif
}
Void::Testing::Test archive_enforces_actual_size_limit()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "large.tar.zst";
write_archive(source, "file", "12345678");
Void::Archive::ExtractionOptions options;
options.maxFileBytes = 4;
Void::Testing::expect(
!Void::Archive::extract(source, temporary / "out", options)
.has_value());
Void::Testing::expect(
!std::filesystem::exists(temporary.path() / "out/file"));
}
+31
View File
@@ -0,0 +1,31 @@
#include <Void/Binary/Reader.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <array>
Void::Testing::Test binary_reader_checks_bounds_and_endian()
{
const std::array bytes{std::byte{0x12}, std::byte{0x34}, std::byte{0x56}};
Void::Binary::Reader reader{bytes};
auto value = reader.read<std::uint16_t>(std::endian::big);
Void::Testing::require(value.has_value());
Void::Testing::expect_eq(*value, static_cast<std::uint16_t>(0x1234));
Void::Testing::expect_eq(reader.position(), static_cast<std::size_t>(2));
auto overflow = reader.read<std::uint16_t>(std::endian::big);
Void::Testing::expect(!overflow.has_value());
Void::Testing::expect_eq(reader.position(), static_cast<std::size_t>(2));
}
Void::Testing::Test binary_reader_subreader_is_bounded()
{
const std::array bytes{std::byte{'a'}, std::byte{'b'}, std::byte{'c'}};
Void::Binary::Reader reader{bytes};
auto child = reader.subreader(2);
Void::Testing::require(child.has_value());
auto value = child->readString(2);
Void::Testing::require(value.has_value());
Void::Testing::expect_eq(*value, std::string{"ab"});
Void::Testing::expect(!child->readBytes(1).has_value());
Void::Testing::expect_eq(reader.remaining(), static_cast<std::size_t>(1));
}
+77
View File
@@ -0,0 +1,77 @@
#include <Void/Crypto/Crypto.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Text/Hex.hpp>
#include <array>
#include <fstream>
namespace
{
std::string hex(const Void::Crypto::Digest& digest)
{
return Void::Encoding::Hex::encode(digest);
}
} // namespace
Void::Testing::Test crypto_known_hash_vectors()
{
auto sha1 = Void::Crypto::sha1("abc");
auto sha256 = Void::Crypto::sha256("abc");
auto sha512 = Void::Crypto::sha512("abc");
Void::Testing::require(sha1.has_value());
Void::Testing::require(sha256.has_value());
Void::Testing::require(sha512.has_value());
Void::Testing::expect_eq(
hex(*sha1), std::string{"a9993e364706816aba3e25717850c26c9cd0d89d"});
Void::Testing::expect_eq(hex(*sha256),
std::string{"ba7816bf8f01cfea414140de5dae2223b0036"
"1a396177a9cb410ff61f20015ad"});
Void::Testing::expect_eq(
hex(*sha512),
std::string{
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a21"
"92992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"});
}
Void::Testing::Test crypto_streaming_and_file_hash_match()
{
auto hasher =
Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
Void::Testing::require(hasher.has_value());
Void::Testing::require(hasher->update("ab").has_value());
Void::Testing::require(hasher->update("c").has_value());
auto streamed = hasher->finalize();
Void::Testing::require(streamed.has_value());
Void::Testing::expect(!hasher->update("again").has_value());
Void::FileSystem::TempDir temporary{"void_crypto_"};
const auto path = temporary / "data";
std::ofstream{path, std::ios::binary} << "abc";
auto file = Void::Crypto::sha256File(path);
Void::Testing::require(file.has_value());
Void::Testing::expect_eq(*file, *streamed);
}
Void::Testing::Test crypto_ed25519_rfc8032_vector()
{
const auto publicText = Void::Encoding::Hex::decode(
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
const auto signatureText = Void::Encoding::Hex::decode(
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
"5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
Void::Testing::require(publicText.has_value());
Void::Testing::require(signatureText.has_value());
const auto publicKey =
std::as_bytes(std::span{publicText->data(), publicText->size()});
const auto signature =
std::as_bytes(std::span{signatureText->data(), signatureText->size()});
auto valid = Void::Crypto::verifyEd25519({}, signature, publicKey);
Void::Testing::require(valid.has_value());
Void::Testing::expect(*valid);
const std::array message{std::byte{1}};
auto invalid = Void::Crypto::verifyEd25519(message, signature, publicKey);
Void::Testing::require(invalid.has_value());
Void::Testing::expect(!*invalid);
}
+41
View File
@@ -0,0 +1,41 @@
#include <Void/Data/StrictJson.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <string>
#include <variant>
Void::Testing::Test strict_json_preserves_signed_64_bit_integers()
{
const auto result = Void::Json::Strict::parse(
R"({"minimum":-9223372036854775808,"maximum":9223372036854775807})");
Void::Testing::require(result.has_value());
const auto* object =
std::get_if<Void::Json::Strict::Value::Object>(&result->value);
Void::Testing::require(object != nullptr);
Void::Testing::expect_eq(
std::get<std::int64_t>(object->at("minimum").value), INT64_MIN);
Void::Testing::expect_eq(
std::get<std::int64_t>(object->at("maximum").value), INT64_MAX);
}
Void::Testing::Test strict_json_rejects_duplicates_floats_and_deep_inputs()
{
Void::Testing::expect(
!Void::Json::Strict::parse(R"({"key":1,"key":2})").has_value());
Void::Testing::expect(
!Void::Json::Strict::parse(R"({"value":1.5})").has_value());
Void::Testing::expect(
!Void::Json::Strict::parse("[[[0]]]", 1U).has_value());
}
Void::Testing::Test strict_json_decodes_valid_unicode_pairs()
{
const auto result = Void::Json::Strict::parse(R"("\uD83D\uDE03")");
Void::Testing::require(result.has_value());
Void::Testing::expect_eq(std::get<std::string>(result->value),
std::string{"\xF0\x9F\x98\x83"});
Void::Testing::expect(
!Void::Json::Strict::parse(R"("\uD83D")").has_value());
}
+1 -1
View File
@@ -38,7 +38,7 @@ Void::Testing::Test field_scope_nests()
FieldScope a{"a", "1"};
{
FieldScope b{{{"b", "2"}, {"c", "3"}}};
FieldScope b{{"b", "2"}, {"c", "3"}};
log.info("two scopes");
}
log.info("one scope");
+22 -3
View File
@@ -19,6 +19,25 @@ namespace
std::ifstream f(p);
return {std::istreambuf_iterator<char>(f), {}};
}
std::size_t archive_count(const std::filesystem::path& path)
{
const auto directory = path.parent_path() / "history";
if (!std::filesystem::exists(directory)) {
return 0;
}
const auto prefix = path.stem().string() + "-";
std::size_t count = 0;
for (const auto& entry :
std::filesystem::directory_iterator(directory)) {
const auto filename = entry.path().filename().string();
if (entry.is_regular_file() && filename.starts_with(prefix) &&
entry.path().extension() == path.extension()) {
++count;
}
}
return count;
}
} // namespace
class SplitFileLoggerTests : public Void::Testing::Fixture
@@ -135,8 +154,8 @@ class HistoryLoggerTests : public Void::Testing::Fixture
std::to_string(i));
}
}
auto rotated = path;
rotated += ".1";
Void::Testing::expect(std::filesystem::exists(rotated));
const auto archives = archive_count(path);
Void::Testing::expect(archives >= 1);
Void::Testing::expect(archives <= 3);
}
};
+149 -125
View File
@@ -1,7 +1,7 @@
#include <Void/Log/Sinks.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Fixture.hpp>
#include <Void/Testing/Test.hpp>
@@ -14,170 +14,194 @@
using namespace Void::Logging;
// ── NullLogger / CallbackLogger ───────────────────────────────────────────────
namespace
{
std::size_t archive_count(const std::filesystem::path& path)
{
const auto directory = path.parent_path() / "history";
if (!std::filesystem::exists(directory)) {
return 0;
}
const auto prefix = path.stem().string() + "-";
std::size_t count = 0;
for (const auto& entry :
std::filesystem::directory_iterator(directory)) {
const auto filename = entry.path().filename().string();
if (entry.is_regular_file() && filename.starts_with(prefix) &&
entry.path().extension() == path.extension()) {
++count;
}
}
return count;
}
} // namespace
// ── NullLogger / CallbackLogger
// ───────────────────────────────────────────────
Void::Testing::Test null_logger_swallows_everything()
{
NullLogger log;
log.fatal("into the void");
log.flush();
Void::Testing::expect(true); // reached without crashing
NullLogger log;
log.fatal("into the void");
log.flush();
Void::Testing::expect(true); // reached without crashing
}
Void::Testing::Test callback_logger_receives_entry_fields()
{
Entry got;
CallbackLogger log{[&](const Entry& e) { got = e; },
Mode::Immediate};
log.warning("payload");
Void::Testing::expect(got.level == Level::Warning);
Void::Testing::expect_eq(got.message, std::string{"payload"});
Entry got;
CallbackLogger log{[&](const Entry& e) { got = e; }, Mode::Immediate};
log.warning("payload");
Void::Testing::expect(got.level == Level::Warning);
Void::Testing::expect_eq(got.message, std::string{"payload"});
}
// ── MultiLogger ───────────────────────────────────────────────────────────────
// ── MultiLogger
// ───────────────────────────────────────────────────────────────
Void::Testing::Test multi_logger_fans_out_to_all_children()
{
int a = 0;
int b = 0;
MultiLogger multi;
multi.add(std::make_shared<CallbackLogger>(
[&](const Entry&) { ++a; }, Mode::Immediate));
multi.add(std::make_shared<CallbackLogger>(
[&](const Entry&) { ++b; }, Mode::Immediate));
int a = 0;
int b = 0;
MultiLogger multi;
multi.add(std::make_shared<CallbackLogger>([&](const Entry&) { ++a; },
Mode::Immediate));
multi.add(std::make_shared<CallbackLogger>([&](const Entry&) { ++b; },
Mode::Immediate));
multi.info("to both");
Void::Testing::expect_eq(a, 1);
Void::Testing::expect_eq(b, 1);
Void::Testing::expect_eq(multi.child_count(), std::size_t{2});
multi.info("to both");
Void::Testing::expect_eq(a, 1);
Void::Testing::expect_eq(b, 1);
Void::Testing::expect_eq(multi.child_count(), std::size_t{2});
}
Void::Testing::Test multi_logger_children_keep_own_levels()
{
int verbose_count = 0;
int errors_only = 0;
auto verbose = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++verbose_count; }, Mode::Immediate);
auto strict = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++errors_only; }, Mode::Immediate);
strict->set_level(Level::Error);
int verbose_count = 0;
int errors_only = 0;
auto verbose = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++verbose_count; }, Mode::Immediate);
auto strict = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++errors_only; }, Mode::Immediate);
strict->set_level(Level::Error);
MultiLogger multi;
multi.add(verbose);
multi.add(strict);
MultiLogger multi;
multi.add(verbose);
multi.add(strict);
multi.info("info");
multi.error("error");
Void::Testing::expect_eq(verbose_count, 2);
Void::Testing::expect_eq(errors_only, 1);
multi.info("info");
multi.error("error");
Void::Testing::expect_eq(verbose_count, 2);
Void::Testing::expect_eq(errors_only, 1);
}
Void::Testing::Test multi_logger_relays_async_children_with_flush()
{
int delivered = 0;
auto async_child = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++delivered; }); // Async by default
MultiLogger multi;
multi.add(async_child);
int delivered = 0;
auto async_child = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++delivered; }); // Async by default
MultiLogger multi;
multi.add(async_child);
multi.info("queued in child");
multi.flush(); // flushes children too
Void::Testing::expect_eq(delivered, 1);
multi.info("queued in child");
multi.flush(); // flushes children too
Void::Testing::expect_eq(delivered, 1);
}
// ── ConsoleLogger + Formatter ─────────────────────────────────────────────────
// ── ConsoleLogger + Formatter
// ─────────────────────────────────────────────────
Void::Testing::Test console_logger_uses_installed_formatter()
{
std::ostringstream out;
{
ConsoleLogger log{out, Mode::Immediate};
log.set_formatter(
std::make_shared<PatternFormatter>("{level}>{message}"));
log.info("custom format");
}
Void::Testing::expect_eq(out.str(),
std::string{"Info>custom format\n"});
std::ostringstream out;
{
ConsoleLogger log{out, Mode::Immediate};
log.set_formatter(
std::make_shared<PatternFormatter>("{level}>{message}"));
log.info("custom format");
}
Void::Testing::expect_eq(out.str(), std::string{"Info>custom format\n"});
}
// ── RotatingFileLogger ────────────────────────────────────────────────────────
// ── RotatingFileLogger
// ────────────────────────────────────────────────────────
class RotatingFileLoggerTests : public Void::Testing::Fixture
{
public:
public:
std::filesystem::path dir;
std::filesystem::path file;
std::filesystem::path dir;
std::filesystem::path file;
void setup() override
{
dir = std::filesystem::temp_directory_path() /
"void_rotating_test";
std::filesystem::remove_all(dir);
std::filesystem::create_directories(dir);
file = dir / "app.log";
}
void setup() override
{
dir = std::filesystem::temp_directory_path() / "void_rotating_test";
std::filesystem::remove_all(dir);
std::filesystem::create_directories(dir);
file = dir / "app.log";
}
void teardown() override { std::filesystem::remove_all(dir); }
void teardown() override { std::filesystem::remove_all(dir); }
static std::string slurp(const std::filesystem::path& p)
{
std::ifstream f(p);
return {std::istreambuf_iterator<char>(f), {}};
}
static std::string slurp(const std::filesystem::path& p)
{
std::ifstream f(p);
return {std::istreambuf_iterator<char>(f), {}};
}
Void::Testing::Test writes_and_flushes()
{
{
RotatingFileLogger log{file};
log.info("rotating hello");
}
Void::Testing::expect(slurp(file).find("rotating hello") !=
std::string::npos);
}
Void::Testing::Test writes_and_flushes()
{
{
RotatingFileLogger log{file};
log.info("rotating hello");
}
Void::Testing::expect(slurp(file).find("rotating hello") !=
std::string::npos);
}
Void::Testing::Test rotates_when_size_exceeded()
{
{
RotatingFileLogger::Options opt;
opt.max_bytes = 256;
opt.max_files = 3;
opt.mode = Mode::Immediate;
RotatingFileLogger log{file, opt};
for (int i = 0; i < 40; ++i) {
log.info("a reasonably long line to fill the file " +
std::to_string(i));
}
}
Void::Testing::expect(std::filesystem::exists(file));
auto rotated = file;
rotated += ".1";
Void::Testing::expect(std::filesystem::exists(rotated));
// The bound holds: no file beyond .3
auto beyond = file;
beyond += ".4";
Void::Testing::expect(!std::filesystem::exists(beyond));
}
Void::Testing::Test rotates_when_size_exceeded()
{
{
RotatingFileLogger::Options opt;
opt.max_bytes = 256;
opt.max_files = 3;
opt.mode = Mode::Immediate;
RotatingFileLogger log{file, opt};
for (int i = 0; i < 40; ++i) {
log.info("a reasonably long line to fill the file " +
std::to_string(i));
}
}
Void::Testing::expect(std::filesystem::exists(file));
const auto archives = archive_count(file);
Void::Testing::expect(archives >= 1);
Void::Testing::expect(archives <= 3);
}
Void::Testing::Test open_factory_rejects_bad_path()
{
auto r = RotatingFileLogger::open(
"/this/path/does/not/exist/app.log");
Void::Testing::expect(!r.has_value());
}
Void::Testing::Test open_factory_rejects_bad_path()
{
const auto blocking_parent = dir / "not-a-directory";
{
std::ofstream blocker{blocking_parent};
blocker << "file blocks directory creation";
}
const auto result =
RotatingFileLogger::open(blocking_parent / "app.log");
Void::Testing::expect(!result.has_value());
}
Void::Testing::Test async_rotation_under_load()
{
{
RotatingFileLogger::Options opt;
opt.max_bytes = 512;
opt.max_files = 2;
RotatingFileLogger log{file, opt}; // Async default
for (int i = 0; i < 200; ++i) {
log.info("async rotation line " + std::to_string(i));
}
log.flush();
}
Void::Testing::expect(std::filesystem::exists(file));
}
Void::Testing::Test async_rotation_under_load()
{
{
RotatingFileLogger::Options opt;
opt.max_bytes = 512;
opt.max_files = 2;
RotatingFileLogger log{file, opt}; // Async default
for (int i = 0; i < 200; ++i) {
log.info("async rotation line " + std::to_string(i));
}
log.flush();
}
Void::Testing::expect(std::filesystem::exists(file));
}
};
+330
View File
@@ -0,0 +1,330 @@
#include <Void/Net/Server.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <array>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <memory>
#include <optional>
#include <string>
#include <vector>
namespace
{
using Void::Net::Method;
using Void::Net::Router;
using Void::Net::ServerRequest;
using Void::Net::ServerResponse;
using Void::Net::StaticFileResolver;
using Void::Net::WebSocketClose;
using Void::Net::WebSocketConnection;
using Void::Net::WebSocketConnectionId;
using Void::Net::WebSocketEvents;
using Void::Net::WebSocketSessions;
using Void::Testing::Test;
void write_file(const std::filesystem::path& path, std::string_view body)
{
std::filesystem::create_directories(path.parent_path());
std::ofstream output{path, std::ios::binary};
output << body;
}
struct FakeConnection final : WebSocketConnection {
explicit FakeConnection(std::uint64_t value) : id_{value} {}
[[nodiscard]] WebSocketConnectionId id() const noexcept override
{
return id_;
}
[[nodiscard]] Void::Result::Result<void>
send_text(std::string_view message) override
{
sent_text.emplace_back(message);
return {};
}
[[nodiscard]] Void::Result::Result<void>
send_binary(std::span<const std::byte> message) override
{
sent_binary.emplace_back(message.begin(), message.end());
return {};
}
void close(const WebSocketClose& info) noexcept override
{
closed = true;
close_code = info.code;
}
WebSocketConnectionId id_;
std::vector<std::string> sent_text;
std::vector<std::vector<std::byte>> sent_binary;
bool closed{false};
std::uint16_t close_code{};
};
struct RouterTests : Void::Testing::Suite<RouterTests> {
Test routes_by_method_and_extracts_parameters()
{
Router router;
auto added = router.add(
Method::Get, "/rooms/:room/members/:member",
[](const ServerRequest& request) {
return Void::Result::ok(ServerResponse{
.status = 200,
.body = request.parameters.at("room") + ":" +
request.parameters.at("member")});
});
Void::Testing::require(added.has_value());
auto response = router.dispatch(
ServerRequest{.method = Method::Get,
.path = "/rooms/alpha/members/7?full=1"});
Void::Testing::require(response.has_value());
Void::Testing::require(response->has_value());
Void::Testing::expect_eq((*response)->body,
std::string{"alpha:7"});
auto miss = router.dispatch(ServerRequest{
.method = Method::Post, .path = "/rooms/alpha/members/7"});
Void::Testing::require(miss.has_value());
Void::Testing::expect(!miss->has_value());
}
Test final_catch_all_captures_remaining_path()
{
Router router;
Void::Testing::require(
router
.add(Method::Get, "/assets/*path",
[](const ServerRequest& request) {
return Void::Result::ok(ServerResponse{
.body = request.parameters.at("path")});
})
.has_value());
auto response = router.dispatch(ServerRequest{
.method = Method::Get, .path = "/assets/js/app.js"});
Void::Testing::require(response.has_value());
Void::Testing::require(response->has_value());
Void::Testing::expect_eq((*response)->body,
std::string{"js/app.js"});
}
Test static_route_takes_precedence_over_parameter_route()
{
Router router;
Void::Testing::require(
router
.add(Method::Get, "/rooms/:room",
[](const ServerRequest&) {
return Void::Result::ok(
ServerResponse{.body = "parameter"});
})
.has_value());
Void::Testing::require(
router
.add(Method::Get, "/rooms/new",
[](const ServerRequest&) {
return Void::Result::ok(
ServerResponse{.body = "static"});
})
.has_value());
auto response = router.dispatch(
ServerRequest{.method = Method::Get, .path = "/rooms/new"});
Void::Testing::require(response.has_value());
Void::Testing::require(response->has_value());
Void::Testing::expect_eq((*response)->body,
std::string{"static"});
}
Test rejects_invalid_and_duplicate_patterns()
{
Router router;
auto handler = [](const ServerRequest&) {
return Void::Result::ok(ServerResponse{});
};
Void::Testing::expect(
!router.add(Method::Get, "relative", handler));
Void::Testing::expect(
!router.add(Method::Get, "/bad/*path/tail", handler));
Void::Testing::require(
router.add(Method::Get, "/health", handler).has_value());
Void::Testing::expect(
!router.add(Method::Get, "/health", handler).has_value());
Void::Testing::require(
router.add(Method::Get, "/users/:id", handler).has_value());
Void::Testing::expect(
!router.add(Method::Get, "/users/:name", handler)
.has_value());
}
Test header_lookup_is_case_insensitive()
{
ServerRequest request{
.headers = {{"Content-Type", "application/json"}}};
Void::Testing::require(
request.header("content-type").has_value());
Void::Testing::expect_eq(*request.header("CONTENT-TYPE"),
std::string_view{"application/json"});
}
};
struct StaticFileTests : Void::Testing::Suite<StaticFileTests> {
Test resolves_index_assets_and_content_types()
{
Void::FileSystem::TempDir directory{"void_net_static_"};
write_file(directory / "index.html", "index");
write_file(directory / "assets/app.js", "script");
auto resolver = StaticFileResolver::create(directory.path());
Void::Testing::require(resolver.has_value());
auto index = resolver->resolve("/");
auto script = resolver->resolve("/assets/app.js?v=1");
Void::Testing::require(index.has_value() && index->has_value());
Void::Testing::require(script.has_value() &&
script->has_value());
Void::Testing::expect_eq((*index)->path.filename(),
std::filesystem::path{"index.html"});
Void::Testing::expect_eq(
(*script)->content_type,
std::string_view{"text/javascript; charset=utf-8"});
Void::Testing::expect_eq((*script)->size,
static_cast<std::uintmax_t>(6));
}
Test rejects_plain_encoded_and_backslash_traversal()
{
Void::FileSystem::TempDir directory{"void_net_static_"};
auto resolver = StaticFileResolver::create(directory.path());
Void::Testing::require(resolver.has_value());
Void::Testing::expect(
!resolver->resolve("/../secret").has_value());
Void::Testing::expect(
!resolver->resolve("/%2e%2e/secret").has_value());
Void::Testing::expect(
!resolver->resolve("/..%2fsecret").has_value());
Void::Testing::expect(
!resolver->resolve("/dir%5csecret").has_value());
}
Test missing_file_is_a_successful_empty_result()
{
Void::FileSystem::TempDir directory{"void_net_static_"};
auto resolver = StaticFileResolver::create(directory.path());
Void::Testing::require(resolver.has_value());
auto missing = resolver->resolve("/missing.txt");
Void::Testing::require(missing.has_value());
Void::Testing::expect(!missing->has_value());
}
Test rejects_symlinks_that_escape_the_document_root()
{
Void::FileSystem::TempDir root{"void_net_root_"};
Void::FileSystem::TempDir outside{"void_net_outside_"};
write_file(outside / "secret.txt", "secret");
std::error_code error;
std::filesystem::create_directory_symlink(
outside.path(), root / "escape", error);
if (error) {
Void::Testing::skip(
std::string_view{"directory symlinks are unavailable"});
}
auto resolver = StaticFileResolver::create(root.path());
Void::Testing::require(resolver.has_value());
Void::Testing::expect(
!resolver->resolve("/escape/secret.txt").has_value());
}
};
struct WebSocketTests : Void::Testing::Suite<WebSocketTests> {
Test lifecycle_callbacks_run_outside_registry_lock()
{
WebSocketSessions sessions;
std::size_t opened = 0;
std::string received;
std::uint16_t close_code = 0;
sessions.set_events(WebSocketEvents{
.opened =
[&](const auto& connection) {
++opened;
Void::Testing::expect(
sessions.contains(connection->id()));
},
.text =
[&](const auto& connection, std::string_view message) {
Void::Testing::expect(
sessions.find(connection->id()) != nullptr);
received = message;
},
.closed =
[&](WebSocketConnectionId,
const WebSocketClose& close) {
close_code = close.code;
}});
auto connection = std::make_shared<FakeConnection>(7);
auto accepted = sessions.open(connection);
Void::Testing::require(accepted.has_value() && *accepted);
Void::Testing::expect_eq(opened, static_cast<std::size_t>(1));
Void::Testing::expect(sessions.receive_text({7}, "hello"));
Void::Testing::expect_eq(received, std::string{"hello"});
Void::Testing::expect(
sessions.close({7}, WebSocketClose{1008, "policy"}));
Void::Testing::expect(connection->closed);
Void::Testing::expect_eq(connection->close_code,
static_cast<std::uint16_t>(1008));
Void::Testing::expect_eq(close_code,
static_cast<std::uint16_t>(1008));
Void::Testing::expect_eq(sessions.size(),
static_cast<std::size_t>(0));
}
Test duplicate_and_unknown_connections_are_ignored()
{
WebSocketSessions sessions;
auto first = std::make_shared<FakeConnection>(9);
auto duplicate = std::make_shared<FakeConnection>(9);
auto accepted = sessions.open(first);
auto rejected = sessions.open(duplicate);
Void::Testing::require(accepted.has_value() && *accepted);
Void::Testing::require(rejected.has_value());
Void::Testing::expect(!*rejected);
Void::Testing::expect(!sessions.receive_text({99}, "ignored"));
Void::Testing::expect(!sessions.disconnect({99}));
}
Test transport_disconnect_does_not_close_transport_again()
{
WebSocketSessions sessions;
auto connection = std::make_shared<FakeConnection>(11);
Void::Testing::require(*sessions.open(connection));
Void::Testing::expect(
sessions.disconnect({11}, {1000, "done"}));
Void::Testing::expect(!connection->closed);
}
Test shutdown_closes_every_connection_once()
{
WebSocketSessions sessions;
auto first = std::make_shared<FakeConnection>(1);
auto second = std::make_shared<FakeConnection>(2);
Void::Testing::require(*sessions.open(first));
Void::Testing::require(*sessions.open(second));
Void::Testing::expect_eq(sessions.shutdown(),
static_cast<std::size_t>(2));
Void::Testing::expect(first->closed && second->closed);
Void::Testing::expect_eq(sessions.shutdown(),
static_cast<std::size_t>(0));
auto after_shutdown =
sessions.open(std::make_shared<FakeConnection>(3));
Void::Testing::require(after_shutdown.has_value());
Void::Testing::expect(!*after_shutdown);
}
};
} // namespace
+21
View File
@@ -1,4 +1,5 @@
#include <Void/Plugin/Manager.hpp>
#include <Void/Plugin/Loader.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
@@ -92,4 +93,24 @@ Void::Testing::Test activation_failure_keeps_current_instance()
std::string_view{"accepted"});
}
Void::Testing::Test host_validation_failure_keeps_current_instance()
{
Void::FileSystem::TempDir tmp{"void_cfg_validator"};
const auto so = tmp.path() / "plugin.so";
std::filesystem::copy_file(VOID_CONFIGURABLE_PATH, so);
bool accepted = true;
PluginManager mgr{{.instance_validator = [&accepted](IPlugin&,
const PluginInfo&) { return accepted; }}};
Void::Testing::expect(mgr.load(so).has_value());
auto before = mgr.acquire("ConfigurablePlugin");
accepted = false;
const auto result = mgr.reload("ConfigurablePlugin");
Void::Testing::expect(!result.has_value());
Void::Testing::expect(result.error() == LoadError::ActivationFailed);
auto after = mgr.acquire("ConfigurablePlugin");
Void::Testing::expect(after.get() == before.get());
}
#endif // configurable plugin available
+69
View File
@@ -61,6 +61,41 @@ Void::Testing::Test manager_unknown_plugin_yields_empty_handle()
LoadError::UnknownPlugin);
}
Void::Testing::Test manager_candidate_validator_rejects_initial_load()
{
int validations = 0;
PluginManager manager{
{.candidate_validator = [&](const PluginHandle& candidate) {
++validations;
Void::Testing::expect(static_cast<bool>(candidate));
Void::Testing::expect(candidate.raw_symbol(kInfoSymbol) != nullptr);
return false;
}}};
const auto loaded = manager.load(VOID_STATEFUL_V1_PATH);
Void::Testing::expect(!loaded.has_value());
Void::Testing::expect(loaded.error() == LoadError::ActivationFailed);
Void::Testing::expect_eq(validations, 1);
Void::Testing::expect(!manager.acquire("StatefulPlugin"));
}
Void::Testing::Test manager_candidate_validator_rejects_reload_transactionally()
{
bool accept = true;
PluginManager manager{
{.candidate_validator = [&](const PluginHandle&) { return accept; }}};
Void::Testing::require(manager.load(VOID_STATEFUL_V1_PATH).has_value());
auto before = manager.acquire("StatefulPlugin");
stateful(before)->bump();
accept = false;
const auto replaced =
manager.replace("StatefulPlugin", VOID_STATEFUL_V2_PATH);
Void::Testing::expect(!replaced.has_value());
Void::Testing::expect(replaced.error() == LoadError::ActivationFailed);
auto after = manager.acquire("StatefulPlugin");
Void::Testing::expect_eq(stateful(after)->schema_version(), 1);
Void::Testing::expect_eq(stateful(after)->counter(), 1);
}
Void::Testing::Test manager_reload_migrates_v1_state_to_v2()
{
// Copy v1 into a temp path we control, then overwrite with v2 and
@@ -90,6 +125,40 @@ Void::Testing::Test manager_reload_migrates_v1_state_to_v2()
Void::Testing::expect_eq(stateful(h)->counter(), 3); // migrated
}
Void::Testing::Test manager_replace_migrates_from_immutable_new_path()
{
PluginManager manager;
Void::Testing::require(manager.load(VOID_STATEFUL_V1_PATH).has_value());
auto pinned = manager.acquire("StatefulPlugin");
stateful(pinned)->bump();
stateful(pinned)->bump();
auto replaced = manager.replace("StatefulPlugin", VOID_STATEFUL_V2_PATH);
Void::Testing::require(replaced.has_value());
Void::Testing::expect_eq(stateful(pinned)->schema_version(), 1);
auto current = manager.acquire("StatefulPlugin");
Void::Testing::expect_eq(stateful(current)->schema_version(), 2);
Void::Testing::expect_eq(stateful(current)->counter(), 2);
}
Void::Testing::Test manager_replace_failure_keeps_current_generation()
{
PluginManager manager;
Void::Testing::require(manager.load(VOID_STATEFUL_V1_PATH).has_value());
auto before = manager.acquire("StatefulPlugin");
stateful(before)->bump();
#ifdef VOID_TEST_PLUGIN_PATH
auto mismatch = manager.replace("StatefulPlugin", VOID_TEST_PLUGIN_PATH);
Void::Testing::expect(!mismatch.has_value());
Void::Testing::expect(mismatch.error() == LoadError::NameMismatch);
#endif
auto missing = manager.replace("StatefulPlugin", "/no/such/plugin.so");
Void::Testing::expect(!missing.has_value());
Void::Testing::expect(missing.error() == LoadError::FileNotFound);
auto after = manager.acquire("StatefulPlugin");
Void::Testing::expect_eq(stateful(after)->schema_version(), 1);
Void::Testing::expect_eq(stateful(after)->counter(), 1);
}
Void::Testing::Test manager_pinned_handle_survives_reload()
{
Void::FileSystem::TempDir tmp{"void_mgr"};
+78
View File
@@ -0,0 +1,78 @@
#include <Void/Plugin/Module.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <memory>
#include <string_view>
using namespace Void::Plugin;
namespace
{
class TestModule final : public IModule
{
public:
std::string_view name() const noexcept override
{
return "test.module";
}
Void::Result::Result<void> activate(ModuleHost&) override
{
return {};
}
ModuleReadiness readiness() const override
{
return {.ready = true, .detail = "ready"};
}
};
std::unique_ptr<IModule> createTestModule()
{
return std::make_unique<TestModule>();
}
} // namespace
Void::Testing::Test module_descriptor_uses_void_contract_types()
{
const ModuleDescriptor descriptor{
.module_id = "test.module",
.component_version = {.major = 2, .minor = 0, .patch = 0},
.abi_hash = "sha256:test",
.abi_contract = Void::Json::object({{"schemaVersion", 1}}),
.dependencies =
{
{
.module_id = "echoion.api",
.version_range = "^2.0.0",
.abi_hash = "sha256:api",
},
},
.activation_policy = ActivationPolicy::Reloadable,
.create = createTestModule,
};
Void::Testing::expect(descriptor.validate().has_value());
Void::Testing::expect(
descriptor.dependencies.front().accepts(Void::Semver::Version{
.major = 2,
.minor = 3,
.patch = 0,
.pre_release = {},
.build = {},
}));
Void::Testing::expect(
!descriptor.dependencies.front().accepts(Void::Semver::Version{
.major = 3,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {},
}));
auto module = descriptor.create();
Void::Testing::expect(module != nullptr);
Void::Testing::expect_eq(module->name(), std::string_view{"test.module"});
}
@@ -35,7 +35,7 @@ namespace
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
Void::Testing::expect(rl.allow(2)); // key 2 still full
}
Test refills_per_key_over_time()
@@ -60,16 +60,43 @@ namespace
Test cleanup_drops_stale_keys()
{
KeyedRateLimiter<int> rl{1.0, 1.0};
ManualClock clk;
KeyedRateLimiter<int> rl{1.0, 1.0, clk.fn()};
(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});
clk.advance(2h);
Void::Testing::expect_eq(rl.cleanup(1h), std::size_t{2});
Void::Testing::expect_eq(rl.tracked(), std::size_t{0});
}
Test bounds_untrusted_key_cardinality()
{
ManualClock clk;
KeyedRateLimiter<std::string> rl{2.0, 0.0, clk.fn(),
std::size_t{2}};
Void::Testing::expect(rl.allow("a"));
Void::Testing::expect(rl.allow("b"));
Void::Testing::expect(!rl.allow("c"));
Void::Testing::expect_eq(rl.tracked(), std::size_t{2});
clk.advance(2min);
Void::Testing::expect_eq(rl.cleanup(1min), std::size_t{2});
Void::Testing::expect(rl.allow("c"));
}
Test explicit_time_is_shared_by_tracking_and_refill()
{
ManualClock clk;
KeyedRateLimiter<int> rl{1.0, 1.0, clk.fn(), std::size_t{1}};
const TP start = *clk.now;
Void::Testing::expect(rl.allow_at(1, start));
Void::Testing::expect(!rl.allow_at(1, start));
Void::Testing::expect(rl.allow_at(1, start + 1s));
Void::Testing::expect_eq(rl.cleanup_at(start + 3s, 1s),
std::size_t{1});
}
};
} // namespace
+131
View File
@@ -0,0 +1,131 @@
#include <Void/Security/Security.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <string>
#include <vector>
namespace
{
using Void::Security::PasswordHashStrength;
using Void::Testing::Test;
struct SecurityTests : Void::Testing::Suite<SecurityTests> {
Test random_tokens_are_url_safe_and_unique()
{
auto first = Void::Security::random_token();
auto second = Void::Security::random_token();
Void::Testing::require(first.has_value());
Void::Testing::require(second.has_value());
Void::Testing::expect_eq(first->size(),
static_cast<std::size_t>(43));
Void::Testing::expect(first->find_first_of("+/=") ==
std::string::npos);
Void::Testing::expect_ne(*first, *second);
}
Test random_token_rejects_zero_entropy()
{
Void::Testing::expect(
!Void::Security::random_token(0).has_value());
}
Test token_hash_is_deterministic_and_verifies_in_constant_time()
{
auto first = Void::Security::hash_token("session-secret");
auto second = Void::Security::hash_token("session-secret");
Void::Testing::require(first.has_value());
Void::Testing::require(second.has_value());
Void::Testing::expect_eq(*first, *second);
Void::Testing::expect_eq(first->size(),
static_cast<std::size_t>(64));
auto valid =
Void::Security::verify_token("session-secret", *first);
auto invalid =
Void::Security::verify_token("other-secret", *first);
Void::Testing::require(valid.has_value());
Void::Testing::require(invalid.has_value());
Void::Testing::expect(*valid);
Void::Testing::expect(!*invalid);
}
Test token_verification_rejects_malformed_digest()
{
auto malformed =
Void::Security::verify_token("token", "not-hex");
Void::Testing::require(malformed.has_value());
Void::Testing::expect(!*malformed);
}
Test password_hash_uses_argon2id_and_random_salts()
{
auto first = Void::Security::hash_password(
"correct horse battery staple",
PasswordHashStrength::Interactive);
auto second = Void::Security::hash_password(
"correct horse battery staple",
PasswordHashStrength::Interactive);
Void::Testing::require(first.has_value());
Void::Testing::require(second.has_value());
Void::Testing::expect(first->starts_with("$argon2id$"));
Void::Testing::expect_ne(*first, *second);
}
Test password_verification_accepts_only_the_original_password()
{
auto encoded = Void::Security::hash_password(
"correct horse battery staple",
PasswordHashStrength::Interactive);
Void::Testing::require(encoded.has_value());
auto valid = Void::Security::verify_password(
"correct horse battery staple", *encoded);
auto invalid =
Void::Security::verify_password("incorrect", *encoded);
auto malformed = Void::Security::verify_password(
"correct horse battery staple", "$argon2id$broken");
Void::Testing::require(valid.has_value());
Void::Testing::require(invalid.has_value());
Void::Testing::require(malformed.has_value());
Void::Testing::expect(*valid);
Void::Testing::expect(!*invalid);
Void::Testing::expect(!*malformed);
}
Test sealed_secrets_round_trip_and_use_random_nonces()
{
auto key = Void::Security::random_secret_key();
Void::Testing::require(key.has_value());
const std::vector<unsigned char> plaintext{'s', 'e', 'c',
'r', 'e', 't'};
auto first = Void::Security::seal_secret(plaintext, *key);
auto second = Void::Security::seal_secret(plaintext, *key);
Void::Testing::require(first.has_value());
Void::Testing::require(second.has_value());
Void::Testing::expect_ne(*first, *second);
auto opened = Void::Security::open_secret(*first, *key);
Void::Testing::require(opened.has_value());
Void::Testing::expect_eq(*opened, plaintext);
}
Test sealed_secrets_reject_tampering_and_wrong_keys()
{
auto key = Void::Security::random_secret_key();
auto wrong = Void::Security::random_secret_key();
Void::Testing::require(key.has_value());
Void::Testing::require(wrong.has_value());
const std::vector<unsigned char> plaintext{'t', 'o', 'k', 'e',
'n'};
auto envelope = Void::Security::seal_secret(plaintext, *key);
Void::Testing::require(envelope.has_value());
auto wrong_key = Void::Security::open_secret(*envelope, *wrong);
Void::Testing::expect(!wrong_key.has_value());
envelope->back() ^= 0x01U;
auto tampered = Void::Security::open_secret(*envelope, *key);
Void::Testing::expect(!tampered.has_value());
}
};
} // namespace
+58
View File
@@ -0,0 +1,58 @@
#include <Void/ShortUrl/ShortUrl.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <string>
namespace
{
class Shortener final : public Void::ShortUrl::IShortener
{
public:
[[nodiscard]] std::string_view provider_id() const noexcept override
{
return "test";
}
[[nodiscard]] Void::ShortUrl::Health health() const override
{
return {.status = Void::ShortUrl::HealthStatus::healthy};
}
[[nodiscard]] Void::ShortUrl::ShortenResult
shorten(const Void::ShortUrl::ShortenRequest& request) override
{
return {
.short_url = "https://sho.rt/s/Ab3dE5fG7h",
.key = "Ab3dE5fG7h",
.expires_at_unix_seconds = request.expires_at_unix_seconds,
};
}
};
} // namespace
Void::Testing::Test short_url_service_contract()
{
Shortener shortener;
Void::Testing::expect_eq(shortener.service_name(),
Void::ShortUrl::kServiceId);
Void::Testing::expect_eq(shortener.service_version(), std::uint32_t{1});
Void::Testing::expect_eq(shortener.provider_id(), std::string_view{"test"});
Void::Testing::expect_eq(shortener.health().status,
Void::ShortUrl::HealthStatus::healthy);
auto result = shortener.shorten({.target_url = "https://example.com/a"});
Void::Testing::expect(result.ok());
Void::Testing::expect_eq(result.key, std::string{"Ab3dE5fG7h"});
}
Void::Testing::Test short_url_resolution_is_optional()
{
Shortener shortener;
auto result = shortener.resolve({.key = "Ab3dE5fG7h"});
Void::Testing::expect(!result.ok());
Void::Testing::expect_eq(result.error.code,
Void::ShortUrl::ErrorCode::unsupported);
}
+22
View File
@@ -0,0 +1,22 @@
#include <Void/System/SignalWatcher.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <csignal>
Void::Testing::Test signal_watcher_polls_and_receives_blocked_signal()
{
#ifdef __linux__
auto watcher = Void::Process::SignalWatcher::create({SIGUSR1});
Void::Testing::require(watcher.has_value());
auto empty = watcher->poll();
Void::Testing::require(empty.has_value());
Void::Testing::expect(!empty->has_value());
Void::Testing::require(::raise(SIGUSR1) == 0);
auto received = watcher->wait(std::chrono::milliseconds{100});
Void::Testing::require(received.has_value());
Void::Testing::require(received->has_value());
Void::Testing::expect_eq(**received, SIGUSR1);
#endif
}
+145 -95
View File
@@ -1,240 +1,290 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Text/Base64.hpp>
#include <Void/Text/Hex.hpp>
#include <Void/Text/Html.hpp>
#include <Void/Text/Url.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
// ── Base64 encode ─────────────────────────────────────────────────────────────
#include <array>
#include <cstddef>
#include <cstdint>
#include <span>
// ── Base64 encode
// ─────────────────────────────────────────────────────────────
Void::Testing::Test base64_encode_empty()
{
Void::Testing::expect(Void::Encoding::Base64::encode("").empty());
Void::Testing::expect(Void::Encoding::Base64::encode("").empty());
}
Void::Testing::Test base64_encode_man()
{
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Man"),
std::string{"TWFu"});
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Man"),
std::string{"TWFu"});
}
Void::Testing::Test base64_encode_ma()
{
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"),
std::string{"TWE="});
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Ma"),
std::string{"TWE="});
}
Void::Testing::Test base64_encode_m()
{
Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"),
std::string{"TQ=="});
Void::Testing::expect_eq(Void::Encoding::Base64::encode("M"),
std::string{"TQ=="});
}
Void::Testing::Test base64_encode_hello_world()
{
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"),
std::string{"SGVsbG8sIFdvcmxkIQ=="});
Void::Testing::expect_eq(Void::Encoding::Base64::encode("Hello, World!"),
std::string{"SGVsbG8sIFdvcmxkIQ=="});
}
// ── Base64 decode ─────────────────────────────────────────────────────────────
// ── Base64 decode
// ─────────────────────────────────────────────────────────────
Void::Testing::Test base64_decode_empty()
{
const auto r = Void::Encoding::Base64::decode("");
Void::Testing::expect(r.has_value());
Void::Testing::expect(r->empty());
const auto r = Void::Encoding::Base64::decode("");
Void::Testing::expect(r.has_value());
Void::Testing::expect(r->empty());
}
Void::Testing::Test base64_decode_man()
{
const auto r = Void::Encoding::Base64::decode("TWFu");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Man"});
const auto r = Void::Encoding::Base64::decode("TWFu");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Man"});
}
Void::Testing::Test base64_decode_with_padding()
{
const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ==");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Hello, World!"});
const auto r = Void::Encoding::Base64::decode("SGVsbG8sIFdvcmxkIQ==");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Hello, World!"});
}
Void::Testing::Test base64_decode_invalid_returns_nullopt()
{
const auto r = Void::Encoding::Base64::decode("!!");
Void::Testing::expect(!r.has_value());
const auto r = Void::Encoding::Base64::decode("!!");
Void::Testing::expect(!r.has_value());
}
Void::Testing::Test base64_decode_rejects_malformed_padding()
{
Void::Testing::expect(!Void::Encoding::Base64::decode("T=WE").has_value());
Void::Testing::expect(!Void::Encoding::Base64::decode("TWFu=").has_value());
Void::Testing::expect(!Void::Encoding::Base64::decode("TQ===").has_value());
}
Void::Testing::Test base64_decode_rejects_nonzero_trailing_bits()
{
Void::Testing::expect(!Void::Encoding::Base64::decode("TR==").has_value());
}
Void::Testing::Test base64_round_trip()
{
const std::string original = "The quick brown fox jumps over the lazy dog";
const auto encoded = Void::Encoding::Base64::encode(original);
const auto decoded = Void::Encoding::Base64::decode(encoded);
Void::Testing::expect(decoded.has_value());
Void::Testing::expect_eq(*decoded, original);
const std::string original = "The quick brown fox jumps over the lazy dog";
const auto encoded = Void::Encoding::Base64::encode(original);
const auto decoded = Void::Encoding::Base64::decode(encoded);
Void::Testing::expect(decoded.has_value());
Void::Testing::expect_eq(*decoded, original);
}
// ── Base64 URL ────────────────────────────────────────────────────────────────
Void::Testing::Test base64_byte_buffer_round_trip()
{
const std::array<std::uint8_t, 5> original{0x00, 0x7F, 0x80, 0xFE, 0xFF};
const auto encoded =
Void::Encoding::Base64::encode(std::span<const std::uint8_t>{original});
const auto decoded = Void::Encoding::Base64::decode_bytes(encoded);
Void::Testing::expect(decoded.has_value());
Void::Testing::expect_eq(decoded->size(), original.size());
for (std::size_t i = 0; i < original.size(); ++i) {
Void::Testing::expect_eq(std::to_integer<std::uint8_t>((*decoded)[i]),
original[i]);
}
}
// ── Base64 URL
// ────────────────────────────────────────────────────────────────
Void::Testing::Test base64url_no_padding()
{
const auto s = Void::Encoding::Base64::encode_url("Man");
Void::Testing::expect_eq(s, std::string{"TWFu"});
Void::Testing::expect(s.find('=') == std::string::npos);
const auto s = Void::Encoding::Base64::encode_url("Man");
Void::Testing::expect_eq(s, std::string{"TWFu"});
Void::Testing::expect(s.find('=') == std::string::npos);
}
Void::Testing::Test base64url_no_plus_or_slash()
{
// encode something that would produce + or / in standard base64
const std::string tricky = "\xfb\xff\xfe";
const auto s = Void::Encoding::Base64::encode_url(tricky);
Void::Testing::expect(s.find('+') == std::string::npos);
Void::Testing::expect(s.find('/') == std::string::npos);
// encode something that would produce + or / in standard base64
const std::string tricky = "\xfb\xff\xfe";
const auto s = Void::Encoding::Base64::encode_url(tricky);
Void::Testing::expect(s.find('+') == std::string::npos);
Void::Testing::expect(s.find('/') == std::string::npos);
}
// ── Hex encode ───────────────────────────────────────────────────────────────
Void::Testing::Test hex_encode_empty()
{
Void::Testing::expect(Void::Encoding::Hex::encode("").empty());
Void::Testing::expect(Void::Encoding::Hex::encode("").empty());
}
Void::Testing::Test hex_encode_hello()
{
Void::Testing::expect_eq(Void::Encoding::Hex::encode("Hi"),
std::string{"4869"});
Void::Testing::expect_eq(Void::Encoding::Hex::encode("Hi"),
std::string{"4869"});
}
Void::Testing::Test hex_encode_binary()
{
const std::string bin{'\x00', '\xff', '\xab'};
Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin),
std::string{"00ffab"});
const std::string bin{'\x00', '\xff', '\xab'};
Void::Testing::expect_eq(Void::Encoding::Hex::encode(bin),
std::string{"00ffab"});
}
Void::Testing::Test hex_encode_upper()
{
Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"),
std::string{"4869"});
Void::Testing::expect_eq(Void::Encoding::Hex::encode_upper("Hi"),
std::string{"4869"});
}
// ── Hex decode ───────────────────────────────────────────────────────────────
Void::Testing::Test hex_decode_empty()
{
const auto r = Void::Encoding::Hex::decode("");
Void::Testing::expect(r.has_value());
Void::Testing::expect(r->empty());
const auto r = Void::Encoding::Hex::decode("");
Void::Testing::expect(r.has_value());
Void::Testing::expect(r->empty());
}
Void::Testing::Test hex_decode_hello()
{
const auto r = Void::Encoding::Hex::decode("4869");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Hi"});
const auto r = Void::Encoding::Hex::decode("4869");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Hi"});
}
Void::Testing::Test hex_decode_uppercase()
{
const auto r = Void::Encoding::Hex::decode("4869");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Hi"});
const auto r = Void::Encoding::Hex::decode("4869");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"Hi"});
}
Void::Testing::Test hex_decode_odd_length_fails()
{
Void::Testing::expect(!Void::Encoding::Hex::decode("abc").has_value());
Void::Testing::expect(!Void::Encoding::Hex::decode("abc").has_value());
}
Void::Testing::Test hex_decode_invalid_char_fails()
{
Void::Testing::expect(!Void::Encoding::Hex::decode("zz").has_value());
Void::Testing::expect(!Void::Encoding::Hex::decode("zz").has_value());
}
Void::Testing::Test hex_round_trip()
{
const std::string original = "binary\x00\x01\x02\xff";
const auto encoded = Void::Encoding::Hex::encode(original);
const auto decoded = Void::Encoding::Hex::decode(encoded);
Void::Testing::expect(decoded.has_value());
Void::Testing::expect_eq(*decoded, original);
const std::string original = "binary\x00\x01\x02\xff";
const auto encoded = Void::Encoding::Hex::encode(original);
const auto decoded = Void::Encoding::Hex::decode(encoded);
Void::Testing::expect(decoded.has_value());
Void::Testing::expect_eq(*decoded, original);
}
// ── URL / percent encoding ─────────────────────────────────────────────────────
Void::Testing::Test hex_byte_buffer_round_trip()
{
const std::array<std::uint8_t, 5> original{0x00, 0x7F, 0x80, 0xFE, 0xFF};
const auto encoded =
Void::Encoding::Hex::encode(std::span<const std::uint8_t>{original});
const auto decoded = Void::Encoding::Hex::decode_bytes(encoded);
Void::Testing::expect(decoded.has_value());
Void::Testing::expect_eq(decoded->size(), original.size());
for (std::size_t i = 0; i < original.size(); ++i) {
Void::Testing::expect_eq(std::to_integer<std::uint8_t>((*decoded)[i]),
original[i]);
}
}
// ── URL / percent encoding
// ─────────────────────────────────────────────────────
Void::Testing::Test url_encode_unreserved_passthrough()
{
Void::Testing::expect_eq(Void::Encoding::Url::encode("AZaz09-._~"),
std::string{"AZaz09-._~"});
Void::Testing::expect_eq(Void::Encoding::Url::encode("AZaz09-._~"),
std::string{"AZaz09-._~"});
}
Void::Testing::Test url_encode_reserved()
{
Void::Testing::expect_eq(Void::Encoding::Url::encode("a b/c?d=e&f"),
std::string{"a%20b%2Fc%3Fd%3De%26f"});
Void::Testing::expect_eq(Void::Encoding::Url::encode("a b/c?d=e&f"),
std::string{"a%20b%2Fc%3Fd%3De%26f"});
}
Void::Testing::Test url_query_encode_space_as_plus()
{
Void::Testing::expect_eq(Void::Encoding::Url::query_encode("a b c"),
std::string{"a+b+c"});
Void::Testing::expect_eq(Void::Encoding::Url::query_encode("a b c"),
std::string{"a+b+c"});
}
Void::Testing::Test url_decode_basic()
{
const auto r = Void::Encoding::Url::decode("a%20b%2Fc");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"a b/c"});
const auto r = Void::Encoding::Url::decode("a%20b%2Fc");
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"a b/c"});
}
Void::Testing::Test url_decode_plus_as_space()
{
const auto r = Void::Encoding::Url::decode("a+b", /*plus_as_space=*/true);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"a b"});
const auto r = Void::Encoding::Url::decode("a+b", /*plus_as_space=*/true);
Void::Testing::expect(r.has_value());
Void::Testing::expect_eq(*r, std::string{"a b"});
}
Void::Testing::Test url_decode_malformed_fails()
{
Void::Testing::expect(!Void::Encoding::Url::decode("a%2").has_value());
Void::Testing::expect(!Void::Encoding::Url::decode("a%zz").has_value());
Void::Testing::expect(!Void::Encoding::Url::decode("a%2").has_value());
Void::Testing::expect(!Void::Encoding::Url::decode("a%zz").has_value());
}
Void::Testing::Test url_round_trip_utf8()
{
const std::string original = "café/naïve?x=1 2";
const auto enc = Void::Encoding::Url::encode(original);
const auto dec = Void::Encoding::Url::decode(enc);
Void::Testing::expect(dec.has_value());
Void::Testing::expect_eq(*dec, original);
const std::string original = "café/naïve?x=1 2";
const auto enc = Void::Encoding::Url::encode(original);
const auto dec = Void::Encoding::Url::decode(enc);
Void::Testing::expect(dec.has_value());
Void::Testing::expect_eq(*dec, original);
}
// ── HTML entity decoding ───────────────────────────────────────────────────────
// ── HTML entity decoding
// ───────────────────────────────────────────────────────
Void::Testing::Test html_named_entities()
{
Void::Testing::expect_eq(
Void::Text::html_unescape("a &amp; b &lt; c &gt; d &quot;e&quot;"),
std::string{"a & b < c > d \"e\""});
Void::Testing::expect_eq(
Void::Text::html_unescape("a &amp; b &lt; c &gt; d &quot;e&quot;"),
std::string{"a & b < c > d \"e\""});
}
Void::Testing::Test html_numeric_decimal()
{
Void::Testing::expect_eq(Void::Text::html_unescape("&#65;&#66;&#67;"),
std::string{"ABC"});
Void::Testing::expect_eq(Void::Text::html_unescape("&#65;&#66;&#67;"),
std::string{"ABC"});
}
Void::Testing::Test html_numeric_hex_utf8()
{
// U+1F600 grinning face -> 4-byte UTF-8
const auto r = Void::Text::html_unescape("&#x1F600;");
Void::Testing::expect_eq(r.size(), std::size_t{4});
// U+1F600 grinning face -> 4-byte UTF-8
const auto r = Void::Text::html_unescape("&#x1F600;");
Void::Testing::expect_eq(r.size(), std::size_t{4});
}
Void::Testing::Test html_unknown_left_verbatim()
{
Void::Testing::expect_eq(Void::Text::html_unescape("a &bogus; b"),
std::string{"a &bogus; b"});
Void::Testing::expect_eq(Void::Text::html_unescape("plain & text"),
std::string{"plain & text"});
Void::Testing::expect_eq(Void::Text::html_unescape("a &bogus; b"),
std::string{"a &bogus; b"});
Void::Testing::expect_eq(Void::Text::html_unescape("plain & text"),
std::string{"plain & text"});
}
+114 -69
View File
@@ -4,158 +4,203 @@
#include <string>
// ── parse ─────────────────────────────────────────────────────────────────────
// ── parse
// ─────────────────────────────────────────────────────────────────────
Void::Testing::Test semver_parse_simple()
{
const auto v = Void::Semver::parse("1.2.3");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->major, 1u);
Void::Testing::expect_eq(v->minor, 2u);
Void::Testing::expect_eq(v->patch, 3u);
const auto v = Void::Semver::parse("1.2.3");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->major, 1u);
Void::Testing::expect_eq(v->minor, 2u);
Void::Testing::expect_eq(v->patch, 3u);
}
Void::Testing::Test semver_parse_with_v_prefix()
{
const auto v = Void::Semver::parse("v2.0.0");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->major, 2u);
const auto v = Void::Semver::parse("v2.0.0");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->major, 2u);
}
Void::Testing::Test semver_parse_pre_release()
{
const auto v = Void::Semver::parse("1.0.0-alpha.1");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->pre_release, std::string{"alpha.1"});
const auto v = Void::Semver::parse("1.0.0-alpha.1");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->pre_release, std::string{"alpha.1"});
}
Void::Testing::Test semver_parse_build_metadata()
{
const auto v = Void::Semver::parse("1.0.0+build.123");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->build, std::string{"build.123"});
const auto v = Void::Semver::parse("1.0.0+build.123");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->build, std::string{"build.123"});
}
Void::Testing::Test semver_parse_full()
{
const auto v = Void::Semver::parse("2.3.4-beta.2+20240101");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->major, 2u);
Void::Testing::expect_eq(v->pre_release, std::string{"beta.2"});
Void::Testing::expect_eq(v->build, std::string{"20240101"});
const auto v = Void::Semver::parse("2.3.4-beta.2+20240101");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->major, 2u);
Void::Testing::expect_eq(v->pre_release, std::string{"beta.2"});
Void::Testing::expect_eq(v->build, std::string{"20240101"});
}
Void::Testing::Test semver_parse_invalid()
{
Void::Testing::expect(!Void::Semver::parse("not-a-version").has_value());
Void::Testing::expect(!Void::Semver::parse("1.2").has_value());
Void::Testing::expect(!Void::Semver::parse("not-a-version").has_value());
Void::Testing::expect(!Void::Semver::parse("1.2").has_value());
Void::Testing::expect(!Void::Semver::parse_strict("v1.2.3").has_value());
Void::Testing::expect(!Void::Semver::parse("01.2.3").has_value());
Void::Testing::expect(!Void::Semver::parse("1.2.3-alpha.01").has_value());
Void::Testing::expect(!Void::Semver::parse("1.2.3-alpha..1").has_value());
}
// ── to_string ─────────────────────────────────────────────────────────────────
// ── to_string
// ─────────────────────────────────────────────────────────────────
Void::Testing::Test semver_to_string_simple()
{
Void::Semver::Version v{1, 2, 3};
Void::Testing::expect_eq(v.to_string(), std::string{"1.2.3"});
Void::Semver::Version v{1, 2, 3};
Void::Testing::expect_eq(v.to_string(), std::string{"1.2.3"});
}
Void::Testing::Test semver_to_string_with_pre_release()
{
Void::Semver::Version v{1, 0, 0};
v.pre_release = "alpha";
Void::Testing::expect_eq(v.to_string(), std::string{"1.0.0-alpha"});
Void::Semver::Version v{1, 0, 0};
v.pre_release = "alpha";
Void::Testing::expect_eq(v.to_string(), std::string{"1.0.0-alpha"});
}
Void::Testing::Test semver_round_trip()
{
const auto v = Void::Semver::parse("3.1.4-rc.1+build1");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->to_string(), std::string{"3.1.4-rc.1+build1"});
const auto v = Void::Semver::parse("3.1.4-rc.1+build1");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(v->to_string(), std::string{"3.1.4-rc.1+build1"});
}
// ── comparison ───────────────────────────────────────────────────────────────
Void::Testing::Test semver_compare_major()
{
const auto a = *Void::Semver::parse("2.0.0");
const auto b = *Void::Semver::parse("1.9.9");
Void::Testing::expect(a > b);
const auto a = *Void::Semver::parse("2.0.0");
const auto b = *Void::Semver::parse("1.9.9");
Void::Testing::expect(a > b);
}
Void::Testing::Test semver_compare_minor()
{
const auto a = *Void::Semver::parse("1.2.0");
const auto b = *Void::Semver::parse("1.1.9");
Void::Testing::expect(a > b);
const auto a = *Void::Semver::parse("1.2.0");
const auto b = *Void::Semver::parse("1.1.9");
Void::Testing::expect(a > b);
}
Void::Testing::Test semver_compare_patch()
{
const auto a = *Void::Semver::parse("1.0.1");
const auto b = *Void::Semver::parse("1.0.0");
Void::Testing::expect(a > b);
const auto a = *Void::Semver::parse("1.0.1");
const auto b = *Void::Semver::parse("1.0.0");
Void::Testing::expect(a > b);
}
Void::Testing::Test semver_release_gt_pre_release()
{
const auto a = *Void::Semver::parse("1.0.0");
const auto b = *Void::Semver::parse("1.0.0-alpha");
Void::Testing::expect(a > b);
const auto a = *Void::Semver::parse("1.0.0");
const auto b = *Void::Semver::parse("1.0.0-alpha");
Void::Testing::expect(a > b);
}
Void::Testing::Test semver_equal()
{
const auto a = *Void::Semver::parse("1.2.3");
const auto b = *Void::Semver::parse("1.2.3");
Void::Testing::expect(a == b);
const auto a = *Void::Semver::parse("1.2.3");
const auto b = *Void::Semver::parse("1.2.3");
Void::Testing::expect(a == b);
}
Void::Testing::Test semver_prerelease_precedence_is_spec_compliant()
{
const auto rc2 = *Void::Semver::parse("1.0.0-rc.2");
const auto rc10 = *Void::Semver::parse("1.0.0-rc.10");
const auto numeric = *Void::Semver::parse("1.0.0-1");
const auto alpha = *Void::Semver::parse("1.0.0-alpha");
Void::Testing::expect(rc10 > rc2);
Void::Testing::expect(numeric < alpha);
Void::Testing::expect(*Void::Semver::parse("1.0.0-alpha") <
*Void::Semver::parse("1.0.0-alpha.1"));
}
Void::Testing::Test semver_version_ranges()
{
auto bounded = Void::Semver::parse_range(">=1.2.0 <2.0.0");
auto caret = Void::Semver::parse_range("^1.2.3");
auto wildcard = Void::Semver::parse_range("1.4.x || 2.0.0");
Void::Testing::require(bounded.has_value());
Void::Testing::require(caret.has_value());
Void::Testing::require(wildcard.has_value());
Void::Testing::expect(bounded->contains(*Void::Semver::parse("1.9.9")));
Void::Testing::expect(!bounded->contains(*Void::Semver::parse("2.0.0")));
Void::Testing::expect(caret->contains(*Void::Semver::parse("1.8.0")));
Void::Testing::expect(!caret->contains(*Void::Semver::parse("2.0.0")));
Void::Testing::expect(wildcard->contains(*Void::Semver::parse("1.4.9")));
Void::Testing::expect(wildcard->contains(*Void::Semver::parse("2.0.0")));
}
Void::Testing::Test semver_version_ranges_reject_overflowing_upper_bounds()
{
Void::Testing::expect(
!Void::Semver::parse_range("^4294967295.0.0").has_value());
Void::Testing::expect(
!Void::Semver::parse_range("4294967295.x").has_value());
Void::Testing::expect(
!Void::Semver::parse_range("1.4294967295.x").has_value());
}
// ── bump ─────────────────────────────────────────────────────────────────────
Void::Testing::Test semver_bump_major()
{
const auto v = Void::Semver::Version{1, 2, 3};
const auto b = v.bumped_major();
Void::Testing::expect_eq(b.major, 2u);
Void::Testing::expect_eq(b.minor, 0u);
Void::Testing::expect_eq(b.patch, 0u);
const auto v = Void::Semver::Version{1, 2, 3};
const auto b = v.bumped_major();
Void::Testing::expect_eq(b.major, 2u);
Void::Testing::expect_eq(b.minor, 0u);
Void::Testing::expect_eq(b.patch, 0u);
}
Void::Testing::Test semver_bump_minor()
{
const auto v = Void::Semver::Version{1, 2, 3};
const auto b = v.bumped_minor();
Void::Testing::expect_eq(b.minor, 3u);
Void::Testing::expect_eq(b.patch, 0u);
const auto v = Void::Semver::Version{1, 2, 3};
const auto b = v.bumped_minor();
Void::Testing::expect_eq(b.minor, 3u);
Void::Testing::expect_eq(b.patch, 0u);
}
Void::Testing::Test semver_bump_patch()
{
const auto v = Void::Semver::Version{1, 2, 3};
Void::Testing::expect_eq(v.bumped_patch().patch, 4u);
const auto v = Void::Semver::Version{1, 2, 3};
Void::Testing::expect_eq(v.bumped_patch().patch, 4u);
}
// ── compatible_with ───────────────────────────────────────────────────────────
// ── compatible_with
// ───────────────────────────────────────────────────────────
Void::Testing::Test semver_compatible_same_major()
{
const auto a = *Void::Semver::parse("1.3.0");
const auto req = *Void::Semver::parse("1.2.0");
Void::Testing::expect(a.compatible_with(req));
const auto a = *Void::Semver::parse("1.3.0");
const auto req = *Void::Semver::parse("1.2.0");
Void::Testing::expect(a.compatible_with(req));
}
Void::Testing::Test semver_incompatible_different_major()
{
const auto a = *Void::Semver::parse("2.0.0");
const auto req = *Void::Semver::parse("1.9.9");
Void::Testing::expect(!a.compatible_with(req));
const auto a = *Void::Semver::parse("2.0.0");
const auto req = *Void::Semver::parse("1.9.9");
Void::Testing::expect(!a.compatible_with(req));
}
Void::Testing::Test semver_is_stable()
{
Void::Testing::expect(Void::Semver::Version{1,0,0}.is_stable());
Void::Testing::expect(!Void::Semver::Version{0,9,0}.is_stable());
Void::Semver::Version pre{1,0,0};
pre.pre_release = "alpha";
Void::Testing::expect(!pre.is_stable());
Void::Testing::expect(Void::Semver::Version{1, 0, 0}.is_stable());
Void::Testing::expect(!Void::Semver::Version{0, 9, 0}.is_stable());
Void::Semver::Version pre{1, 0, 0};
pre.pre_release = "alpha";
Void::Testing::expect(!pre.is_stable());
}
+988
View File
@@ -0,0 +1,988 @@
#include <Void/Update/Update.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Text/Base64.hpp>
#include <Void/Text/Hex.hpp>
#include <array>
#include <cstring>
#include <filesystem>
#include <format>
#include <fstream>
#include <iterator>
#include <memory>
#include <openssl/evp.h>
namespace
{
constexpr std::string_view payload = R"json({
"schemaVersion": 1,
"feedId": "vendor-main",
"sequence": 7,
"generatedAt": "2026-01-01T00:00:00Z",
"expiresAt": "2099-01-01T00:00:00Z",
"releases": [{
"component": "service",
"artifactId": "main",
"channel": "stable",
"version": "1.2.0",
"cohort": "linux-abi-2",
"platform": "linux",
"arch": "x86_64",
"url": "https://updates.example.invalid/service-1.2.0.tar.zst",
"size": 1234,
"sha256": "1111111111111111111111111111111111111111111111111111111111111111",
"packageType": "tar.zst",
"compatibility": {
"versionContracts": {"host.api": ">=1.0.0 <2.0.0"},
"exactContracts": {"plugin.abi": "2"}
},
"releaseManifestSha256": "2222222222222222222222222222222222222222222222222222222222222222"
}]
})json";
std::string sign(std::string_view message)
{
const auto seedText = Void::Encoding::Hex::decode(
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
Void::Testing::require(seedText.has_value());
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
Key key{EVP_PKEY_new_raw_private_key(
EVP_PKEY_ED25519, nullptr,
reinterpret_cast<const unsigned char*>(seedText->data()),
seedText->size()),
&EVP_PKEY_free};
Void::Testing::require(static_cast<bool>(key));
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
Void::Testing::require(static_cast<bool>(context));
Void::Testing::require(EVP_DigestSignInit(context.get(), nullptr,
nullptr, nullptr,
key.get()) == 1);
std::string signature(64, '\0');
std::size_t size = signature.size();
Void::Testing::require(
EVP_DigestSign(
context.get(),
reinterpret_cast<unsigned char*>(signature.data()), &size,
reinterpret_cast<const unsigned char*>(message.data()),
message.size()) == 1);
signature.resize(size);
return signature;
}
Void::Update::Keyring keyring()
{
const auto publicText = Void::Encoding::Hex::decode(
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
Void::Testing::require(publicText.has_value());
Void::Update::Ed25519PublicKey key{};
std::memcpy(key.data(), publicText->data(), key.size());
return {{"test-key", key}};
}
std::string envelope(std::string signature)
{
return std::format("{{\"schemaVersion\":1,\"keyId\":\"test-key\","
"\"payload\":\"{}\",\"signature\":\"{}\"}}",
Void::Encoding::Base64::encode_url(payload),
Void::Encoding::Base64::encode_url(signature));
}
std::string signedEnvelope(std::string_view message,
std::uint32_t schemaVersion)
{
return std::format("{{\"schemaVersion\":{},\"keyId\":\"test-key\","
"\"payload\":\"{}\",\"signature\":\"{}\"}}",
schemaVersion,
Void::Encoding::Base64::encode_url(message),
Void::Encoding::Base64::encode_url(sign(message)));
}
std::string signedReadableEnvelope(std::string_view message)
{
return std::format(
"{{\n \"schemaVersion\": 3,\n \"keyId\": \"test-key\",\n"
" \"document\": {},\n \"signedPayload\": \"{}\",\n"
" \"signature\": \"{}\"\n}}",
message, Void::Encoding::Base64::encode_url(message),
Void::Encoding::Base64::encode_url(sign(message)));
}
constexpr std::string_view componentCatalogPayload = R"json({
"schemaVersion": 2,
"document": "echoion-component-catalog",
"channel": "stable",
"sequence": 11,
"generatedAt": "2026-01-01T00:00:00Z",
"expiresAt": "2099-01-01T00:00:00Z",
"productVersion": "2.0.0",
"components": [{
"componentId": "Host",
"pluginId": null,
"kind": "runtime-module",
"componentVersion": "2.0.1",
"activation": "restart-required",
"dependencies": {"Api": ">=2.0.0 <3.0.0"},
"sequence": 11,
"latestUrl": "https://updates.invalid/feeds/stable/host/latest.json",
"artifactSha256": "1111111111111111111111111111111111111111111111111111111111111111"
}, {
"componentId": "Api",
"pluginId": null,
"kind": "sdk",
"componentVersion": "2.0.0",
"activation": "restart-required",
"dependencies": {},
"sequence": 11,
"latestUrl": "https://updates.invalid/feeds/stable/api/latest.json",
"artifactSha256": "2222222222222222222222222222222222222222222222222222222222222222"
}]
})json";
std::string componentReleasePayload(std::string_view componentId,
std::string_view version,
std::string_view artifactHash,
std::string_view dependencies)
{
return std::format(
R"json({{
"schemaVersion": 2,
"document": "echoion-component-release",
"channel": "stable",
"sequence": 11,
"generatedAt": "2026-01-01T00:00:00Z",
"expiresAt": "2099-01-01T00:00:00Z",
"productVersion": "2.0.0",
"componentId": "{}",
"pluginId": null,
"kind": "{}",
"componentVersion": "{}",
"sourceSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"sourceTreeHash": "git-sha1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"abiHash": {},
"artifactIdentity": "{}-{}-linux-x86_64",
"activation": "restart-required",
"platform": "linux",
"architecture": "x86_64",
"toolchainContract": "linux-x86_64-glibc-2.35-cxx26",
"dependencies": {},
"artifact": {{
"name": "{}-{}.tar.zst",
"url": "https://updates.invalid/{}-{}.tar.zst",
"sha256": "{}",
"size": 42,
"manifestSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
"packageType": "tar.zst"
}}
}})json",
componentId, componentId == "Api" ? "sdk" : "runtime-module",
version,
componentId == "Api"
? "null"
: R"("sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc")",
componentId, version, dependencies, componentId, version,
componentId, version, artifactHash);
}
} // namespace
Void::Testing::Test update_feed_verifies_before_parsing()
{
auto verified =
Void::Update::verifyFeedEnvelope(envelope(sign(payload)), keyring());
Void::Testing::require(verified.has_value());
Void::Testing::expect_eq(verified->feed.feedId, std::string{"vendor-main"});
Void::Testing::expect_eq(verified->feed.sequence, std::uint64_t{7});
Void::Testing::expect_eq(verified->feed.releases.size(), std::size_t{1});
Void::Testing::expect_eq(verified->signedPayload, std::string{payload});
auto badSignature = sign(payload);
badSignature.front() ^= 1;
Void::Testing::expect(!Void::Update::verifyFeedEnvelope(
envelope(std::move(badSignature)), keyring())
.has_value());
}
Void::Testing::Test update_feed_unsigned_parse_replay_and_selection()
{
auto parsed = Void::Update::parseFeedPayload(payload);
Void::Testing::require(parsed.has_value());
Void::Update::VerificationPolicy replay;
replay.minimumSequence = 7;
Void::Testing::expect(
!Void::Update::parseFeedPayload(payload, replay).has_value());
auto newer = parsed->releases.front();
newer.version = *Void::Semver::parse("1.3.0");
parsed->releases.push_back(newer);
Void::Update::SelectionRequest request{
.component = "service",
.artifactId = "main",
.channel = "stable",
.environment = {.versionContracts = {{"host.api",
*Void::Semver::parse("1.5.0")}},
.exactContracts = {{"plugin.abi", "2"}},
.platform = "linux",
.architecture = "x86_64"},
.currentVersion = *Void::Semver::parse("1.1.0")};
auto selected = Void::Update::selectRelease(*parsed, request);
Void::Testing::require(selected.has_value());
Void::Testing::expect_eq(selected->version.to_string(),
std::string{"1.3.0"});
request.environment.exactContracts["plugin.abi"] = "3";
Void::Testing::expect(
!Void::Update::selectRelease(*parsed, request).has_value());
}
Void::Testing::Test component_feed_verifies_and_resolves_complete_set()
{
auto envelope = Void::Update::verifyEnvelope(
signedEnvelope(componentCatalogPayload, 2), keyring());
Void::Testing::require(envelope.has_value());
Void::Testing::expect_eq(envelope->schemaVersion, std::uint32_t{2});
auto catalog =
Void::Update::parseComponentCatalogPayload(envelope->signedPayload);
Void::Testing::require(catalog.has_value());
Void::Testing::expect_eq(catalog->components.size(), std::size_t{2});
auto host =
Void::Update::parseComponentReleasePayload(componentReleasePayload(
"Host", "2.0.1",
"1111111111111111111111111111111111111111111111111111111111111111",
R"json({"Api":">=2.0.0 <3.0.0"})json"));
auto api =
Void::Update::parseComponentReleasePayload(componentReleasePayload(
"Api", "2.0.0",
"2222222222222222222222222222222222222222222222222222222222222222",
"{}"));
Void::Testing::require(host.has_value());
Void::Testing::require(api.has_value());
Void::Testing::expect(!api->abiHash.has_value());
Void::Testing::require(host->abiHash.has_value());
Void::Testing::expect_eq(*host->abiHash,
std::string{"sha256:"
"ccccccccccccccccccccccccccccccccccccc"
"ccccccccccccccccccccccccccc"});
Void::Testing::expect_eq(
host->sourceTreeHash,
std::string{"git-sha1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"});
Void::Testing::expect_eq(host->platform, std::string{"linux"});
std::map<std::string, Void::Update::ComponentRelease> releases;
releases.emplace("Api", *api);
releases.emplace("Host", *host);
Void::Testing::expect(
Void::Update::validateComponentSet(*catalog, releases).has_value());
releases.at("Api").componentVersion = *Void::Semver::parse("3.0.0");
Void::Testing::expect(
!Void::Update::validateComponentSet(*catalog, releases).has_value());
}
Void::Testing::Test readable_component_envelope_matches_signed_payload()
{
auto envelope = Void::Update::verifyEnvelope(
signedReadableEnvelope(componentCatalogPayload), keyring());
Void::Testing::require(envelope.has_value());
Void::Testing::expect_eq(envelope->schemaVersion, std::uint32_t{3});
Void::Testing::expect_eq(envelope->signedPayload,
std::string{componentCatalogPayload});
auto tampered = signedReadableEnvelope(componentCatalogPayload);
const auto position = tampered.find("\"sequence\": 11");
Void::Testing::require(position != std::string::npos);
tampered.replace(position, std::string{"\"sequence\": 11"}.size(),
"\"sequence\": 12");
Void::Testing::expect(
!Void::Update::verifyEnvelope(tampered, keyring()).has_value());
}
Void::Testing::Test update_feed_rejects_empty_fractional_timestamp()
{
std::string malformed{payload};
const auto timestamp = malformed.find("2026-01-01T00:00:00Z");
Void::Testing::require(timestamp != std::string::npos);
malformed.replace(timestamp,
std::string_view{"2026-01-01T00:00:00Z"}.size(),
"2026-01-01T00:00:00.Z");
Void::Testing::expect(
!Void::Update::parseFeedPayload(malformed).has_value());
}
Void::Testing::Test update_feed_rejects_noncanonical_sha256()
{
std::string uppercaseArtifactHash{payload};
const auto artifactHash = uppercaseArtifactHash.find(std::string(64, '1'));
Void::Testing::require(artifactHash != std::string::npos);
uppercaseArtifactHash[artifactHash] = 'A';
Void::Testing::expect(
!Void::Update::parseFeedPayload(uppercaseArtifactHash).has_value());
std::string uppercaseManifestHash{payload};
const auto manifestHash = uppercaseManifestHash.find(std::string(64, '2'));
Void::Testing::require(manifestHash != std::string::npos);
uppercaseManifestHash[manifestHash] = 'B';
Void::Testing::expect(
!Void::Update::parseFeedPayload(uppercaseManifestHash).has_value());
}
Void::Testing::Test update_feed_accepts_generic_artifact_kinds()
{
std::string sharedLibrary{payload};
constexpr std::string_view packageField{"\"packageType\": \"tar.zst\""};
const auto package = sharedLibrary.find(packageField);
Void::Testing::require(package != std::string::npos);
sharedLibrary.replace(package, packageField.size(),
"\"packageType\": \"shared-library\"");
const auto manifest = sharedLibrary.find(
",\n \"releaseManifestSha256\": "
"\"2222222222222222222222222222222222222222222222222222222222222222\"");
Void::Testing::require(manifest != std::string::npos);
sharedLibrary.erase(manifest,
std::string_view{",\n \"releaseManifestSha256\": "
"\"22222222222222222222222222222222222"
"22222222222222222222222222222\""}
.size());
auto parsed = Void::Update::parseFeedPayload(sharedLibrary);
Void::Testing::require(parsed.has_value());
Void::Testing::require(parsed->releases.size() == 1);
Void::Testing::expect_eq(parsed->releases.front().packageType,
std::string{"shared-library"});
Void::Testing::expect(
parsed->releases.front().releaseManifestSha256.empty());
const Void::Update::SelectionRequest request{
.component = "service",
.artifactId = "main",
.channel = "stable",
.environment = {.versionContracts = {{"host.api",
*Void::Semver::parse("1.5.0")}},
.exactContracts = {{"plugin.abi", "2"}},
.platform = "linux",
.architecture = "x86_64"},
.currentVersion = std::nullopt,
.requiredCohort = std::nullopt,
.allowDowngrade = false,
.includeCurrent = false};
const auto selected = Void::Update::selectRelease(*parsed, request);
Void::Testing::require(selected.has_value());
Void::Testing::expect_eq(selected->packageType,
std::string{"shared-library"});
const auto packageType = sharedLibrary.find("shared-library");
Void::Testing::require(packageType != std::string::npos);
sharedLibrary.replace(packageType,
std::string_view{"shared-library"}.size(), "file");
const auto fileFeed = Void::Update::parseFeedPayload(sharedLibrary);
Void::Testing::require(fileFeed.has_value());
Void::Testing::expect_eq(fileFeed->releases.front().packageType,
std::string{"file"});
const auto filePackageType = sharedLibrary.find("file");
Void::Testing::require(filePackageType != std::string::npos);
sharedLibrary.replace(filePackageType, std::string_view{"file"}.size(),
"wasm-module");
const auto wasmFeed = Void::Update::parseFeedPayload(sharedLibrary);
Void::Testing::require(wasmFeed.has_value());
Void::Testing::expect_eq(wasmFeed->releases.front().packageType,
std::string{"wasm-module"});
}
Void::Testing::Test version_store_commits_and_reconciles_activation()
{
Void::FileSystem::TempDir temporary{"void_versions_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const auto version1 = *Void::Semver::parse("1.0.0");
const auto version2 = *Void::Semver::parse("2.0.0");
auto staging1 = store.prepare(version1);
Void::Testing::require(staging1.has_value());
std::ofstream{*staging1 / "marker"} << "one";
Void::Testing::require(store.publish(version1, *staging1).has_value());
Void::Testing::require(store.activate(version1).has_value());
Void::Testing::require(store.commit().has_value());
auto staging2 = store.prepare(version2);
Void::Testing::require(staging2.has_value());
std::ofstream{*staging2 / "marker"} << "two";
Void::Testing::require(store.publish(version2, *staging2).has_value());
Void::Testing::require(store.activate(version2).has_value());
Void::Testing::expect(!store.recordHealthy(version2).has_value());
auto current = store.currentVersion();
Void::Testing::require(current.has_value() && current->has_value());
Void::Testing::expect_eq((*current)->to_string(), std::string{"2.0.0"});
Void::Testing::require(store.reconcile().has_value());
current = store.currentVersion();
Void::Testing::require(current.has_value() && current->has_value());
Void::Testing::expect_eq((*current)->to_string(), std::string{"1.0.0"});
Void::Testing::expect(!store.pendingActivation()->has_value());
}
Void::Testing::Test version_store_commit_point_is_unambiguous_and_idempotent()
{
Void::FileSystem::TempDir temporary{"void_versions_commit_point_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const auto version = *Void::Semver::parse("2.1.0");
auto staging = store.prepare(version);
Void::Testing::require(staging.has_value());
std::ofstream{*staging / "marker"} << "candidate";
Void::Testing::require(store.publish(version, *staging).has_value());
Void::Testing::require(store.activate(version).has_value());
Void::Testing::require(store.commit().has_value());
Void::Testing::expect(
!std::filesystem::exists(store.root() / "activation.json"));
Void::Testing::require(store.commit().has_value());
std::ifstream healthInput{store.root() / "health.log"};
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
std::istreambuf_iterator<char>{}};
const auto healthyRecord = healthHistory.find("H 2.1.0\n");
Void::Testing::require(healthyRecord != std::string::npos);
Void::Testing::expect(healthHistory.find("H 2.1.0\n", healthyRecord + 1) ==
std::string::npos);
Void::Testing::require(store.rollback().has_value());
const auto current = store.currentVersion();
Void::Testing::require(current.has_value() && current->has_value());
Void::Testing::expect_eq((*current)->to_string(), std::string{"2.1.0"});
}
Void::Testing::Test version_store_reconciles_durable_commit_marker()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_versions_commit_marker_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const auto version = *Void::Semver::parse("2.2.0");
auto staging = store.prepare(version);
Void::Testing::require(staging.has_value());
std::ofstream{*staging / "marker"} << "candidate";
Void::Testing::require(store.publish(version, *staging).has_value());
Void::Testing::require(store.activate(version).has_value());
std::ifstream healthInput{store.root() / "health.log"};
std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
std::istreambuf_iterator<char>{}};
healthHistory += "H 2.2.0\n";
const auto replacement = store.root() / "health.replacement";
std::ofstream{replacement, std::ios::binary | std::ios::trunc}
<< healthHistory;
std::filesystem::rename(replacement, store.root() / "health.log");
Void::Testing::expect(
std::filesystem::exists(store.root() / "activation.json"));
const auto healthyRecord = healthHistory.find("H 2.2.0\n");
Void::Testing::require(healthyRecord != std::string::npos);
Void::Testing::expect(healthHistory.find("H 2.2.0\n", healthyRecord + 1) ==
std::string::npos);
Void::Testing::require(store.rollback().has_value());
const auto committedCurrent = store.currentVersion();
Void::Testing::require(committedCurrent.has_value() &&
committedCurrent->has_value());
Void::Testing::expect_eq((*committedCurrent)->to_string(),
std::string{"2.2.0"});
Void::Testing::require(store.reconcile().has_value());
Void::Testing::expect(
!std::filesystem::exists(store.root() / "activation.json"));
const auto reconciledCurrent = store.currentVersion();
Void::Testing::require(reconciledCurrent.has_value() &&
reconciledCurrent->has_value());
Void::Testing::expect_eq((*reconciledCurrent)->to_string(),
std::string{"2.2.0"});
#endif
}
Void::Testing::Test version_store_reactivation_refreshes_health_order()
{
Void::FileSystem::TempDir temporary{"void_versions_reactivation_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
for (const std::string_view text : {"1.0.0", "2.0.0", "3.0.0"}) {
const auto version = *Void::Semver::parse(text);
auto staging = store.prepare(version);
Void::Testing::require(staging.has_value());
std::ofstream{*staging / "marker"} << text;
Void::Testing::require(store.publish(version, *staging).has_value());
Void::Testing::require(store.activate(version).has_value());
Void::Testing::require(store.commit().has_value());
}
const auto reactivated = *Void::Semver::parse("1.0.0");
Void::Testing::require(store.activate(reactivated).has_value());
Void::Testing::require(store.commit().has_value());
const auto removed = store.prune(1);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{1});
Void::Testing::expect_eq(removed->front().to_string(),
std::string{"2.0.0"});
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(reactivated)));
Void::Testing::expect(std::filesystem::is_directory(
store.versionPath(*Void::Semver::parse("3.0.0"))));
}
Void::Testing::Test version_store_records_external_lifecycle_without_staging()
{
Void::FileSystem::TempDir temporary{"void_versions_external_lifecycle_"};
Void::Update::VersionStore store{temporary.path() / "store"};
std::filesystem::create_directories(store.root() / "versions");
for (const std::string_view text :
{"1.0.0", "2.0.0", "3.0.0", "4.0.0", "5.0.0"}) {
std::filesystem::create_directories(
store.versionPath(*Void::Semver::parse(text)));
}
const auto version1 = *Void::Semver::parse("1.0.0");
const auto version2 = *Void::Semver::parse("2.0.0");
const auto version3 = *Void::Semver::parse("3.0.0");
const auto version4 = *Void::Semver::parse("4.0.0");
const auto version5 = *Void::Semver::parse("5.0.0");
Void::Testing::require(store.recordHealthy(version1).has_value());
Void::Testing::require(store.recordHealthy(version2).has_value());
Void::Testing::require(store.recordHealthy(version3).has_value());
Void::Testing::require(store.recordHealthy(version1).has_value());
Void::Testing::require(store.recordFailed(version2).has_value());
Void::Testing::require(store.recordFailed(version4).has_value());
Void::Testing::expect(!std::filesystem::exists(store.root() / "staging"));
std::ifstream healthInput{store.root() / "health.log"};
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
std::istreambuf_iterator<char>{}};
Void::Testing::expect(healthHistory.find("F 2.0.0\n") == std::string::npos);
Void::Testing::expect(healthHistory.find("F 4.0.0\n") != std::string::npos);
#ifndef _WIN32
const auto external = temporary.path() / "external";
std::filesystem::create_directories(external);
const auto linkedVersion = *Void::Semver::parse("6.0.0");
std::filesystem::create_directory_symlink(external,
store.versionPath(linkedVersion));
Void::Testing::expect(!store.recordHealthy(linkedVersion).has_value());
std::filesystem::create_directory_symlink(
std::filesystem::path{"versions"} / version1.to_string(),
store.root() / "current");
const auto removed = store.prune(1);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{2});
Void::Testing::expect(
!std::filesystem::exists(store.versionPath(version2)));
Void::Testing::expect(
!std::filesystem::exists(store.versionPath(version4)));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(version1)));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(version3)));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(version5)));
Void::Testing::expect(std::filesystem::is_directory(external));
Void::Testing::expect(
std::filesystem::is_symlink(store.versionPath(linkedVersion)));
Void::Testing::expect(!std::filesystem::exists(store.root() / "staging"));
#else
(void)version5;
#endif
}
Void::Testing::Test version_store_prunes_without_an_active_version()
{
Void::FileSystem::TempDir temporary{"void_versions_no_current_"};
Void::Update::VersionStore store{temporary.path() / "store"};
std::filesystem::create_directories(store.root() / "versions");
for (const std::string_view text : {"1.0.0", "2.0.0", "3.0.0", "4.0.0"}) {
std::filesystem::create_directories(
store.versionPath(*Void::Semver::parse(text)));
}
const auto version1 = *Void::Semver::parse("1.0.0");
const auto version2 = *Void::Semver::parse("2.0.0");
const auto version3 = *Void::Semver::parse("3.0.0");
const auto version4 = *Void::Semver::parse("4.0.0");
Void::Testing::require(store.recordHealthy(version1).has_value());
Void::Testing::require(store.recordHealthy(version2).has_value());
Void::Testing::require(store.recordFailed(version3).has_value());
auto removed = store.prune(1);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{2});
Void::Testing::expect(
!std::filesystem::exists(store.versionPath(version1)));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(version2)));
Void::Testing::expect(
!std::filesystem::exists(store.versionPath(version3)));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(version4)));
// A retired SemVer may be republished by an external lifecycle owner. Its
// earlier healthy event belongs to the retired publication, so a failure in
// the new publication must still be recorded and prunable.
std::filesystem::create_directories(store.versionPath(version1));
Void::Testing::require(store.recordFailed(version1).has_value());
std::ifstream healthInput{store.root() / "health.log"};
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
std::istreambuf_iterator<char>{}};
const auto retired = healthHistory.find("D 1.0.0\n");
Void::Testing::require(retired != std::string::npos);
Void::Testing::expect(healthHistory.find("F 1.0.0\n", retired) !=
std::string::npos);
removed = store.prune(1);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{1});
Void::Testing::expect(
!std::filesystem::exists(store.versionPath(version1)));
}
Void::Testing::Test version_store_reports_healthy_publications_in_event_order()
{
Void::FileSystem::TempDir temporary{"void_versions_healthy_query_"};
Void::Update::VersionStore store{temporary.path() / "store"};
std::filesystem::create_directories(store.root() / "versions");
const auto version1 = *Void::Semver::parse("1.0.0");
const auto version2 = *Void::Semver::parse("2.0.0");
const auto version3 = *Void::Semver::parse("3.0.0");
const auto version4 = *Void::Semver::parse("4.0.0");
const auto version5 = *Void::Semver::parse("5.0.0");
for (const auto& version :
{version1, version2, version3, version4, version5}) {
std::filesystem::create_directories(store.versionPath(version));
}
Void::Testing::require(store.recordHealthy(version1).has_value());
Void::Testing::require(store.recordHealthy(version2).has_value());
Void::Testing::require(store.recordHealthy(version3).has_value());
Void::Testing::require(store.recordHealthy(version1).has_value());
Void::Testing::require(store.recordFailed(version4).has_value());
#ifndef _WIN32
const auto readable = std::filesystem::perms::owner_read |
std::filesystem::perms::group_read |
std::filesystem::perms::others_read;
Void::Testing::expect(
(std::filesystem::status(store.root() / ".update.lock").permissions() &
readable) == readable);
Void::Testing::expect(
(std::filesystem::status(store.root() / "health.log").permissions() &
readable) == readable);
#endif
auto healthy = store.healthyPublishedVersions();
Void::Testing::require(healthy.has_value());
Void::Testing::expect_eq(healthy->size(), std::size_t{3});
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"1.0.0"});
Void::Testing::expect_eq((*healthy)[1].to_string(), std::string{"3.0.0"});
Void::Testing::expect_eq((*healthy)[2].to_string(), std::string{"2.0.0"});
// Pruning retires an older healthy lifecycle and excludes failed and
// retired publications. Unknown publications remain on disk but are not
// reported as rollback candidates.
Void::Testing::require(store.prune(2).has_value());
healthy = store.healthyPublishedVersions();
Void::Testing::require(healthy.has_value());
Void::Testing::expect_eq(healthy->size(), std::size_t{2});
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"1.0.0"});
Void::Testing::expect_eq((*healthy)[1].to_string(), std::string{"3.0.0"});
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(version5)));
std::filesystem::create_directories(store.versionPath(version2));
Void::Testing::require(store.recordFailed(version2).has_value());
healthy = store.healthyPublishedVersions();
Void::Testing::require(healthy.has_value());
Void::Testing::expect_eq(healthy->size(), std::size_t{2});
Void::Testing::require(store.recordHealthy(version2).has_value());
healthy = store.healthyPublishedVersions();
Void::Testing::require(healthy.has_value());
Void::Testing::expect_eq(healthy->size(), std::size_t{3});
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"2.0.0"});
std::filesystem::remove_all(store.versionPath(version1));
healthy = store.healthyPublishedVersions();
Void::Testing::require(healthy.has_value());
Void::Testing::expect_eq(healthy->size(), std::size_t{2});
Void::Testing::expect_eq((*healthy)[0].to_string(), std::string{"2.0.0"});
Void::Testing::expect_eq((*healthy)[1].to_string(), std::string{"3.0.0"});
}
Void::Testing::Test version_store_prune_never_synthesizes_health()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_versions_prune_health_"};
Void::Update::VersionStore store{temporary.path() / "store"};
std::filesystem::create_directories(store.root() / "versions");
const auto failed = *Void::Semver::parse("1.0.0");
const auto healthy = *Void::Semver::parse("2.0.0");
std::filesystem::create_directories(store.versionPath(failed));
std::filesystem::create_directories(store.versionPath(healthy));
Void::Testing::require(store.recordFailed(failed).has_value());
Void::Testing::require(store.recordHealthy(healthy).has_value());
std::filesystem::create_directory_symlink(
std::filesystem::path{"versions"} / failed.to_string(),
store.root() / "current");
Void::Testing::require(store.prune(1).has_value());
std::ifstream healthInput{store.root() / "health.log"};
const std::string healthHistory{std::istreambuf_iterator<char>{healthInput},
std::istreambuf_iterator<char>{}};
Void::Testing::expect(healthHistory.find("H 1.0.0\n") == std::string::npos);
std::filesystem::remove(store.root() / "current");
std::filesystem::create_directory_symlink(
std::filesystem::path{"versions"} / healthy.to_string(),
store.root() / "current");
const auto removed = store.prune(0);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{1});
Void::Testing::expect(!std::filesystem::exists(store.versionPath(failed)));
#endif
}
Void::Testing::Test version_store_compacts_health_history_atomically()
{
Void::FileSystem::TempDir temporary{"void_versions_health_compaction_"};
Void::Update::VersionStore store{temporary.path() / "store"};
std::filesystem::create_directories(store.root() / "versions");
const auto version1 = *Void::Semver::parse("1.0.0");
const auto version2 = *Void::Semver::parse("2.0.0");
std::filesystem::create_directories(store.versionPath(version1));
std::filesystem::create_directories(store.versionPath(version2));
{
std::ofstream history{store.root() / "health.log",
std::ios::binary | std::ios::trunc};
for (std::size_t index = 0; index < 100'000; ++index) {
history << "H 1.0.0\n";
}
}
Void::Testing::require(store.recordHealthy(version2).has_value());
Void::Testing::expect(
std::filesystem::file_size(store.root() / "health.log") < 1024);
const auto removed = store.prune(1);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{1});
Void::Testing::expect_eq(removed->front().to_string(),
std::string{"1.0.0"});
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(version2)));
}
Void::Testing::Test version_store_rejects_unsafe_activation_journal()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_versions_journal_safety_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const auto external = temporary.path() / "external-activation.json";
std::ofstream{external}
<< R"({"schemaVersion":1,"previousVersion":null,"candidateVersion":"1.0.0"})";
std::filesystem::create_symlink(external, store.root() / "activation.json");
Void::Testing::expect(!store.pendingActivation().has_value());
Void::Testing::expect(std::filesystem::is_regular_file(external));
std::filesystem::remove(store.root() / "activation.json");
{
std::ofstream oversized{store.root() / "activation.json",
std::ios::binary | std::ios::trunc};
oversized.seekp(128 * 1024);
oversized.put('\0');
}
Void::Testing::expect(!store.pendingActivation().has_value());
std::filesystem::remove(store.root() / "activation.json");
std::ofstream{store.root() / "activation.json"}
<< R"({"schemaVersion":1,"previousVersion":null,"candidateVersion":"1.0.0"})";
Void::Testing::expect(!store.pendingActivation().has_value());
#endif
}
Void::Testing::Test version_store_prunes_only_unprotected_real_versions()
{
Void::FileSystem::TempDir temporary{"void_versions_prune_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const std::array versionTexts{"1.0.0", "2.0.0", "3.0.0", "4.0.0"};
for (const std::string_view text : versionTexts) {
const auto version = *Void::Semver::parse(text);
auto staging = store.prepare(version);
Void::Testing::require(staging.has_value());
std::ofstream{*staging / "marker"} << text;
Void::Testing::require(store.publish(version, *staging).has_value());
Void::Testing::require(store.activate(version).has_value());
Void::Testing::require(store.commit().has_value());
}
const auto active = *Void::Semver::parse("4.0.0");
const auto staged = store.prepare(*Void::Semver::parse("8.0.0"));
Void::Testing::require(staged.has_value());
std::ofstream{*staged / "keep"} << "staging";
const auto uncommitted = *Void::Semver::parse("7.0.0");
auto uncommittedStaging = store.prepare(uncommitted);
Void::Testing::require(uncommittedStaging.has_value());
std::ofstream{*uncommittedStaging / "marker"} << "uncommitted";
Void::Testing::require(
store.publish(uncommitted, *uncommittedStaging).has_value());
#ifndef _WIN32
const auto external = temporary.path() / "external";
std::filesystem::create_directories(external);
std::ofstream{external / "keep"} << "outside";
std::filesystem::create_directory_symlink(
external, store.versionPath(*Void::Semver::parse("1.0.0")) / "linked");
std::filesystem::create_directory_symlink(
external, store.versionPath(*Void::Semver::parse("9.0.0")));
const auto orphanedQuarantine = store.root() / "versions" / ".prune.orphan";
std::filesystem::create_directories(orphanedQuarantine);
std::filesystem::create_directory_symlink(external,
orphanedQuarantine / "linked");
#endif
auto removed = store.prune(2);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{1});
Void::Testing::expect_eq(removed->front().to_string(),
std::string{"1.0.0"});
Void::Testing::expect(!std::filesystem::exists(
store.versionPath(*Void::Semver::parse("1.0.0"))));
for (const std::string_view text : {"2.0.0", "3.0.0", "4.0.0"}) {
Void::Testing::expect(std::filesystem::is_directory(
store.versionPath(*Void::Semver::parse(text))));
}
Void::Testing::expect(std::filesystem::exists(*staged / "keep"));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(uncommitted)));
#ifndef _WIN32
Void::Testing::expect(std::filesystem::exists(external / "keep"));
Void::Testing::expect(!std::filesystem::exists(orphanedQuarantine));
Void::Testing::expect(std::filesystem::is_symlink(
store.versionPath(*Void::Semver::parse("9.0.0"))));
#endif
const auto candidate = *Void::Semver::parse("5.0.0");
auto candidateStaging = store.prepare(candidate);
Void::Testing::require(candidateStaging.has_value());
std::ofstream{*candidateStaging / "marker"} << "candidate";
Void::Testing::require(
store.publish(candidate, *candidateStaging).has_value());
Void::Testing::require(store.activate(candidate).has_value());
removed = store.prune(0);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{2});
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(candidate)));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(active)));
Void::Testing::expect(std::filesystem::exists(*staged / "keep"));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(uncommitted)));
Void::Testing::require(store.rollback().has_value());
const auto current = store.currentVersion();
Void::Testing::require(current.has_value() && current->has_value());
Void::Testing::expect_eq((*current)->to_string(), std::string{"4.0.0"});
removed = store.prune(0);
Void::Testing::require(removed.has_value());
Void::Testing::expect_eq(removed->size(), std::size_t{1});
Void::Testing::expect_eq(removed->front().to_string(),
std::string{"5.0.0"});
Void::Testing::expect(
!std::filesystem::exists(store.versionPath(candidate)));
Void::Testing::expect(
std::filesystem::is_directory(store.versionPath(uncommitted)));
}
Void::Testing::Test version_store_rejects_symlink_layout()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_versions_links_"};
const auto target = temporary.path() / "target";
std::filesystem::create_directories(target);
const auto linkedRoot = temporary.path() / "linked-store";
std::filesystem::create_directory_symlink(target, linkedRoot);
Void::Update::VersionStore rootStore{linkedRoot};
Void::Testing::expect(!rootStore.initialize().has_value());
const auto versionsRoot = temporary.path() / "versions-store";
std::filesystem::create_directories(versionsRoot / "staging");
std::filesystem::create_directory_symlink(target,
versionsRoot / "versions");
Void::Update::VersionStore versionsStore{versionsRoot};
Void::Testing::expect(!versionsStore.initialize().has_value());
const auto stagingRoot = temporary.path() / "staging-store";
std::filesystem::create_directories(stagingRoot / "versions");
std::filesystem::create_directory_symlink(target, stagingRoot / "staging");
Void::Update::VersionStore stagingStore{stagingRoot};
Void::Testing::expect(!stagingStore.initialize().has_value());
#endif
}
Void::Testing::Test version_store_publish_requires_immediate_real_child()
{
Void::FileSystem::TempDir temporary{"void_versions_publish_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const auto nested = store.root() / "staging" / "nested" / "candidate";
std::filesystem::create_directories(nested);
const auto version1 = *Void::Semver::parse("3.0.0");
Void::Testing::expect(!store.publish(version1, nested).has_value());
#ifndef _WIN32
const auto external = temporary.path() / "external-candidate";
std::filesystem::create_directories(external);
const auto linked = store.root() / "staging" / "linked-candidate";
std::filesystem::create_directory_symlink(external, linked);
const auto version2 = *Void::Semver::parse("3.1.0");
Void::Testing::expect(!store.publish(version2, linked).has_value());
#endif
}
Void::Testing::Test version_store_activate_rejects_symlink_version()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_versions_activate_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const auto external = temporary.path() / "external-version";
std::filesystem::create_directories(external);
const auto version = *Void::Semver::parse("4.0.0");
std::filesystem::create_directory_symlink(external,
store.versionPath(version));
Void::Testing::expect(!store.activate(version).has_value());
Void::Testing::expect(
!std::filesystem::exists(store.root() / "activation.json"));
#endif
}
Void::Testing::Test version_store_rollback_revalidates_previous_version()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_versions_rollback_links_"};
Void::Update::VersionStore store{temporary.path() / "store"};
Void::Testing::require(store.initialize().has_value());
const auto version1 = *Void::Semver::parse("1.0.0");
const auto version2 = *Void::Semver::parse("2.0.0");
for (const auto& version : {version1, version2}) {
auto staging = store.prepare(version);
Void::Testing::require(staging.has_value());
std::ofstream{*staging / "marker"} << version.to_string();
Void::Testing::require(store.publish(version, *staging).has_value());
}
Void::Testing::require(store.activate(version1).has_value());
Void::Testing::require(store.commit().has_value());
Void::Testing::require(store.activate(version2).has_value());
const auto external = temporary.path() / "external-previous";
std::filesystem::create_directories(external);
std::filesystem::remove_all(store.versionPath(version1));
std::filesystem::create_directory_symlink(external,
store.versionPath(version1));
Void::Testing::expect(!store.rollback().has_value());
Void::Testing::expect(
std::filesystem::exists(store.root() / "activation.json"));
const auto current = store.currentVersion();
Void::Testing::require(current.has_value() && current->has_value());
Void::Testing::expect_eq((*current)->to_string(), std::string{"2.0.0"});
Void::Testing::expect(std::filesystem::is_directory(external));
#endif
}