Merge feat/roadmap-p2-wave5: P2 Observability, Resilience, Log, and Stacktrace

This commit is contained in:
faumaray committed 2026-11-24 10:39:26 +03:00
commit 44799602c9
66 files changed
+10434 -1756

No files matched your search

+5
View File
@@ -1,6 +1,7 @@
set_property(GLOBAL PROPERTY VOID_MODULES "")
set_property(GLOBAL PROPERTY VOID_MODULE_DEPENDENCY_RECORDS "")
set_property(GLOBAL PROPERTY VOID_PENDING_OPTIONAL_DEPS "")
set_property(GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "")
function(void_add_module MODULE_NAME)
cmake_parse_arguments(ARG "" ""
@@ -61,6 +62,10 @@ function(void_add_module MODULE_NAME)
add_library(${ALIAS} ALIAS ${TGT})
set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME})
foreach(_hdr IN LISTS HDR)
file(RELATIVE_PATH _rel_hdr "${CMAKE_CURRENT_SOURCE_DIR}/include" "${_hdr}")
set_property(GLOBAL APPEND PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "${_rel_hdr}")
endforeach()
set(_module_external_deps "")
foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS)
# FindSQLite3's package name and imported-target namespace differ.
+1
View File
@@ -72,3 +72,4 @@ plans requiring updates. Do not record a proposal as user approval.
| D-029 | Follow `MIGRATION.md` Wave A+B: keep 1.x public APIs and existing tests compiling/passing while introducing NEW APIs and adapters beside them | CONFIRMED by user |
| D-030 | Create dedicated git branch (`feat/roadmap-p0-p1-foundations`) and make focused commits per completed milestone/task; leave local untracked files (`.env`, `.serena/`, `WG.conf`, `keys`) untouched | CONFIRMED by user |
| D-031 | Proceed continuously across roadmap waves without pausing for confirmation between waves, and merge verified waves locally into `main` (without pushing to remote) | CONFIRMED by user |
| D-032 | Push verified `main` (and active feature branches) to `origin` (`git@git.faumaray.com:Void/VoidLibrary.git`) after each verified wave merge, superseding the local-only constraint in `D-031` | CONFIRMED by user ("dont forget to push") |
+44 -8
View File
@@ -1,8 +1,8 @@
# Workflow state
Updated: 2026-11-24.
Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4b` (from `main`
at `2e5d1ef`, merged Waves 1–4A).
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave5` (from `main`
at `1e901ce`, merged Waves 1–4B and pushed to `origin/main`).
## Completed objective
@@ -72,10 +72,11 @@ at `2e5d1ef`, merged Waves 1–4A).
## Baseline and authorization
User decisions D-027..D-031 authorize continuous roadmap-order execution on branch
`feat/roadmap-p0-p1-foundations`, per-task workflow specs in `docs/agent-workflow/tasks/`,
Wave A+B API compatibility, and local merges of verified waves into `main` (without
pushing to remote) while leaving local untracked files untouched.
User decisions D-027..D-032 authorize continuous roadmap-order execution across dedicated
wave branches (`feat/roadmap-*`), per-task workflow specs in
`docs/agent-workflow/tasks/`, Wave A+B API compatibility, `--no-ff` merges of verified
waves into `main`, and pushing verified `main` and active feature branches to `origin`
while leaving local untracked files untouched.
## Verification already observed (P0)
@@ -180,7 +181,42 @@ pushing to remote) while leaving local untracked files untouched.
`binary_reader_u64_be` 1.35 ns, `data_json_parse_small_object` 316.78 ns,
`data_json_serialize_small_object` 168.16 ns.
## Verification already observed (Wave 5 — P2 Operations Foundations)
- `ObservabilityHooks` + `Observability` (`fe99051`): `Observability*` 4/4 passed
(12.1 ms); `ctest` 2/2 passed (including `ObservabilityHooksOnly` &
`ObservabilityOnly`, 7.03 s).
- `Resilience` + `ResilienceAsync` + P2 error domains (`18a623a`): standalone 21/21
(2.8 ms) + `AsyncPolicy*` 6/6 (1.3 ms); `ctest` 2/2 (5.99 s including `ResilienceOnly`).
- `LogState` + `Log` + `LogConfig` (`a74a402`): `Log;Testing` `724 ✔`, `2 ⊘`
(`broken_feature`, `unquoted_skip`), `0 ✘` (799.2 ms); `ctest` 2/2 (`LogOnly` 7.15 s,
total 8.09 s); `LogConfig;Testing` 12/12 (28.9 ms).
- CMake `VOID_ACTIVE_PUBLIC_HEADERS` fix (`3d8dfb0`) + `Stacktrace` (`7b57b35`):
`Stacktrace;Testing` `Stacktrace*` 4/4 passed (374.2 ms) without selecting `Log`.
- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w5-full`, 37 modules,
`7b57b35`): `VoidTests` 1,378 tests — 1,375 passed, 3 intentional skips
(`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (7.49 s);
`ctest` 2/2 passed (`VoidTests` 8.09 s, `VoidInstalledComponentConsumers` all 16 consumers
66.12 s, total 74.22 s).
- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w5-asan`, 37
modules, `7b57b35`): initial run hit 1 timing assertion in unrelated existing
`internal_fsm_service_hot_reload_under_load` (`FsmServiceHotReload.cpp:119`); clean
re-run passed all 1,378 tests — 1,375 passed, 3 skipped, 0 failed (50.16 s), 0 leaks,
0 UB.
- Wave 5 Debug TSan subset (`/tmp/void-w5-tsan`, 15 modules, `7b57b35`):
`Observability*|ResilienceHardening*|AsyncPolicy*|Log*|AsyncLogger*|LogScopeSnapshot*|Io*|OperationScope*`
68/68 passed (7.01 s), 0 TSan data races.
- `VoidFoundationBench` post-W5 (`rev=7b57b355cd75`, `/tmp/void-w5-full`, `post-w5.json`):
`harness_empty_loop` 0.75 ns, `core_uuid_parse_hyphenated` 43.49 ns,
`core_uuid_to_string` 32.51 ns, `core_hash_fnv1a64_256b` 213.37 ns,
`core_hash_murmur3_256b` 92.34 ns, `functional_result_ok_chain` 1.65 ns,
`functional_error_with_context` 94.82 ns, `math_checked_add_loop` 0.86 ns,
`containers_spsc_ring_push_pop` 10.76 ns, `containers_lru_get_put` 31.99 ns,
`binary_reader_u64_be` 2.24 ns, `data_json_parse_small_object` 576.81 ns,
`data_json_serialize_small_object` 284.87 ns.
## Ownership and next step
Waves 1–4B (`P0` and `P1`) are complete and verified on `feat/roadmap-p1-wave4b` and ready
to merge locally into `main`, before planning and executing **P2 Wave 5**.
Waves 1–5 (`P0`, `P1`, and `P2` Operations Foundations: `Observability`, `Resilience`,
`Log`, `Stacktrace`) are complete and verified on `feat/roadmap-p2-wave5`, ready to merge
into `main`, push to `origin`, and proceed continuously to **P2 Wave 6**.
+11
View File
@@ -59,6 +59,17 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| S-RUNTIME-01 | `CMakeLists.txt` explicit `void_add_module` keyword matching fix, `src/Runtime/module.cmake` (`Core Functional Time Memory Algorithms Async IO`), `Options.hpp`, `ResourceGraph.hpp`, `Host.hpp`, `RuntimeOnly` consumer (`1b3331e`) | [S-RUNTIME-01](tasks/S-RUNTIME-01.md) | VERIFIED | `RuntimeHost` 3/3, `RuntimeOnly` & `ctest` 2/2 passed (11-module closure); full RelWithDebInfo (1,356 ✔) & ASan+UBSan (0 leaks/UB) |
| M-TESTING-02, M-TESTING-03 | `OwningJUnitReporter`, strict CLI/config validation (`--allow-empty`, `--selftest-child`), bounded assertion/failure capture, `Subprocess` POSIX runner, frozen v1 `DeterministicRng`/`ReplayToken`/`check_property` shrinker & `DeterministicRun` (`de8a981`) | [M-TESTING-02-03](tasks/M-TESTING-02-03.md) | VERIFIED | `Core;Testing` 14 ✔ / 2 ⊘ & `ctest` 2/2 passed; full RelWithDebInfo (1,356 ✔) & ASan+UBSan (0 leaks/UB) |
## Wave 5 — P2 Operations Foundations (`feat/roadmap-p2-wave5`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| Wave 5 specs & P2 error domains | Per-task specs under `docs/agent-workflow/tasks/` and reserved P2 domain IDs (`kRuntimeErrorDomain = 11`, `kLogErrorDomain = 12`, `kStacktraceErrorDomain = 13`, `kObservabilityErrorDomain = 14`, `kResilienceErrorDomain = 15`) (`809b6f5`, fixed in `18a623a`) | — | VERIFIED | Integrated RelWithDebInfo & ASan+UBSan passed with zero domain collisions |
| S-OBSERVABILITY-01..04 | `ObservabilityHooks` std-only `INTERFACE`, `Observability` (`Hooks`, `Context`, `AsyncContext`, thread-sharded `Metrics`, sampled/budgeted `Tracing`), `ObservabilityHooksOnly` & `ObservabilityOnly` consumers (`fe99051`) | [S-OBSERVABILITY-01-04](tasks/S-OBSERVABILITY-01-04.md) | VERIFIED | `Observability` 4/4, Debug TSan 4/4 (0 races), `ObservabilityHooksOnly`/`ObservabilityOnly` consumers, full RelWithDebInfo (1,375 ✔) & ASan+UBSan (0 leaks/UB) |
| M-RESILIENCE-01..04 | `Resilience` (`Types`, `RateLimiter`, bounded cursor `KeyedRateLimiter`, generation-bound `Breaker`/`BreakerPermit`, overflow-safe `ResourceMonitor`/`ResourcePermit`) & `ResilienceAsync` (`AsyncPolicy` FIFO `Bulkhead`, `execute_resilient`), `ResilienceOnly` consumer (`18a623a`) | [M-RESILIENCE-01-04](tasks/M-RESILIENCE-01-04.md) | VERIFIED | Standalone 21/21 & `AsyncPolicy` 6/6, Debug TSan `ResilienceHardening`+`AsyncPolicy` 6/6 (0 races), `ResilienceOnly` consumer, full RelWithDebInfo (1,375 ✔) & ASan+UBSan |
| M-LOG-01..05 | Hardened `LogState` (`SinkRegistration`, `detach_and_drain`, reentrancy cap 8), bounded `Logger` (`DeliveryLimits`, `LoggerOptions`, `try_submit`, `flush_through`, quarantine, `set_mode` barrier), redaction/escaping `Formatter`, `MultiLogger::try_add` cap 8 + cycle check, `FileLogger`/`RotatingFileLogger` `fsync`/`reopen`, separate `LogConfig`, `LogOnly` consumer (`a74a402`) | [M-LOG-01-05](tasks/M-LOG-01-05.md) | VERIFIED | `Log;Testing` 724 ✔ / 2 ⊘ & `LogConfig;Testing` 12/12, Debug TSan 36/36 (`Log*`, `AsyncLogger*`, `LogScopeSnapshot*`, `LogHardening*`), `LogOnly` consumer, full RelWithDebInfo & ASan+UBSan |
| CMake test header check fix | Track `VOID_ACTIVE_PUBLIC_HEADERS` in `cmake/Module.cmake` so `tests/CMakeLists.txt` maps split `EXTRA_HEADERS` (e.g. `Void/Log/Log.hpp` -> `LogState`) accurately (`3d8dfb0`) | — | VERIFIED | `Stacktrace;Testing` discovers and passes `Stacktrace*` 4/4 without `Log`; full suite discovers all 1,378 tests |
| M-STACKTRACE-01..04 | `src/Stacktrace/module.cmake` (`INTERNAL_DEPS Functional Time LogState`), split `capture()` (<=256 frames, zero log/source IO) & `Resolver` (1024-entry / 4 MiB cache, `invalidate_module`), `Capabilities`, checked `read_source_snippet_checked` (roots, symlink-escape & `..` rejection, overflow-safe `int64_t` math), `format_resolved_trace`, `write_fatal_signal_marker`, `tests/standalone/Stacktrace/Stacktrace.cpp` (`7b57b35`) | [M-STACKTRACE-01-04](tasks/M-STACKTRACE-01-04.md) | VERIFIED | `Stacktrace;Testing` `Stacktrace*` 4/4 (374.2ms), full RelWithDebInfo (1,375 ✔) & ASan+UBSan (0 leaks/UB) |
All workers share the checkout and have disjoint file ownership defined in their
persisted task specifications. Root owns all cross-cutting files and resolves contract
changes. No worker owns application code, build files, existing docs/short-url.md, or Git
+15
View File
@@ -215,3 +215,18 @@ Branch: `feat/roadmap-p1-wave4b` (branched from `main` at `2e5d1ef`). Toolchain
| Full Integrated ASan+UBSan (`de8a981`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w4b-asan`, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w4b-asan/tests/VoidTests` | 33 active modules; `VoidTests`: 1,359 tests — 1,356 passed, 3 skipped, 0 failed (14.87s), 0 leaks, 0 UB |
| Wave 4B TSan Subset (`de8a981`) | `dev cpp-gcc -c` Debug (`IO;Async;Containers;Time;Testing`, `/tmp/void-w4b-tsan`, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w4b-tsan/tests/VoidTests --filter "Io*\|OperationScope*\|Executor*\|Ring*\|Pool*\|Clock*"` | 9 active modules; 80/80 passed (60.7ms), 0 TSan data races |
| Post-W4B Benchmark (`de8a981`, `rev=de8a981893d8`) | `VoidFoundationBench` in `/tmp/void-w4b-full` (`post-w4b.json`) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.28ns, `core_uuid_to_string` 16.94ns, `core_hash_fnv1a64_256b` 184.30ns, `core_hash_murmur3_256b` 69.63ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 60.17ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 9.06ns, `containers_lru_get_put` 21.30ns, `binary_reader_u64_be` 1.35ns, `data_json_parse_small_object` 316.78ns, `data_json_serialize_small_object` 168.16ns |
## Wave 5 / P2 Operations Foundations Verification (2026-11-24)
Branch: `feat/roadmap-p2-wave5` (branched from `main` at `1e901ce`, which was pushed to `origin/main`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2.
| Scope | Command & configuration | Observed outcome |
| --- | --- | --- |
| S-OBSERVABILITY-01..04 (`fe99051`) | `Observability;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w5-obs` (`VoidTests --filter "Observability*"`, `ctest`) | `Observability` 4/4 passed (12.1ms); `ctest` 2/2 passed (`VoidTests` 0.41s, `VoidInstalledComponentConsumers` including `ObservabilityHooksOnly` & `ObservabilityOnly` 6.62s, total 7.03s) |
| M-RESILIENCE-01..04 (`18a623a`) | `Resilience;Testing` (`/tmp/void-w5-resilience`) & `ResilienceAsync;Testing` (`/tmp/void-w5-resilience-async`) RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` | `Resilience` `CircuitBreaker*\|RateLimiter*\|KeyedRateLimiter*\|ResourceMonitor*\|ResilienceHardening*` 21/21 (2.8ms) & `ctest` 2/2 (`5.99s` including `ResilienceOnly`); `ResilienceAsync` `AsyncPolicy*\|ResilienceHardening*` 6/6 (1.3ms) |
| M-LOG-01..05 (`a74a402`) | `Log;Testing` (`/tmp/void-w5-log`, 10 modules) & `LogConfig;Testing` (`/tmp/void-w5-logconfig`, 13 modules) RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` | `Log;Testing` `VoidTests`: 726 tests — 724 passed, 2 intentional skips (`broken_feature`, `unquoted_skip`), 0 failed (799.2ms) & `ctest` 2/2 (8.09s including `LogOnly` 7.15s); `LogConfig;Testing` `LogHardening*\|FromConfig*` 12/12 (28.9ms) |
| M-STACKTRACE-01..04 & CMake fix (`3d8dfb0`, `7b57b35`) | `Stacktrace;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w5-stacktrace`, 6 active modules, Boost cached) | `Stacktrace*` 4/4 passed (374.2ms); `Log` not required thanks to `VOID_ACTIVE_PUBLIC_HEADERS` mapping |
| Full Integrated RelWithDebInfo (`7b57b35`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w5-full`, 37 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w5-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w5-full --output-on-failure --timeout 180` | `VoidTests`: 1,378 tests — 1,375 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (7.49s); `ctest`: 2/2 passed (`VoidTests` 8.09s + `VoidInstalledComponentConsumers` all 16 consumers 66.12s, total 74.22s) |
| Full Integrated ASan+UBSan (`7b57b35`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w5-asan`, 37 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w5-asan/tests/VoidTests` | Initial run hit 1 timing assertion in unrelated existing `internal_fsm_service_hot_reload_under_load` (`FsmServiceHotReload.cpp:119`, 0 leaks/UB); full re-run on same binary passed 1,378 tests — 1,375 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (50.16s), 0 ASan/LSan leaks, 0 UBSan errors |
| Wave 5 TSan Subset (`7b57b35`) | `dev cpp-gcc -c` Debug (`Observability;ResilienceAsync;Log;IO;Async;Time;Testing`, `/tmp/void-w5-tsan`, 15 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w5-tsan/tests/VoidTests --filter "Observability*\|ResilienceHardening*\|AsyncPolicy*\|Log*\|AsyncLogger*\|LogScopeSnapshot*\|Io*\|OperationScope*"` | 68/68 passed (7.01s, including `AsyncLogger::async_multi_producer_no_loss` 6.53s, `Observability` 4/4, `ResilienceHardening` 4/4, `AsyncPolicy` 2/2, `Log` 12/12, `LogHardening` 4/4, `LogScopeSnapshot` 3/3, `IoDriver` 4/4, `OperationScope` 5/5), 0 TSan data races |
| Post-W5 Benchmark (`7b57b35`, `rev=7b57b355cd75`) | `/tmp/void-w5-full/benchmarks/VoidFoundationBench --json /tmp/void-w5-full/post-w5.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.75ns, `core_uuid_parse_hyphenated` 43.49ns, `core_uuid_to_string` 32.51ns, `core_hash_fnv1a64_256b` 213.37ns, `core_hash_murmur3_256b` 92.34ns, `functional_result_ok_chain` 1.65ns, `functional_error_with_context` 94.82ns, `math_checked_add_loop` 0.86ns, `containers_spsc_ring_push_pop` 10.76ns, `containers_lru_get_put` 31.99ns, `binary_reader_u64_be` 2.24ns, `data_json_parse_small_object` 576.81ns, `data_json_serialize_small_object` 284.87ns |
+28
View File
@@ -0,0 +1,28 @@
# Log Hardening, Bounded Delivery, File Sync, and LogConfig Separation
Task ID: M-LOG-01..05
Phase: P2
Status: APPROVED
Contracts: C-01, C-02, C-03, C-04, C-05, C-11
## 1. Context and baseline
`Void::Log` (`Log.hpp` + `LogState/State.cpp`) holds `Sink` behind `State::mutex` during emission, and `Void::Logging::Logger` (`src/Log/Logger.cpp`) uses an unbounded batch drain without byte budgeting, contiguous ticket completion, exception quarantine, or file durability/reopen controls, while `Log` links `Configuration` via `FromConfig.hpp`.
## 2. Deliverables
- Split `LogConfig` (`src/LogConfig/module.cmake`, `FromConfig.hpp`/`src/LogConfig/FromConfig.cpp`) out of `Log` (`src/Log/module.cmake`: `INTERNAL_DEPS Async Core Data Functional Memory Time LogState`, `OPTIONAL_DEPS Stacktrace`, `EXCLUDE_HEADERS Void/Log/Log.hpp Void/Log/FromConfig.hpp`).
- `include/Void/Log/Log.hpp` & `src/LogState/State.cpp`: immutable `SinkRegistration`, `register_sink`, `detach_and_drain` (`DrainResult` with `would_deadlock`), outer-of-lock callback invocation & owner destruction, reentrancy guard (depth <= 8) + emergency hook.
- `include/Void/Log/Entry.hpp`: `bool truncated{false};`.
- `include/Void/Log/Logger.hpp` & `src/Log/Logger.cpp`: `LogErrorCode`, `make_log_error` (`kLogErrorDomain = 12`), `DeliveryLimits`, `FailurePolicy`, `LoggerOptions`, `SubmitState`, `Ticket`, `SubmitReceipt`, `FlushDurability`, `FlushOptions`, `CloseOptions`, `FlushReport`, bounded deque with queued+in-flight entry and byte accounting, contiguous ticket watermark, `try_submit`, `flush_through`, `close`, quarantine & reset, admission-barrier `set_mode`, `sync_files()`.
- `include/Void/Log/Sinks.hpp`: `CallbackLogger(Callback, LoggerOptions)`, `MultiLogger::try_add` with max 8 children and cycle check.
- `include/Void/Log/Formatter.hpp` & `src/Log/Formatter.cpp`: field redaction in `FieldFilter`, `LogfmtFormatter` control-char escaping, `JsonLinesFormatter` int64 line numbers, `format_bounded`.
- `FileLogger` / `RotatingFileLogger` / `RollingFile`: explicit `create_directories`, `RotatingFileOptions::roadmap_defaults()`, stream write-error surfacing, `reopen()`, POSIX `::fsync` in `sync_files()`.
- `src/LogConfig/FromConfig.cpp` + moved `tests/standalone/LogConfig/FromConfig.cpp`: strict config value validation.
- `tests/standalone/Log/LogHardening.cpp` and `tests/package/LogOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake`.
## 3. Edge cases
- Legacy 3-argument `Logger` constructor preserves compatibility for existing `LogScopeSnapshot` immediate recursion and `AsyncLogger` 400k stress test (`owned_bytes >= max(8 MiB, entries * 1024)`, `suppress_reentrancy = false`).
- `DropOldest` never evicts already-dispatched in-flight batch entries; `Block` rejects self-blocking on worker (`would_deadlock`).
## 4. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w5-log -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Log;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w5-log && /tmp/void-w5-log/tests/VoidTests && ctest --test-dir /tmp/void-w5-log --output-on-failure --timeout 120'
```
@@ -0,0 +1,28 @@
# Resilience Hardening, Permits, Bounded Keyed Cleanup, and Async Policy
Task ID: M-RESILIENCE-01..04
Phase: P2
Status: APPROVED
Contracts: C-02, C-03, C-04, C-05, C-11, C-13
## 1. Context and baseline
`Void::Resilience` currently provides `TokenBucket`, `KeyedRateLimiter`, `CircuitBreaker`, and `ResourceMonitor` without config/input validation, overflow-safe `ResourceMonitor` subtraction, synchronized callback setters, single-probe HalfOpen leases, generation binding, bounded keyed cleanup cursors, or optional `Async` bulkhead/retry composition.
## 2. Deliverables
- `src/Resilience/module.cmake` (`INTERNAL_DEPS Functional Time ObservabilityHooks`, `EXCLUDE_HEADERS Void/Resilience/AsyncPolicy.hpp`)
- `src/ResilienceAsync/module.cmake` (`INTERNAL_DEPS Resilience Async Functional Time ObservabilityHooks`, `EXTRA_HEADERS Void/Resilience/AsyncPolicy.hpp`)
- `include/Void/Resilience/Types.hpp`: `ResilienceErrorCode`, `make_resilience_error` (`kResilienceErrorDomain = 15`), `Outcome`, `Admission`, validated `BucketConfig`, `KeyedBucketConfig`, `BreakerConfig`, `MonitorConfig`
- Upgrades in `RateLimiter.hpp`, `KeyedRateLimiter.hpp`, `CircuitBreaker.hpp`, `ResourceMonitor.hpp`, `Resilience.hpp` (`TokenBucket::create`/`try_acquire_checked`/`try_acquire_all`, `BoundedKeyedRateLimiter`, `Breaker`/`BreakerPermit`, overflow-safe `ResourceMonitor`/`ResourcePermit`)
- `include/Void/Resilience/AsyncPolicy.hpp`: `BulkheadConfig`, `Bulkhead`, `BulkheadPermit`, `ResilientRetryConfig` (using `Void::Retry::ExponentialBackoff` + `JitterMode::Full`), `execute_resilient`
- `tests/standalone/Resilience/ResilienceHardening.cpp`, `tests/standalone/ResilienceAsync/AsyncPolicy.cpp`
- `tests/package/ResilienceOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake`
## 3. Edge cases
- Clock regression never moves `last_` backwards or adds tokens; NaN/Inf/negative/oversize costs consume nothing.
- `BreakerPermit` enforces single (or `half_open_max_probes`) concurrent HalfOpen probe, rejects stale-generation completions from closing newer Open state, and releases slot neutrally on abandonment.
- `ResourceMonitor` rejects overflow (`amount > limit - usage`), over-release (`release_checked`), and isolates observer callback exceptions outside locks.
- `execute_resilient` honors composition order, shares total deadline across retries, and never retries non-replay-safe operations.
## 4. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w5-resilience -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Resilience;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w5-resilience && /tmp/void-w5-resilience/tests/VoidTests --filter "CircuitBreaker*|RateLimiter*|KeyedRateLimiter*|ResourceMonitor*|ResilienceHardening*" && ctest --test-dir /tmp/void-w5-resilience --output-on-failure --timeout 120'
```
@@ -0,0 +1,27 @@
# Stacktrace Split Capture/Resolve, Bounded Cache, Safe Snippets, and Crash Marker
Task ID: M-STACKTRACE-01..04
Phase: P2
Status: APPROVED
Contracts: C-01, C-02, C-03, C-04, C-05
## 1. Context and baseline
`Void::Stacktrace` currently couples raw capture with demangling, source snippet file reads, and `Void::Log` diagnostics, has no explicit `Capabilities` query or async-signal-safe fatal marker helper, and has no standalone test directory under `tests/standalone/Stacktrace/`.
## 2. Deliverables
- `src/Stacktrace/module.cmake`: add `Time` (`INTERNAL_DEPS Functional Time LogState`)
- `include/Void/Stacktrace/Stacktrace.hpp` & `src/Stacktrace/Stacktrace.cpp`:
- Legacy `StackFrame`, `capture_stacktrace`, `read_source_snippet`, `format_stacktrace`, `print_stacktrace` preserved.
- `kStacktraceErrorDomain = 13` `StacktraceErrorCode` + `make_stacktrace_error`.
- `Capabilities` (`raw_capture`, `symbols`, `line_info`, `async_signal_safe = false`, `backend_name`) + `capabilities() noexcept`.
- `CaptureOptions`, owned `RawFrame` (`address`, `module_offset`, `module_path`, `module_id`), `RawTrace`, `capture()` (validates `1 <= max_frames <= 256`, zero source IO, zero `Void::Log` calls).
- `FrameResolveStatus`, `ResolvedFrame`, `ResolvedTrace`, `ResolveOptions`, `Resolver` (bounded `1024` entries / `4 MiB` cache keyed by `(module_id, module_offset)`, `invalidate_module`, `clear_cache`), `read_source_snippet_checked` (allowed roots, symlink-escape rejection, overflow-safe line math, byte limits), `format_resolved_trace`, `write_fatal_signal_marker(int fd, int sig) noexcept`.
- `tests/standalone/Stacktrace/Stacktrace.cpp`
## 3. Edge cases
- Pre-cancelled `stop_token` and expired `ManualClock` deadline return `incomplete == true` while preserving captured raw frames.
- Path traversal (`..`) and symlinks escaping `allowed_source_roots` fail with `unsafe_path`; `INT_MAX` line arithmetic never overflows.
## 4. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w5-stacktrace -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Stacktrace;Testing" -DVOID_WARNINGS_AS_ERRORS=ON -DFETCHCONTENT_SOURCE_DIR_BOOST=/home/faumaray/Projects/VoidLibrary/build/_deps/boost-src && cmake --build /tmp/void-w5-stacktrace && /tmp/void-w5-stacktrace/tests/VoidTests --filter "Stacktrace*"'
```
@@ -0,0 +1,31 @@
# Observability Hooks, Context, Metrics, and Tracing
Task ID: S-OBSERVABILITY-01..04
Phase: P2
Status: APPROVED
Contracts: C-01, C-02, C-03, C-04, C-05
## 1. Context and baseline
`ObservabilityHooks` and `Observability` do not yet exist in `src/` or `include/Void/Observability/`. Higher modules need zero-dependency instrumentation hooks, `HookLease` drain lifetimes, immutable `ContextSnapshot` propagation, bounded producer-sharded metrics, head-sampled bounded tracing, and a deterministic text snapshot exporter with zero dependency on `Async`, `IO`, `Runtime`, `Log`, `Net`, `Configuration`, or `System`.
## 2. Deliverables
- `src/ObservabilityHooks/module.cmake` (header-only `Void/Observability/Hooks.hpp`, zero deps)
- `src/Observability/module.cmake` (`INTERNAL_DEPS ObservabilityHooks Core Functional Time Memory`, `EXCLUDE_HEADERS Void/Observability/Hooks.hpp`)
- `include/Void/Observability/Hooks.hpp`: `MetricKind`, `AttributeView`, `MetricPoint`, `DiagnosticEvent`, `ObservationHooks`, `kNullObservationHooks`, `DrainStatus`, `HookRegistrationId`, `HookLease`, `HookSlot`
- `include/Void/Observability/Context.hpp`: `ObservabilityErrorCode`, `make_observability_error` (`kObservabilityErrorDomain = 14`), `TraceId`, `SpanId`, `TraceContext`, `ContextLimits`, `ContextSnapshot`, `ScopedContext`
- `include/Void/Observability/AsyncContext.hpp`: `bind_context`, `ContextAwaitable` (no `#include <Void/Async/...>`)
- `include/Void/Observability/Metrics.hpp` & `src/Observability/Metrics.cpp`: `MetricsLimits`, `InstrumentSpec`, `InstrumentHandle`, `HistogramSnapshot`, `SeriesSnapshot`, `MetricsSnapshot`, `MetricRegistry`
- `include/Void/Observability/Tracing.hpp` & `src/Observability/Tracing.cpp`: `TracingLimits`, `SpanStatus`, `SpanSpec`, `SpanEvent`, `CompletedSpan`, `ExportBatch`, `ExportReport`, `ExportOptions`, `Span`, `SpanExporter`, `CallbackSpanExporter`, `TextSnapshotExporter`, `Tracer`
- `include/Void/Observability/Observability.hpp`
- `tests/standalone/Observability/Observability.cpp`
- `tests/package/ObservabilityHooksOnly/{CMakeLists.txt,main.cpp}` & `tests/package/ObservabilityOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake`
## 3. Edge cases
- Null hooks allocate zero memory and initialize no backend.
- `HookSlot::detach_and_drain` detects self-drain from within an active callback (`would_deadlock`) and destroys owners strictly outside the lock.
- Exiting producer threads retain their metric shards via `std::shared_ptr<Shard>` in `MetricRegistry` while `thread_local` caches hold `std::weak_ptr<Shard>`, preventing leaks when `MetricRegistry` is destroyed.
- Cardinality overflow routes to `__overflow__` and increments overflow counters; exporting respects span/byte caps, retry limits, and deadline/stop without spawning hidden background threads.
## 4. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w5-obs -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Observability;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w5-obs && /tmp/void-w5-obs/tests/VoidTests --filter "Observability*" && ctest --test-dir /tmp/void-w5-obs --output-on-failure --timeout 120'
```
+5
View File
@@ -60,6 +60,11 @@ namespace Void::Result
inline constexpr std::uint32_t kIoErrorDomain = 8;
inline constexpr std::uint32_t kStorageErrorDomain = 9;
inline constexpr std::uint32_t kSystemErrorDomain = 10;
inline constexpr std::uint32_t kRuntimeErrorDomain = 11;
inline constexpr std::uint32_t kLogErrorDomain = 12;
inline constexpr std::uint32_t kStacktraceErrorDomain = 13;
inline constexpr std::uint32_t kObservabilityErrorDomain = 14;
inline constexpr std::uint32_t kResilienceErrorDomain = 15;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
+6 -43
View File
@@ -1,5 +1,7 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <filesystem>
@@ -12,37 +14,12 @@ namespace Void::Logging::Detail
struct RollingFileOptions {
std::size_t max_bytes = 1024 * 1024;
std::size_t max_files = 5;
bool create_directories = true;
};
/// Format a time point as a filesystem-safe, lexicographically (and
/// therefore chronologically) sortable UTC timestamp:
/// `YYYYMMDD-HHMMSS-ffffff` (microseconds).
[[nodiscard]] std::string
format_timestamp(std::chrono::system_clock::time_point tp);
/// A single append-only log file with size-based rotation. Not thread
/// safe — each sink owns one and drives it from its single worker.
///
/// Two rotation modes, selected by the `self_rotate` constructor
/// argument:
///
/// - self_rotate = true (default), "solo": write() rotates on its
/// own once the file exceeds max_bytes. The live file is closed
/// and renamed in place to `<name>-<rotation_time>` — same
/// directory, no subfolder. At most max_files such archives are
/// kept; the oldest (by name, which sorts chronologically) is
/// deleted. With max_files == 0 nothing is kept — the file is
/// just truncated.
///
/// - self_rotate = false, "grouped": write() only tracks size and
/// never rotates by itself. The owner polls exceeds_limit()
/// across a set of RollingFiles and, once any one of them crosses
/// the threshold, calls snapshot_into(dir) on every file in that
/// set so they all land — under their original names — in the
/// same directory at the same moment (e.g. so several files can
/// roll together into one shared `history/<creation_time>/`).
/// max_files does not apply to this path: nothing is ever deleted,
/// every snapshot is kept.
class RollingFile
{
public:
@@ -50,32 +27,18 @@ namespace Void::Logging::Detail
RollingFile(std::filesystem::path path, RollingFileOptions opt,
bool self_rotate = true);
/// Open for append (creating parent dirs). False on failure.
[[nodiscard]] bool open();
[[nodiscard]] bool reopen();
/// Append a line (a trailing '\n' is added). In solo mode,
/// rotates automatically once max_bytes is exceeded; in
/// grouped mode this only updates the byte count — the
/// caller drives rotation via exceeds_limit()/snapshot_into().
/// No-op if not open.
void write(std::string_view line);
void flush();
[[nodiscard]] Void::Result::Result<void> sync();
/// True once the current file has reached max_bytes. Meant
/// for grouped (self_rotate == false) use, so an owner can
/// check a whole set of files and decide when to roll them
/// together.
[[nodiscard]] bool exceeds_limit() const noexcept
{
return m_current_bytes >= m_opt.max_bytes;
}
/// Move the live file — same name, unmodified — into `dir`
/// (created if needed), then continue with a fresh file at
/// path(). Ignores max_files; nothing is ever deleted here.
/// Intended to be called on every file in a group so they
/// land together.
void snapshot_into(const std::filesystem::path& dir);
[[nodiscard]] bool is_open() const noexcept
@@ -102,4 +65,4 @@ namespace Void::Logging::Detail
std::chrono::time_point<std::chrono::system_clock> m_rotationTime;
};
} // namespace Void::Logging::Detail
} // namespace Void::Logging::Detail
+7 -18
View File
@@ -11,14 +11,6 @@
namespace Void::Logging
{
/// Distinguishes regular messages from scope boundary markers.
///
/// Sinks may use Kind to render scope entries differently —
/// e.g. with indentation, brackets, or a dedicated colour.
///
/// Message — a regular log record
/// ScopeEnter — emitted when a named scope opens (scope() call)
/// ScopeExit — emitted when a named scope closes (RAII destructor)
enum class Kind { Message, ScopeEnter, ScopeExit };
/// A single, immutable log record produced by Logger and handed to
@@ -44,18 +36,15 @@ namespace Void::Logging
std::thread::id thread_id{std::this_thread::get_id()};
/// Frozen snapshot of the thread-local ScopedContext stack at log
/// time. Ordered outermost → innermost (index 0 is the root
/// scope). For ScopeEnter this already includes the new scope as
/// the last element; for ScopeExit it reflects the stack *before*
/// the pop.
/// time.
std::vector<std::string> scopes{};
/// Structured key/value fields attached to this entry — a frozen
/// snapshot of the thread-local FieldScope stack at log time.
/// Formatters expose them as custom pattern tokens
/// (`{field:key}`) and in JSON/logfmt output. Later duplicate
/// keys win.
/// Structured key/value fields attached to this entry.
std::vector<std::pair<std::string, std::string>> fields{};
/// True when explicit oversize-truncation policy clipped message,
/// fields, scopes, or formatted payload.
bool truncated{false};
};
} // namespace Void::Logging
} // namespace Void::Logging
+17 -20
View File
@@ -12,21 +12,6 @@
namespace Void::Logging
{
/// Logger sink that appends formatted entries to a file on disk.
///
/// Defaults to Mode::Async — entries are queued lock-free and written
/// in batches by the logger's worker thread (one ofstream flush per
/// batch). The destructor flushes any remaining entries. Pass
/// Mode::Immediate/Buffered to opt out of the worker thread.
///
/// Two construction paths:
/// - `FileLogger::open(path)` returns
/// `Result<unique_ptr<FileLogger>, Error>` and never throws —
/// prefer this in code that already uses Void::Result for error
/// plumbing.
/// - The throwing constructor stays for callers that prefer
/// exceptions; it throws std::runtime_error if the path cannot
/// be opened for append.
class FileLogger final : public Logger
{
public:
@@ -35,6 +20,9 @@ namespace Void::Logging
Mode mode = Mode::Async,
std::size_t capacity = 512);
explicit FileLogger(const std::filesystem::path& path,
LoggerOptions options);
~FileLogger() noexcept override;
FileLogger(const FileLogger&) = delete;
@@ -42,21 +30,30 @@ namespace Void::Logging
FileLogger(FileLogger&&) = delete;
FileLogger& operator=(FileLogger&&) = delete;
/// Non-throwing factory. On failure returns
/// `Failure<Error>{Error{"FileLogger: cannot open '<path>'"}}`.
[[nodiscard]] static Void::Result::
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
open(const std::filesystem::path& path,
Mode mode = Mode::Async,
std::size_t capacity = 512);
/// Install a formatter replacing the default "[Level] message"
/// rendering. Call before logging starts.
[[nodiscard]] static Void::Result::
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
open(const std::filesystem::path& path,
LoggerOptions options);
void set_formatter(std::shared_ptr<const Formatter> formatter)
{
m_formatter = std::move(formatter);
}
[[nodiscard]] Void::Result::Result<void> reopen();
[[nodiscard]] Void::Result::Result<void> sync_files() override;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
protected:
void write(const Entry& entry) override;
@@ -71,4 +68,4 @@ namespace Void::Logging
std::shared_ptr<const Formatter> m_formatter;
};
} // namespace Void::Logging
} // namespace Void::Logging
+73 -91
View File
@@ -1,8 +1,10 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Log/Entry.hpp>
#include <Void/Log/Level.hpp>
#include <cstddef>
#include <functional>
#include <string>
#include <string_view>
@@ -11,11 +13,6 @@
namespace Void::Logging
{
/// Renders one Entry into a single output line (no trailing newline —
/// the sink appends its own record separator).
///
/// Formatters must be safe to share between sinks: format() is const
/// and implementations hold no mutable state.
class Formatter
{
public:
@@ -26,8 +23,6 @@ namespace Void::Logging
format(const Entry& entry) const = 0;
};
// ── colour ────────────────────────────────────────────────────────────
enum class AnsiColor {
Default,
Black,
@@ -48,99 +43,24 @@ namespace Void::Logging
BrightWhite,
};
/// Parse a colour name ("red", "bright_black", "cyan", ...). Returns
/// AnsiColor::Default for unknown names.
[[nodiscard]] AnsiColor parse_color(std::string_view name) noexcept;
/// SGR escape for a colour ("\x1b[31m"); empty for Default.
[[nodiscard]] std::string_view ansi_code(AnsiColor color) noexcept;
inline constexpr std::string_view kAnsiReset = "\x1b[0m";
/// Colour configuration for a PatternFormatter. Disabled by default;
/// ConsoleLogger turns it on when the stream is a colour-capable TTY.
struct ColorPolicy {
bool enabled = false;
std::unordered_map<Level, AnsiColor> level_colors;
std::unordered_map<std::string, AnsiColor> token_colors;
/// Sensible per-level defaults (Trace dim → Fatal bright magenta).
[[nodiscard]] static ColorPolicy defaults();
};
// ── PatternFormatter ──────────────────────────────────────────────────
//
// Placeholder pattern with per-token appearance and colour.
//
// {token} — substitute the token
// {token:spec} — spec = [align][width][,colour]
// align : '<' left (default), '>' right, '^'
// centre width : decimal field width (padded with
// spaces) colour: a name ("cyan") or "auto" (=
// level colour)
//
// Built-in tokens: time, level, thread, scopes, message, file, line,
// kind. An unknown token resolves against registered custom tokens
// (register_token), then against Entry::fields by key, and otherwise
// stays literal — so `{request_id:>8}` prints a structured field.
//
// Default pattern: "{time} [{level}] {scopes}{message}"
class PatternFormatter final : public Formatter
{
public:
explicit PatternFormatter(
std::string pattern = "{time} [{level}] {scopes}{message}");
[[nodiscard]] std::string format(const Entry& entry) const override;
/// Add a custom token. `name` becomes usable as `{name}`.
/// Overrides a built-in of the same name.
void register_token(std::string name,
std::function<std::string(const Entry&)>
renderer);
void set_color_policy(ColorPolicy policy)
{
m_colors = std::move(policy);
}
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
{
return m_colors;
}
private:
enum class Align { Left, Right, Center };
enum class ColorMode { None, Auto, Fixed };
struct Segment {
bool literal{true};
std::string text; // literal text, or the token name
Align align{Align::Left};
std::size_t width{0};
ColorMode color_mode{ColorMode::None};
AnsiColor color{AnsiColor::Default};
};
[[nodiscard]] std::string render_token(const Segment& seg,
const Entry& entry) const;
std::vector<Segment> m_segments;
std::unordered_map<std::string,
std::function<std::string(const Entry&)>>
m_custom;
ColorPolicy m_colors;
};
/// An allow/deny list applied to an entry's structured fields by the
/// json/logfmt sinks. `include` empty means "all keys" (still subject to
/// `exclude`); a non-empty `include` admits only those keys. `exclude`
/// always wins.
struct FieldFilter {
std::vector<std::string> include;
std::vector<std::string> exclude;
std::vector<std::string> include{};
std::vector<std::string> exclude{};
std::vector<std::string> redact{};
std::string redaction_mask{"[REDACTED]"};
[[nodiscard]] bool allows(std::string_view key) const
{
@@ -159,9 +79,68 @@ namespace Void::Logging
}
return false;
}
[[nodiscard]] bool is_redacted(std::string_view key) const
{
for (const auto& r : redact) {
if (r == key) {
return true;
}
}
return false;
}
};
class PatternFormatter final : public Formatter
{
public:
explicit PatternFormatter(
std::string pattern = "{time} [{level}] {scopes}{message}");
[[nodiscard]] std::string format(const Entry& entry) const override;
void register_token(std::string name,
std::function<std::string(const Entry&)>
renderer);
void set_color_policy(ColorPolicy policy)
{
m_colors = std::move(policy);
}
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
{
return m_colors;
}
void set_field_filter(FieldFilter f) { m_fields = std::move(f); }
private:
enum class Align { Left, Right, Center };
enum class ColorMode { None, Auto, Fixed };
struct Segment {
bool literal{true};
std::string text;
Align align{Align::Left};
std::size_t width{0};
ColorMode color_mode{ColorMode::None};
AnsiColor color{AnsiColor::Default};
};
[[nodiscard]] std::string render_token(const Segment& seg,
const Entry& entry) const;
std::vector<Segment> m_segments;
std::unordered_map<std::string,
std::function<std::string(const Entry&)>>
m_custom;
ColorPolicy m_colors;
FieldFilter m_fields;
};
/// One compact JSON object per entry (includes fields when present).
class JsonLinesFormatter final : public Formatter
{
public:
@@ -175,7 +154,6 @@ namespace Void::Logging
FieldFilter m_fields;
};
/// logfmt: time=... level=... thread=... msg="..." plus scopes/fields.
class LogfmtFormatter final : public Formatter
{
public:
@@ -189,15 +167,19 @@ namespace Void::Logging
FieldFilter m_fields;
};
[[nodiscard]] Void::Result::Result<std::string>
format_bounded(const Formatter& formatter,
const Entry& entry,
std::size_t max_bytes = 64ULL * 1024ULL,
bool truncate = false);
namespace FormatDetail
{
/// ISO-8601 UTC with milliseconds, e.g. "2026-06-12T10:30:00.123Z".
[[nodiscard]] std::string
iso8601(std::chrono::system_clock::time_point tp);
/// Dotted scope breadcrumb ("net.tls"); empty when no scopes.
[[nodiscard]] std::string
scope_breadcrumb(const std::vector<std::string>& scopes);
} // namespace FormatDetail
} // namespace Void::Logging
} // namespace Void::Logging
+208 -53
View File
@@ -1,8 +1,12 @@
#pragma once
#include <atomic>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <source_location>
@@ -11,6 +15,7 @@
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
// ── Void::Log — the emission facade
// ─────────────────────────────────────────── Header-only apart from its
@@ -18,18 +23,6 @@
// once per process, so every module (including INTERFACE libraries) can log by
// linking only that. The full sink framework lives in Void::Logging
// (Logger.hpp); bridge with Void/Log/LoggingAdapter.hpp.
//
// Integration contract:
// * No sink installed (the default) — every call is a single relaxed
// atomic load; format arguments are NOT formatted. This is the
// "no logging at all" path.
// * set_sink(...) routes everything to any callable — your own logging
// library plugs in here.
// * set_min_level(Level::Disabled) silences without removing the sink.
// * Per-module overrides: set_module_level("Fsm", Level::Trace).
//
// The API is deliberately macro-free: leveled function templates take a
// std::format_string and only format after the level/sink gate passes.
namespace Void::Log
{
@@ -44,23 +37,24 @@ namespace Void::Log
Disabled
};
/// Signature for any log consumer. Four arguments:
/// level — severity of the event
/// module — short library-internal label (e.g. "System.Process")
/// message — human-readable description
/// location — the call site that emitted the event (file/line/function)
/// Signature for any log consumer.
using Sink =
std::function<void(Level level, std::string_view module,
std::string_view message,
const std::source_location& location)>;
using RegistrationId = std::uint64_t;
enum class DrainResult : std::uint8_t {
drained = 0,
not_found,
would_deadlock
};
using EmergencyHandler = void (*)(std::string_view message) noexcept;
namespace Detail
{
// std::source_location cannot follow a variadic pack in a parameter
// list, so this wrapper captures the format string together with the
// caller's source location in its (consteval) constructor.
// std::type_identity_t<Args>... keeps Args non-deduced here, so they
// are deduced solely from the trailing argument pack.
template <typename... Args> struct FmtLoc {
std::format_string<Args...> fmt;
std::source_location location;
@@ -74,36 +68,176 @@ namespace Void::Log
}
};
struct SinkRegistration {
RegistrationId id{0};
Sink sink{};
std::shared_ptr<const void> owner{};
std::atomic<bool> detached{false};
std::atomic<std::size_t> active_calls{0};
std::mutex drain_mutex;
std::condition_variable drain_cv;
};
struct State {
// Fast-path gates (checked before any locking or formatting).
std::atomic<bool> has_sink{false};
std::atomic<Level> min_level{Level::Trace};
std::atomic<bool> has_module_levels{false};
std::atomic<std::uint64_t> reentrant_dropped{0};
std::atomic<EmergencyHandler> emergency_handler{nullptr};
// Slow path.
Sink sink;
// Slow path (registration is immutable after creation;
// invoked and destroyed strictly outside `mutex`).
std::shared_ptr<SinkRegistration> registration{};
RegistrationId next_id{0};
std::unordered_map<RegistrationId, std::weak_ptr<SinkRegistration>> known;
std::unordered_map<std::string, Level> module_levels;
std::shared_mutex mutex;
};
// The process's one State, defined in Void::LogState (a static in an
// inline function would be one per DLL on Windows).
inline constexpr std::size_t kMaxNestedFacadeSinks = 8;
// Process-wide singleton accessors defined in Void::LogState.
State& state();
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept;
struct ActiveRegistrationGuard {
std::shared_ptr<SinkRegistration> reg;
std::vector<const SinkRegistration*>& stack;
ActiveRegistrationGuard(std::shared_ptr<SinkRegistration> r,
std::vector<const SinkRegistration*>& st)
: reg(std::move(r)), stack(st)
{
stack.push_back(reg.get());
}
~ActiveRegistrationGuard() noexcept
{
if (!stack.empty()) {
stack.pop_back();
}
if (reg->active_calls.fetch_sub(
1, std::memory_order_acq_rel) == 1) {
std::lock_guard lock{reg->drain_mutex};
reg->drain_cv.notify_all();
}
}
ActiveRegistrationGuard(const ActiveRegistrationGuard&) = delete;
ActiveRegistrationGuard&
operator=(const ActiveRegistrationGuard&) = delete;
};
} // namespace Detail
/// Install the global sink. Any previously installed sink is replaced.
/// Pass a default-constructed (empty) Sink to silence all output.
/// Thread-safe: the new sink is visible to all threads after this returns.
inline void set_sink(Sink sink)
/// Install a sink alongside an optional lifetime-keepalive owner and return
/// its registration ID for explicit detach_and_drain().
inline RegistrationId
register_sink(Sink sink, std::shared_ptr<const void> owner = {})
{
auto& s = Detail::state();
std::unique_lock lock{s.mutex};
s.sink = std::move(sink);
s.has_sink.store(static_cast<bool>(s.sink), std::memory_order_release);
std::shared_ptr<Detail::SinkRegistration> prev;
RegistrationId id = 0;
if (sink) {
auto next = std::make_shared<Detail::SinkRegistration>();
next->sink = std::move(sink);
next->owner = std::move(owner);
std::unique_lock lock{s.mutex};
id = ++s.next_id;
next->id = id;
s.known.emplace(id, next);
for (auto it = s.known.begin(); it != s.known.end();) {
if (it->second.expired()) {
it = s.known.erase(it);
} else {
++it;
}
}
prev = std::exchange(s.registration, std::move(next));
if (prev) {
prev->detached.store(true, std::memory_order_release);
}
s.has_sink.store(true, std::memory_order_release);
} else {
std::unique_lock lock{s.mutex};
prev = std::exchange(s.registration, nullptr);
if (prev) {
prev->detached.store(true, std::memory_order_release);
}
s.has_sink.store(false, std::memory_order_release);
}
// Destroy previous callback/owner outside s.mutex.
prev.reset();
return id;
}
/// Install the global sink. Any previously installed sink is replaced
/// outside the facade lock (does not block waiting for in-flight calls).
inline void set_sink(Sink sink)
{
(void)register_sink(std::move(sink), {});
}
/// Detach a registered sink (or active sink when id == 0) and wait until
/// all already-admitted invocations using that registration complete.
/// Returns would_deadlock if called synchronously from that registration's
/// own active callback.
[[nodiscard]] inline DrainResult detach_and_drain(RegistrationId id = 0)
{
auto& s = Detail::state();
std::shared_ptr<Detail::SinkRegistration> target;
{
std::unique_lock lock{s.mutex};
if (id == 0) {
target = s.registration;
} else if (s.registration && s.registration->id == id) {
target = s.registration;
} else if (const auto it = s.known.find(id); it != s.known.end()) {
target = it->second.lock();
}
if (!target) {
return DrainResult::not_found;
}
const auto& active = Detail::active_registrations_tls();
for (const auto* entry : active) {
if (entry == target.get()) {
return DrainResult::would_deadlock;
}
}
target->detached.store(true, std::memory_order_release);
if (target == s.registration) {
s.registration.reset();
s.has_sink.store(false, std::memory_order_release);
}
s.known.erase(target->id);
}
{
std::unique_lock drain_lock{target->drain_mutex};
target->drain_cv.wait(drain_lock, [&target] {
return target->active_calls.load(std::memory_order_acquire) == 0;
});
}
target.reset();
return DrainResult::drained;
}
[[nodiscard]] inline std::uint64_t reentrant_dropped() noexcept
{
return Detail::state().reentrant_dropped.load(std::memory_order_relaxed);
}
inline void set_emergency_handler(EmergencyHandler handler) noexcept
{
Detail::state().emergency_handler.store(
handler, std::memory_order_release);
}
/// Global minimum level. Events below it are discarded before
/// formatting. Default: Trace (everything passes; the sink filters).
inline void set_min_level(Level level) noexcept
{
Detail::state().min_level.store(level, std::memory_order_relaxed);
@@ -114,8 +248,6 @@ namespace Void::Log
return Detail::state().min_level.load(std::memory_order_relaxed);
}
/// Per-module minimum level override (exact label match). Overrides take
/// precedence over the global minimum — they can both raise and lower it.
inline void set_module_level(std::string_view module, Level level)
{
auto& s = Detail::state();
@@ -124,7 +256,6 @@ namespace Void::Log
s.has_module_levels.store(true, std::memory_order_release);
}
/// Remove a per-module override.
inline void clear_module_level(std::string_view module)
{
auto& s = Detail::state();
@@ -134,7 +265,6 @@ namespace Void::Log
std::memory_order_release);
}
/// Would an event at `level` from `module` currently be emitted?
[[nodiscard]] inline bool enabled(Level level, std::string_view module)
{
auto& s = Detail::state();
@@ -154,15 +284,8 @@ namespace Void::Log
return level >= s.min_level.load(std::memory_order_relaxed);
}
/// Emit one pre-formatted log event through the global sink.
/// No-op (zero allocation) when disabled.
namespace Detail
{
// Single, non-overloaded dispatch to the sink. The formatted paths
// must forward through this rather than through log() itself: a
// log(level, module, std::string, source_location) call would also
// match the variadic log() overload (deducing source_location as a
// format argument) and fail in FmtLoc's consteval constructor.
inline void emit(Level level, std::string_view module,
std::string_view message,
const std::source_location& location)
@@ -171,10 +294,45 @@ namespace Void::Log
if (!::Void::Log::enabled(level, module)) {
return;
}
std::shared_lock lock{s.mutex};
if (s.sink) {
s.sink(level, module, message, location);
std::shared_ptr<SinkRegistration> reg;
bool reentrant = false;
{
std::shared_lock lock{s.mutex};
reg = s.registration;
if (!reg || reg->detached.load(std::memory_order_acquire) ||
!reg->sink) {
return;
}
const auto& active = active_registrations_tls();
if (active.size() >= kMaxNestedFacadeSinks) {
reentrant = true;
} else {
for (const auto* entry : active) {
if (entry == reg.get()) {
reentrant = true;
break;
}
}
}
if (!reentrant) {
reg->active_calls.fetch_add(1, std::memory_order_acq_rel);
}
}
if (reentrant) {
s.reentrant_dropped.fetch_add(1, std::memory_order_relaxed);
if (const auto eh =
s.emergency_handler.load(std::memory_order_acquire);
eh != nullptr) {
eh(message);
}
return;
}
ActiveRegistrationGuard guard{
std::move(reg), active_registrations_tls()};
guard.reg->sink(level, module, message, location);
}
} // namespace Detail
@@ -186,9 +344,6 @@ namespace Void::Log
Detail::emit(level, module, message, location);
}
/// Leveled, lazily-formatted emission: arguments are formatted only
/// after the level/sink gate passes. The call-site source location is
/// captured transparently via FmtLoc.
template <typename... Args>
void log(Level level, std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
@@ -243,4 +398,4 @@ namespace Void::Log
log(Level::Fatal, module, fmt, std::forward<Args>(args)...);
}
} // namespace Void::Log
} // namespace Void::Log
+244 -263
View File
@@ -1,18 +1,25 @@
#pragma once
#include "Void/Log/Field.hpp"
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Detail/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Entry.hpp>
#include <Void/Log/Level.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <format>
#include <functional>
#include <mutex>
#include <semaphore>
#include <optional>
#include <set>
#include <source_location>
#include <span>
#include <string>
@@ -23,104 +30,159 @@
namespace Void::Logging
{
/// Dispatch strategy.
/// Async — (default) entries are queued lock-free and delivered in
/// batches by a logger-owned worker thread.
/// Immediate — write() is called inline on the logging thread.
/// Buffered — entries accumulate and flush at capacity / on flush().
enum class Mode { Async, Immediate, Buffered };
/// What happens in Async mode when pending entries reach capacity.
/// Block — (default) the logging thread waits for space; nothing
/// is ever lost.
/// DropNewest — the incoming entry is discarded.
/// DropOldest — the oldest pending entries are discarded by the worker
/// when it falls behind (soft bound: memory can briefly
/// exceed capacity until the next drain).
enum class OverflowPolicy { Block, DropNewest, DropOldest };
/// Abstract base class for all Void loggers.
///
/// ## Responsibilities
/// - Level filtering (thread-safe, lock-free gate)
/// - Entry construction: timestamp, thread_id, scope snapshot
/// - Dispatch: Async (default, lock-free queue + owned worker thread
/// delivering batches), Immediate (inline), or Buffered (flush at
/// capacity). Switch at runtime with set_mode() — no separate
/// async/sync classes.
/// - Thread-safe submission — virtual extension points are called
/// *outside* any internal lock (from the worker thread in Async
/// mode) so derived classes may perform blocking I/O or acquire
/// their own resources freely.
/// - Scoped context via per-thread RAII guards (Logger::ScopedContext)
/// - Named scope logging: scope() emits ScopeEnter/ScopeExit entries
/// - Logger presets via make_preset() — bake in a level (and optional
/// message prefix) and later call with only the message/format args.
///
/// ## Async mode notes
/// - capacity bounds the pending-entry queue; OverflowPolicy decides
/// what happens at the bound (Block by default — nothing is lost).
/// - flush() blocks until every entry submitted *before* the call has
/// been delivered.
/// - In Async mode write()/on_flush() run on the worker thread; sinks
/// need no additional synchronization of their own state.
///
/// ## Deriving a logger
/// 1. Override `write(const Entry&)` — called once per entry in
/// Immediate mode and by the default `on_flush` implementation.
/// 2. Optionally override `on_flush(std::span<const Entry>)` — useful
/// for sinks that benefit from batch writes (e.g. file loggers).
/// 3. **Call `flush()` in your own destructor** before the base
/// destructor runs. Calling a pure virtual from `~Logger` is
/// undefined behaviour, so the base destructor does *not* flush;
/// any unflushed entries that remain after your destructor will be
/// silently discarded (the base destructor only stops and joins
/// the worker — it never invokes the virtuals).
/// 4. Stop logging from other threads before destroying the logger;
/// entries submitted concurrently with destruction are dropped.
///
/// ## Example — minimal derived logger
/// @code
/// class StdoutLogger final : public Void::Logging::Logger
/// {
/// public:
/// ~StdoutLogger() noexcept override { flush(); }
/// protected:
/// void write(const Void::Logging::Entry& e) override
/// {
/// std::println("[{}] {}", e.level, e.message);
/// }
/// };
/// @endcode
enum class LogErrorCode : std::int32_t {
invalid_argument = 1,
queue_full = 2,
entry_too_large = 3,
closed = 4,
cancelled = 5,
timeout = 6,
would_deadlock = 7,
quarantined = 8,
unsupported_capability = 9,
io_error = 10,
cycle_detected = 11
};
[[nodiscard]] inline Void::Result::Error
make_log_error(LogErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case LogErrorCode::invalid_argument:
case LogErrorCode::entry_too_large:
kind = ErrorKind::invalid_argument;
break;
case LogErrorCode::queue_full:
kind = ErrorKind::overloaded;
break;
case LogErrorCode::closed:
case LogErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case LogErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case LogErrorCode::would_deadlock:
case LogErrorCode::cycle_detected:
kind = ErrorKind::conflict;
break;
case LogErrorCode::quarantined:
kind = ErrorKind::internal;
break;
case LogErrorCode::unsupported_capability:
kind = ErrorKind::unsupported;
break;
case LogErrorCode::io_error:
kind = ErrorKind::io;
break;
}
return Error{kind,
std::move(message),
ErrorCode{Void::Result::kLogErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct DeliveryLimits {
std::size_t entries = 4096;
std::size_t owned_bytes = 8ULL * 1024ULL * 1024ULL;
std::size_t max_entry_bytes = 64ULL * 1024ULL;
std::size_t batch_entries = 128;
std::size_t batch_bytes = 256ULL * 1024ULL;
std::size_t max_fields = 32;
std::size_t max_scopes = 16;
std::size_t max_field_key_bytes = 256;
std::size_t max_field_value_bytes = 2048;
std::size_t max_format_scratch_bytes = 1024ULL * 1024ULL;
bool truncate_oversize = false;
[[nodiscard]] Void::Result::Result<void> validate() const;
};
enum class FailurePolicy : std::uint8_t {
Quarantine = 0,
Continue
};
struct LoggerOptions {
Mode mode = Mode::Async;
OverflowPolicy policy = OverflowPolicy::DropNewest;
DeliveryLimits limits{};
FailurePolicy failure_policy = FailurePolicy::Quarantine;
bool suppress_reentrancy = true;
const Void::Time::MonotonicClock* clock =
&Void::Time::SystemMonotonicClock::instance();
};
enum class SubmitState : std::uint8_t {
Accepted = 0,
Filtered,
Dropped,
Closed
};
using Ticket = std::uint64_t;
struct SubmitReceipt {
SubmitState state{SubmitState::Dropped};
std::optional<Ticket> ticket{};
bool truncated{false};
};
enum class FlushDurability : std::uint8_t {
BufferFlush = 0,
SyncFiles
};
struct FlushOptions {
FlushDurability durability = FlushDurability::BufferFlush;
Void::Async::OperationOptions async{};
};
struct CloseOptions {
bool drop_pending = false;
Void::Async::OperationOptions async{};
};
struct FlushReport {
std::uint64_t delivered{0};
std::uint64_t dropped{0};
std::uint64_t failed{0};
Ticket watermark{0};
bool timed_out{false};
bool cancelled{false};
};
struct LoggerStats {
std::size_t queued_entries{0};
std::size_t queued_bytes{0};
std::size_t in_flight_entries{0};
std::size_t in_flight_bytes{0};
std::uint64_t admitted{0};
std::uint64_t delivered{0};
std::uint64_t dropped{0};
std::uint64_t failed{0};
std::uint64_t reentrant_dropped{0};
Ticket completed_watermark{0};
bool quarantined{false};
bool closed{false};
};
/// Abstract base class for all Void loggers with bounded entry/byte
/// admission, ticket completion watermarks, failure quarantine, and flush
/// durability controls.
class Logger
{
public:
// =========================================================================
// ScopedContext — RAII, per-thread, named scope push/pop
//
// Pushing a scope has two effects:
// 1. The scope name is appended to this thread's scope stack so
// all subsequent entries carry it in Entry::scopes.
// 2. A ScopeEnter entry is emitted at the level supplied to
// push_scope() (or Trace by default).
// 3. On destruction a ScopeExit entry is emitted at the same
// level.
//
// Usage:
// {
// auto s = logger.push_scope("network"); // →
// ScopeEnter logger.info("connecting …"); //
// scopes={"network"}
// {
// auto t = logger.push_scope("tls"); // →
// ScopeEnter logger.debug("handshake"); //
// scopes={"network","tls"}
// } // → ScopeExit
// "tls"
// } // → ScopeExit
// "network"
// =========================================================================
class ScopedContext
{
public:
@@ -131,8 +193,6 @@ namespace Void::Logging
std::source_location loc) noexcept;
~ScopedContext() noexcept;
// Non-copyable; move transfers ownership so the moved-from
// guard does not emit a spurious ScopeExit on destruction.
ScopedContext(const ScopedContext&) = delete;
ScopedContext& operator=(const ScopedContext&) = delete;
ScopedContext(ScopedContext&&) noexcept;
@@ -146,23 +206,6 @@ namespace Void::Logging
bool m_active{true};
};
// =========================================================================
// Preset — a partially-applied logger
//
// A Preset captures a reference to the owning Logger together with
// a fixed Level (and optional message prefix). Call it with just
// the message / format args; the level is already baked in.
//
// Lifetime: a Preset must not outlive the Logger it was made from.
//
// Usage:
// auto net_err = logger.make_preset(Level::Error, "[network] ");
// net_err("connection refused"); // same as:
// // logger.error("[network] connection refused");
//
// auto dbg = logger.make_preset(Level::Debug);
// dbg("value = {}", 42);
// =========================================================================
class Preset
{
public:
@@ -174,16 +217,11 @@ namespace Void::Logging
{
}
// Non-owning; copyable so presets can be stored / passed
// around.
Preset(const Preset&) = default;
Preset& operator=(const Preset&) = default;
Preset(Preset&&) = default;
Preset& operator=(Preset&&) = default;
// -----------------------------------------------------------------
// Plain string overload
// -----------------------------------------------------------------
void operator()(std::string_view message,
std::source_location loc =
std::source_location::current()) const
@@ -197,22 +235,6 @@ namespace Void::Logging
}
}
// =========================================================================
// FormatWithLocation helper
//
// std::source_location cannot share a parameter list with
// a variadic pack, so this wrapper type captures both the
// format string and the caller's source location in its
// constructor.
//
// std::type_identity_t<Args>... prevents Args from being
// deduced from the wrapper; they are deduced solely from
// the trailing pack.
//
// Usage — source location is captured transparently:
// logger.info("player {} scored {} points", name,
// score);
// =========================================================================
template <typename... Args> struct FormatWithLocation {
std::format_string<Args...> fmt;
std::source_location location;
@@ -227,12 +249,6 @@ namespace Void::Logging
}
};
// -----------------------------------------------------------------
// Formatted overload
// Uses the same FormatWithLocation trick as Logger itself
// so the call-site source location is captured
// transparently.
// -----------------------------------------------------------------
template <typename... Args>
void operator()(
FormatWithLocation<std::type_identity_t<Args>...> fwl,
@@ -249,7 +265,6 @@ namespace Void::Logging
m_owner->log(m_level, msg, fwl.location);
}
// Accessors
[[nodiscard]] Level level() const noexcept
{
return m_level;
@@ -273,18 +288,13 @@ namespace Void::Logging
// =========================================================================
// Lifetime
// =========================================================================
/// @param mode Dispatch strategy; Async by default.
/// @param capacity Async: pending-queue bound (fixed for the
/// logger's lifetime). Buffered: auto-flush
/// threshold (adjustable).
/// @param policy Async overflow behaviour at capacity.
explicit Logger(
Mode mode = Mode::Async,
std::size_t capacity = 512,
OverflowPolicy policy = OverflowPolicy::Block) noexcept;
/// Stops and joins the worker thread (Async). Does NOT flush
/// remaining entries — see class-level note.
explicit Logger(LoggerOptions options);
virtual ~Logger() noexcept;
Logger(const Logger&) = delete;
@@ -293,103 +303,75 @@ namespace Void::Logging
Logger& operator=(Logger&&) = delete;
// =========================================================================
// Configuration (all setters are thread-safe)
// Configuration
// =========================================================================
/// Set the minimum level. Entries below this level are dropped.
/// Level::Disabled suppresses all output.
void set_level(Level level) noexcept;
[[nodiscard]] Level level() const noexcept;
/// Switch dispatch strategy at runtime (e.g. Async → Immediate
/// to make the logger synchronous). Pending entries are flushed
/// before the switch takes effect.
void set_mode(Mode mode) noexcept;
[[nodiscard]] Mode mode() const noexcept;
/// Maximum number of entries held before an automatic flush
/// (Buffered mode only; the Async queue bound is fixed at
/// construction).
void set_buffer_capacity(std::size_t n) noexcept;
[[nodiscard]] std::size_t buffer_capacity() const noexcept;
[[nodiscard]] OverflowPolicy overflow_policy() const noexcept;
[[nodiscard]] const DeliveryLimits& delivery_limits() const noexcept
{
return m_options.limits;
}
// =========================================================================
// Flush
// P2 Checked Submission, Flush, Close, and Quarantine Controls
// =========================================================================
[[nodiscard]] Void::Result::Result<SubmitReceipt>
try_submit(Entry entry,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<FlushReport>
flush_through(Ticket target = 0, FlushOptions options = {});
[[nodiscard]] Void::Result::Result<FlushReport>
close(CloseOptions options = {});
void request_close() noexcept;
/// Deliver all pending entries. Async: blocks until everything
/// submitted before this call has been written. Buffered: drains
/// the buffer via on_flush(). Immediate: no-op. Thread-safe.
/// Virtual so composite sinks can propagate the flush to
/// children.
virtual void flush();
// =========================================================================
// Scoped context
// =========================================================================
[[nodiscard]] LoggerStats stats() const;
[[nodiscard]] bool is_quarantined() const noexcept;
[[nodiscard]] std::string last_error_summary() const;
void reset_quarantine() noexcept;
/// Push a named scope onto this thread's scope stack AND emit a
/// ScopeEnter entry at the given level. The returned ScopedContext
/// emits a ScopeExit entry and pops the stack when it goes out of
/// scope.
///
/// @param name Human-readable scope label.
/// @param level Level used for the ScopeEnter/ScopeExit entries.
/// Defaults to Trace so scope boundaries are usually
/// invisible in production builds.
/// @return A [[nodiscard]] RAII guard — assign it to a named
/// local; do NOT discard (it would immediately exit).
// =========================================================================
// Scoped context & Presets
// =========================================================================
[[nodiscard]] ScopedContext
push_scope(std::string name,
Level level = Level::Trace,
std::source_location loc =
std::source_location::current()) noexcept;
/// Emit a named scope open/close pair as explicit log entries
/// WITHOUT modifying the thread-local scope stack. Useful when you
/// want scope boundaries in the log but don't want child entries
/// annotated.
///
/// Both ScopeEnter and ScopeExit are emitted immediately (Immediate
/// mode) or buffered together (Buffered mode).
void scope(
std::string_view name,
Level level = Level::Trace,
std::source_location loc = std::source_location::current());
/// Read-only view of the current thread's scope stack.
/// Ordered outermost → innermost.
[[nodiscard]] static std::span<const std::string>
current_scopes() noexcept;
// =========================================================================
// Preset factory
// =========================================================================
/// Create a Preset that fixes the level and an optional message
/// prefix. The Preset holds a non-owning reference to *this — do
/// not outlive the logger.
[[nodiscard]] Preset make_preset(Level level,
std::string prefix = {}) noexcept;
// =========================================================================
// Core (non-template) logging — canonical entry points
// Core & Formatted Logging (legacy compatibility adapters)
// =========================================================================
inline void log(
Level level, std::string_view message,
std::source_location location = std::source_location::current())
{
// Early level check outside the lock to avoid allocations on
// the hot path.
{
std::lock_guard lock(m_mutex);
if (level < m_level) {
return;
}
if (level < m_level.load(std::memory_order_relaxed)) {
return;
}
const auto fields = current_fields();
Entry entry{
.kind = Kind::Message,
@@ -398,7 +380,6 @@ namespace Void::Logging
.timestamp = std::chrono::system_clock::now(),
.location = location,
.thread_id = std::this_thread::get_id(),
// Snapshot here through the existing DLL function boundary.
.scopes = [] {
const auto scopes = Logger::current_scopes();
return std::vector<std::string>(
@@ -406,14 +387,9 @@ namespace Void::Logging
}(),
.fields = {fields.begin(), fields.end()},
};
submit(std::move(entry));
(void)try_submit(std::move(entry));
}
/// Route a fully-built Entry through this logger's level filter
/// and dispatch (queue / buffer / inline write). Meant for
/// composite sinks (e.g. MultiLogger) that fan entries out to
/// children without re-stamping timestamp/thread/scopes.
void relay(Entry entry);
void trace(
@@ -435,10 +411,6 @@ namespace Void::Logging
std::string_view msg,
std::source_location loc = std::source_location::current());
// =========================================================================
// Formatted logging
// =========================================================================
template <typename... Args>
void log(Level level,
Preset::FormatWithLocation<std::type_identity_t<Args>...>
@@ -498,81 +470,90 @@ namespace Void::Logging
log(Level::Fatal, fwl, std::forward<Args>(args)...);
}
[[nodiscard]] virtual Void::Result::Result<void> sync_files();
protected:
// =========================================================================
// Extension points
//
// Both methods are called OUTSIDE the internal mutex. Derived
// classes may block, acquire their own locks, or call other Logger
// methods without risk of deadlock.
// =========================================================================
/// Deliver one entry to the sink.
/// Called once per entry in Immediate mode, and by the default
/// on_flush() for each entry in the batch.
virtual void write(const Entry& entry) = 0;
/// Deliver a batch of buffered entries to the sink.
/// The default implementation calls write() for each entry in
/// order. Override to enable batched / vectored I/O.
virtual void on_flush(std::span<const Entry> entries);
private:
/// Build an Entry and route it to the queue, write() or the
/// buffer depending on the active mode.
void submit(Entry entry);
enum class TerminalOutcome : std::uint8_t {
Delivered = 0,
Dropped,
Failed
};
/// Async path: bounded enqueue honoring the overflow policy.
void async_submit(Entry entry);
struct QueuedItem {
Ticket ticket{0};
std::size_t bytes{0};
Entry entry;
};
[[nodiscard]] static std::size_t
estimate_entry_bytes(const Entry& entry) noexcept;
[[nodiscard]] Void::Result::Result<void>
prepare_entry(Entry& entry) const;
/// Start the worker thread on first use (Async mode).
void start_worker();
/// Wake the worker if it parked itself.
void wake_worker() noexcept;
/// Worker: drain → on_flush batches → park when idle.
void worker_loop();
/// Async: block until everything submitted so far is written.
void drain_async();
/// Emit a raw scope boundary entry; shared by push_scope and
/// scope().
void mark_terminal_locked(Ticket t, TerminalOutcome outcome);
void advance_watermark_locked();
void deliver_batch_unlocked(
std::vector<QueuedItem>& items,
bool stopping,
std::size_t total_bytes);
void emit_scope_boundary(Kind kind,
std::string_view name,
Level level,
std::source_location loc);
[[nodiscard]] bool is_active_logger_on_thread() const noexcept;
std::atomic<Level> m_level{Level::Trace};
std::atomic<Mode> m_mode;
std::size_t m_async_capacity;
OverflowPolicy m_policy;
mutable std::mutex m_mutex;
std::vector<Entry> m_buffer; // Buffered mode only
LoggerOptions m_options;
std::size_t m_buffer_capacity;
// ── Async machinery ──────────────────────────────────────────
Void::Async::MpscQueue<Entry> m_queue;
std::counting_semaphore<> m_space; // Block policy bound
// Counting (not binary): the worker's un-park path can leave a
// stale token behind, and a fresh release on top of it must
// not overflow. Extra tokens only cause spurious wakes, which
// the worker loop absorbs.
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_stop{false};
mutable std::mutex m_mutex;
std::condition_variable m_work_cv;
std::condition_variable m_space_cv;
std::condition_variable m_done_cv;
std::deque<QueuedItem> m_queue;
std::size_t m_queued_entries{0};
std::size_t m_queued_bytes{0};
std::size_t m_in_flight_entries{0};
std::size_t m_in_flight_bytes{0};
Ticket m_next_ticket{0};
Ticket m_completed_watermark{0};
std::set<std::pair<Ticket, TerminalOutcome>> m_pending_terminals;
std::uint64_t m_admitted_count{0};
std::uint64_t m_delivered_count{0};
std::uint64_t m_dropped_count{0};
std::uint64_t m_failed_count{0};
std::uint64_t m_wm_delivered{0};
std::uint64_t m_wm_dropped{0};
std::uint64_t m_wm_failed{0};
std::atomic<std::uint64_t> m_reentrant_dropped{0};
bool m_mode_changing{false};
bool m_stop_admission{false};
bool m_closed{false};
std::atomic<bool> m_stop_worker{false};
std::atomic<bool> m_quarantined{false};
std::string m_last_error;
std::atomic<bool> m_worker_started{false};
std::once_flag m_worker_once;
std::thread m_worker;
std::atomic<std::uint64_t> m_submitted{0};
std::atomic<std::uint64_t> m_completed{0};
std::atomic<std::thread::id> m_worker_id{};
/// Per-thread scope stack. ScopedContext pushes/pops into this.
static thread_local std::vector<std::string> s_scope_stack;
};
} // namespace Void::Logging
} // namespace Void::Logging
+17 -12
View File
@@ -13,21 +13,25 @@
namespace Void::Logging
{
/// File sink with size-based rotation.
///
/// When the current file reaches `max_bytes` after a batch, files are
/// shifted (`app.log` → `app.log.1` → `app.log.2` …); at most
/// `max_files` rotated files are kept, the oldest is deleted.
///
/// Defaults to Async dispatch — rotation and writes happen on the
/// worker thread. An optional Formatter overrides the default
/// "[Level] message" rendering; set it before logging starts.
struct RotatingFileOptions {
std::size_t max_bytes = 1024 * 1024;
std::size_t max_files = 5;
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::Block;
bool create_directories = true;
[[nodiscard]] static constexpr RotatingFileOptions
roadmap_defaults() noexcept
{
return RotatingFileOptions{
.max_bytes = 16ULL * 1024ULL * 1024ULL,
.max_files = 5,
.mode = Mode::Async,
.capacity = 4096,
.policy = OverflowPolicy::DropNewest,
.create_directories = false};
}
};
class RotatingFileLogger final : public Logger
@@ -46,17 +50,18 @@ namespace Void::Logging
RotatingFileLogger(RotatingFileLogger&&) = delete;
RotatingFileLogger& operator=(RotatingFileLogger&&) = delete;
/// Non-throwing factory.
[[nodiscard]] static Void::Result::
Result<std::unique_ptr<RotatingFileLogger>, Void::Result::Error>
open(const std::filesystem::path& path, Options options = {});
/// Install a formatter. Call before logging starts.
void set_formatter(std::shared_ptr<const Formatter> formatter)
{
m_formatter = std::move(formatter);
}
[[nodiscard]] Void::Result::Result<void> reopen();
[[nodiscard]] Void::Result::Result<void> sync_files() override;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
@@ -76,4 +81,4 @@ namespace Void::Logging
std::shared_ptr<const Formatter> m_formatter;
};
} // namespace Void::Logging
} // namespace Void::Logging
+79 -13
View File
@@ -9,12 +9,17 @@
namespace Void::Logging
{
/// Discards everything. Useful as a placeholder or for benchmarks.
inline constexpr std::size_t kDefaultMaxFanoutChildren = 8;
class NullLogger final : public Logger
{
public:
explicit NullLogger(Mode mode = Mode::Immediate) : Logger(mode) {}
explicit NullLogger(LoggerOptions options)
: Logger(std::move(options))
{
}
~NullLogger() noexcept override { flush(); }
@@ -23,8 +28,6 @@ namespace Void::Logging
void write(const Entry&) override {}
};
/// Forwards every entry to a user callback. The simplest way to splice
/// an external logging library into the Logger framework.
class CallbackLogger final : public Logger
{
public:
@@ -41,6 +44,11 @@ namespace Void::Logging
{
}
explicit CallbackLogger(Callback callback, LoggerOptions options)
: Logger(std::move(options)), m_callback(std::move(callback))
{
}
~CallbackLogger() noexcept override { flush(); }
protected:
@@ -57,10 +65,6 @@ namespace Void::Logging
Callback m_callback;
};
/// Tee: relays every entry to each child logger. Children keep their
/// own modes, levels, and formatters. The MultiLogger itself defaults
/// to Immediate dispatch — the children already decide whether they
/// queue asynchronously, so double-queueing only adds latency.
class MultiLogger final : public Logger
{
public:
@@ -72,15 +76,41 @@ namespace Void::Logging
{
}
explicit MultiLogger(
std::vector<std::shared_ptr<Logger>> children,
LoggerOptions options)
: Logger(std::move(options)), m_children(std::move(children))
{
}
~MultiLogger() noexcept override { flush(); }
/// Add a child sink. Not thread-safe with concurrent logging —
/// assemble the tree before use.
void add(std::shared_ptr<Logger> child)
{
if (child) {
m_children.push_back(std::move(child));
(void)try_add(std::move(child));
}
[[nodiscard]] Void::Result::Result<void>
try_add(std::shared_ptr<Logger> child,
std::size_t max_children = kDefaultMaxFanoutChildren)
{
if (!child) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"MultiLogger::try_add: null child"));
}
if (m_children.size() >= max_children) {
return Void::Result::fail(make_log_error(
LogErrorCode::queue_full,
"MultiLogger child fan-out limit exceeded"));
}
if (reaches_self(*child)) {
return Void::Result::fail(make_log_error(
LogErrorCode::cycle_detected,
"MultiLogger fan-out cycle detected"));
}
m_children.push_back(std::move(child));
return {};
}
[[nodiscard]] std::size_t child_count() const noexcept
@@ -88,7 +118,6 @@ namespace Void::Logging
return m_children.size();
}
/// Flush own pending entries, then every child.
void flush() override
{
Logger::flush();
@@ -97,6 +126,26 @@ namespace Void::Logging
}
}
[[nodiscard]] Void::Result::Result<void> sync_files() override
{
if (m_children.empty()) {
return Logger::sync_files();
}
bool any_synced = false;
for (const auto& child : m_children) {
auto res = child->sync_files();
if (res) {
any_synced = true;
} else if (res.error().code().value !=
static_cast<std::int32_t>(
LogErrorCode::unsupported_capability)) {
return res;
}
}
return any_synced ? Void::Result::Result<void>{}
: Logger::sync_files();
}
protected:
void write(const Entry& entry) override
@@ -108,7 +157,24 @@ namespace Void::Logging
private:
[[nodiscard]] bool reaches_self(const Logger& candidate) const
{
if (&candidate == this) {
return true;
}
const auto* nested = dynamic_cast<const MultiLogger*>(&candidate);
if (nested == nullptr) {
return false;
}
for (const auto& grandchild : nested->m_children) {
if (grandchild && reaches_self(*grandchild)) {
return true;
}
}
return false;
}
std::vector<std::shared_ptr<Logger>> m_children;
};
} // namespace Void::Logging
} // namespace Void::Logging
+109
View File
@@ -0,0 +1,109 @@
#pragma once
#include <Void/Observability/Context.hpp>
#include <coroutine>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>
namespace Void::Observability
{
/// Wrap any callable/task with an owned ContextSnapshot so execution on a
/// worker or executor installs ScopedContext across the invocation and restores
/// the worker thread's previous context afterward.
template <typename Fn>
class BoundContextCallable
{
public:
BoundContextCallable(ContextSnapshot snapshot, Fn fn)
: snapshot_(std::move(snapshot))
, fn_(std::move(fn))
{
}
template <typename... Args>
requires std::invocable<Fn&, Args...>
decltype(auto) operator()(Args&&... args)
{
ScopedContext guard{snapshot_};
return std::invoke(fn_, std::forward<Args>(args)...);
}
template <typename... Args>
requires std::invocable<const Fn&, Args...>
decltype(auto) operator()(Args&&... args) const
{
ScopedContext guard{snapshot_};
return std::invoke(fn_, std::forward<Args>(args)...);
}
[[nodiscard]] const ContextSnapshot& context() const noexcept
{
return snapshot_;
}
private:
ContextSnapshot snapshot_;
Fn fn_;
};
template <typename Fn>
[[nodiscard]] BoundContextCallable<std::decay_t<Fn>>
bind_context(ContextSnapshot snapshot, Fn&& fn)
{
return BoundContextCallable<std::decay_t<Fn>>{
std::move(snapshot),
std::forward<Fn>(fn)};
}
/// Coroutine awaitable adapter that binds an owned ContextSnapshot without
/// keeping a thread-local ScopedContext active across coroutine suspension.
template <typename Awaitable>
class ContextAwaitable
{
public:
ContextAwaitable(ContextSnapshot snapshot, Awaitable awaitable)
: snapshot_(std::move(snapshot))
, inner_(std::move(awaitable))
{
}
[[nodiscard]] decltype(auto) await_ready()
{
return inner_.await_ready();
}
[[nodiscard]] decltype(auto) await_suspend(std::coroutine_handle<> handle)
{
return inner_.await_suspend(handle);
}
decltype(auto) await_resume()
{
ScopedContext guard{snapshot_};
return inner_.await_resume();
}
[[nodiscard]] const ContextSnapshot& context() const noexcept
{
return snapshot_;
}
private:
ContextSnapshot snapshot_;
Awaitable inner_;
};
template <typename Awaitable>
[[nodiscard]] ContextAwaitable<std::decay_t<Awaitable>>
with_context(ContextSnapshot snapshot, Awaitable&& awaitable)
{
return ContextAwaitable<std::decay_t<Awaitable>>{
std::move(snapshot),
std::forward<Awaitable>(awaitable)};
}
} // namespace Void::Observability
+553
View File
@@ -0,0 +1,553 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <random>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Observability
{
enum class ObservabilityErrorCode : std::int32_t {
invalid_argument = 1,
invalid_traceparent = 2,
schema_conflict = 3,
capacity_exceeded = 4,
cardinality_exceeded = 5,
closed = 6,
cancelled = 7,
timeout = 8,
unsupported_capability = 9,
would_deadlock = 10,
quarantined = 11
};
[[nodiscard]] inline Void::Result::Error
make_observability_error(ObservabilityErrorCode code,
std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case ObservabilityErrorCode::invalid_argument:
case ObservabilityErrorCode::invalid_traceparent:
kind = ErrorKind::invalid_argument;
break;
case ObservabilityErrorCode::schema_conflict:
case ObservabilityErrorCode::would_deadlock:
kind = ErrorKind::conflict;
break;
case ObservabilityErrorCode::capacity_exceeded:
case ObservabilityErrorCode::cardinality_exceeded:
kind = ErrorKind::exhausted;
break;
case ObservabilityErrorCode::closed:
case ObservabilityErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case ObservabilityErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case ObservabilityErrorCode::unsupported_capability:
kind = ErrorKind::unsupported;
break;
case ObservabilityErrorCode::quarantined:
kind = ErrorKind::internal;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kObservabilityErrorDomain,
static_cast<std::int32_t>(code)}};
}
namespace Detail
{
[[nodiscard]] constexpr int hex_nibble(char c) noexcept
{
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return 10 + (c - 'a');
}
return -1;
}
template <std::size_t N>
[[nodiscard]] inline std::string bytes_to_hex(
const std::array<std::byte, N>& bytes)
{
constexpr char kHex[] = "0123456789abcdef";
std::string out;
out.resize(N * 2);
for (std::size_t i = 0; i < N; ++i) {
const auto v = static_cast<unsigned int>(bytes[i]);
out[i * 2] = kHex[(v >> 4) & 0x0Fu];
out[i * 2 + 1] = kHex[v & 0x0Fu];
}
return out;
}
template <std::size_t N>
[[nodiscard]] inline Void::Result::Result<std::array<std::byte, N>>
hex_to_bytes(std::string_view hex, std::string_view label)
{
if (hex.size() != N * 2) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_traceparent,
std::string{label} + " hex length is invalid"));
}
std::array<std::byte, N> out{};
for (std::size_t i = 0; i < N; ++i) {
const int hi = hex_nibble(hex[i * 2]);
const int lo = hex_nibble(hex[i * 2 + 1]);
if (hi < 0 || lo < 0) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_traceparent,
std::string{label} + " contains non-hex or non-lowercase characters"));
}
out[i] = static_cast<std::byte>((hi << 4) | lo);
}
return out;
}
template <std::size_t N, std::uniform_random_bit_generator G>
[[nodiscard]] inline std::array<std::byte, N> generate_nonzero_bytes(G& gen)
{
std::uniform_int_distribution<unsigned int> dist{0, 255};
std::array<std::byte, N> out{};
bool non_zero = false;
do {
non_zero = false;
for (auto& b : out) {
const auto v = static_cast<std::uint8_t>(dist(gen));
b = static_cast<std::byte>(v);
non_zero = non_zero || (v != 0);
}
} while (!non_zero);
return out;
}
} // namespace Detail
struct TraceId {
std::array<std::byte, 16> bytes{};
[[nodiscard]] constexpr bool operator==(const TraceId&) const noexcept = default;
[[nodiscard]] constexpr bool is_zero() const noexcept
{
for (const auto b : bytes) {
if (b != std::byte{0}) {
return false;
}
}
return true;
}
[[nodiscard]] std::string to_hex() const
{
return Detail::bytes_to_hex(bytes);
}
[[nodiscard]] static Void::Result::Result<TraceId>
from_hex(std::string_view hex)
{
auto parsed = Detail::hex_to_bytes<16>(hex, "TraceId");
if (!parsed) {
return Void::Result::fail(std::move(parsed).error());
}
TraceId id{*parsed};
if (id.is_zero()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_traceparent,
"TraceId must not be all zeros"));
}
return id;
}
[[nodiscard]] static Void::Result::Result<TraceId> generate()
{
try {
std::random_device rd;
return TraceId{Detail::generate_nonzero_bytes<16>(rd)};
} catch (...) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::unsupported_capability,
"System entropy unavailable for TraceId generation"));
}
}
[[nodiscard]] static TraceId generate_seeded(std::uint64_t seed)
{
std::mt19937_64 rng{seed};
return TraceId{Detail::generate_nonzero_bytes<16>(rng)};
}
};
struct SpanId {
std::array<std::byte, 8> bytes{};
[[nodiscard]] constexpr bool operator==(const SpanId&) const noexcept = default;
[[nodiscard]] constexpr bool is_zero() const noexcept
{
for (const auto b : bytes) {
if (b != std::byte{0}) {
return false;
}
}
return true;
}
[[nodiscard]] std::string to_hex() const
{
return Detail::bytes_to_hex(bytes);
}
[[nodiscard]] static Void::Result::Result<SpanId>
from_hex(std::string_view hex)
{
auto parsed = Detail::hex_to_bytes<8>(hex, "SpanId");
if (!parsed) {
return Void::Result::fail(std::move(parsed).error());
}
SpanId id{*parsed};
if (id.is_zero()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_traceparent,
"SpanId must not be all zeros"));
}
return id;
}
[[nodiscard]] static Void::Result::Result<SpanId> generate()
{
try {
std::random_device rd;
return SpanId{Detail::generate_nonzero_bytes<8>(rd)};
} catch (...) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::unsupported_capability,
"System entropy unavailable for SpanId generation"));
}
}
[[nodiscard]] static SpanId generate_seeded(std::uint64_t seed)
{
std::mt19937_64 rng{seed};
return SpanId{Detail::generate_nonzero_bytes<8>(rng)};
}
};
inline constexpr std::uint8_t kTraceFlagSampled = 0x01;
struct TraceContext {
TraceId trace_id{};
SpanId span_id{};
std::uint8_t flags{0};
[[nodiscard]] constexpr bool operator==(const TraceContext&) const noexcept = default;
[[nodiscard]] constexpr bool valid() const noexcept
{
return !trace_id.is_zero() && !span_id.is_zero();
}
[[nodiscard]] constexpr bool sampled() const noexcept
{
return (flags & kTraceFlagSampled) != 0;
}
[[nodiscard]] std::string to_traceparent() const
{
constexpr char kHex[] = "0123456789abcdef";
std::string out;
out.reserve(55);
out += "00-";
out += trace_id.to_hex();
out += '-';
out += span_id.to_hex();
out += '-';
out.push_back(kHex[(flags >> 4) & 0x0Fu]);
out.push_back(kHex[flags & 0x0Fu]);
return out;
}
[[nodiscard]] static Void::Result::Result<TraceContext>
from_traceparent(std::string_view header)
{
if (header.size() != 55 || header[0] != '0' || header[1] != '0' ||
header[2] != '-' || header[35] != '-' || header[52] != '-') {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_traceparent,
"Malformed W3C traceparent framing or version"));
}
auto tid = TraceId::from_hex(header.substr(3, 32));
if (!tid) {
return Void::Result::fail(std::move(tid).error());
}
auto sid = SpanId::from_hex(header.substr(36, 16));
if (!sid) {
return Void::Result::fail(std::move(sid).error());
}
auto flags_bytes = Detail::hex_to_bytes<1>(header.substr(53, 2), "TraceFlags");
if (!flags_bytes) {
return Void::Result::fail(std::move(flags_bytes).error());
}
return TraceContext{
*tid,
*sid,
static_cast<std::uint8_t>((*flags_bytes)[0])};
}
};
struct ContextLimits {
std::size_t max_baggage_items{16};
std::size_t max_baggage_bytes{2048};
std::size_t max_key_bytes{128};
std::size_t max_value_bytes{256};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (max_baggage_items == 0 || max_baggage_bytes == 0 ||
max_key_bytes == 0 || max_value_bytes == 0) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"ContextLimits values must be non-zero"));
}
return {};
}
};
struct BaggageItem {
std::string key;
std::string value;
[[nodiscard]] bool operator==(const BaggageItem&) const = default;
};
/// Immutable owning snapshot of TraceContext and bounded baggage carried across
/// threads, tasks, and coroutine resumptions.
class ContextSnapshot
{
public:
ContextSnapshot() = default;
[[nodiscard]] static Void::Result::Result<ContextSnapshot> create(
std::optional<TraceContext> trace = std::nullopt,
std::span<const BaggageItem> baggage = {},
ContextLimits limits = {})
{
if (auto v = limits.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
if (trace.has_value() && !trace->valid()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"TraceContext in ContextSnapshot must have non-zero IDs"));
}
auto data = std::make_shared<Data>();
data->limits = limits;
data->trace = trace;
for (const auto& item : baggage) {
if (auto r = add_or_replace(*data, item.key, item.value); !r) {
return Void::Result::fail(std::move(r).error());
}
}
return ContextSnapshot{std::move(data)};
}
[[nodiscard]] ContextSnapshot with_trace(TraceContext trace) const
{
auto next = data_ ? std::make_shared<Data>(*data_)
: std::make_shared<Data>();
next->trace = trace;
return ContextSnapshot{std::move(next)};
}
[[nodiscard]] Void::Result::Result<ContextSnapshot>
with_baggage(std::string_view key, std::string_view value) const
{
auto next = data_ ? std::make_shared<Data>(*data_)
: std::make_shared<Data>();
if (auto r = add_or_replace(*next, key, value); !r) {
return Void::Result::fail(std::move(r).error());
}
return ContextSnapshot{std::move(next)};
}
[[nodiscard]] std::optional<std::string_view>
find_baggage(std::string_view key) const noexcept
{
if (!data_) {
return std::nullopt;
}
for (const auto& item : data_->baggage) {
if (item.key == key) {
return std::string_view{item.value};
}
}
return std::nullopt;
}
[[nodiscard]] std::span<const BaggageItem> baggage() const noexcept
{
if (!data_) {
return {};
}
return data_->baggage;
}
[[nodiscard]] std::size_t baggage_bytes() const noexcept
{
return data_ ? data_->baggage_bytes : 0;
}
[[nodiscard]] const std::optional<TraceContext>& trace() const noexcept
{
static const std::optional<TraceContext> kEmpty;
return data_ ? data_->trace : kEmpty;
}
[[nodiscard]] bool empty() const noexcept
{
return !data_ || (!data_->trace.has_value() && data_->baggage.empty());
}
private:
struct Data {
ContextLimits limits{};
std::optional<TraceContext> trace{};
std::vector<BaggageItem> baggage{};
std::size_t baggage_bytes{0};
};
explicit ContextSnapshot(std::shared_ptr<const Data> data) noexcept
: data_(std::move(data))
{
}
static bool valid_key_or_value(std::string_view sv) noexcept
{
for (const unsigned char ch : sv) {
if (ch < 0x20 || ch == 0x7F) {
return false;
}
}
return true;
}
static Void::Result::Result<void>
add_or_replace(Data& data, std::string_view key, std::string_view value)
{
if (key.empty() || key.size() > data.limits.max_key_bytes ||
!valid_key_or_value(key)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid baggage key length or control character"));
}
if (value.size() > data.limits.max_value_bytes ||
!valid_key_or_value(value)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid baggage value length or control character"));
}
for (auto& existing : data.baggage) {
if (existing.key == key) {
const std::size_t without =
data.baggage_bytes - existing.value.size();
if (value.size() > data.limits.max_baggage_bytes - without) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::capacity_exceeded,
"ContextSnapshot baggage byte budget exceeded"));
}
existing.value.assign(value);
data.baggage_bytes = without + existing.value.size();
return {};
}
}
if (data.baggage.size() >= data.limits.max_baggage_items) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::capacity_exceeded,
"ContextSnapshot baggage item limit exceeded"));
}
const std::size_t added = key.size() + value.size();
if (added > data.limits.max_baggage_bytes - data.baggage_bytes) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::capacity_exceeded,
"ContextSnapshot baggage byte budget exceeded"));
}
data.baggage.push_back(BaggageItem{std::string{key}, std::string{value}});
data.baggage_bytes += added;
return {};
}
std::shared_ptr<const Data> data_{};
};
/// Move-only RAII thread-local context scope that always restores the prior
/// snapshot on normal exit or stack unwind.
class ScopedContext
{
public:
explicit ScopedContext(ContextSnapshot snapshot) noexcept
: previous_(std::exchange(tls_slot(), std::move(snapshot)))
, active_(true)
{
}
~ScopedContext() noexcept
{
if (active_) {
tls_slot() = std::move(previous_);
}
}
ScopedContext(ScopedContext&& other) noexcept
: previous_(std::move(other.previous_))
, active_(std::exchange(other.active_, false))
{
}
ScopedContext& operator=(ScopedContext&&) = delete;
ScopedContext(const ScopedContext&) = delete;
ScopedContext& operator=(const ScopedContext&) = delete;
[[nodiscard]] static ContextSnapshot current() noexcept
{
return tls_slot();
}
private:
static ContextSnapshot& tls_slot() noexcept
{
static thread_local ContextSnapshot current_context{};
return current_context;
}
ContextSnapshot previous_{};
bool active_{false};
};
} // namespace Void::Observability
+428
View File
@@ -0,0 +1,428 @@
#pragma once
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <span>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Observability
{
enum class MetricKind : std::uint8_t {
counter = 0,
gauge,
histogram
};
struct AttributeView {
std::string_view key{};
std::string_view value{};
};
struct MetricPoint {
std::string_view name{};
MetricKind kind{MetricKind::counter};
double value{0.0};
std::uint64_t integer_delta{0};
std::span<const AttributeView> attributes{};
};
struct DiagnosticEvent {
std::string_view component{};
std::string_view message{};
bool is_error{false};
};
/// Zero-dependency synchronous observation callback table.
/// Null hooks perform no allocation or backend initialization.
struct ObservationHooks {
void* state{nullptr};
void (*record)(void* state, const MetricPoint& point) noexcept{nullptr};
void (*diagnostic)(void* state, const DiagnosticEvent& event) noexcept{nullptr};
[[nodiscard]] constexpr bool active() const noexcept
{
return record != nullptr || diagnostic != nullptr;
}
void emit_metric(const MetricPoint& point) const noexcept
{
if (record != nullptr) {
record(state, point);
}
}
void emit_diagnostic(const DiagnosticEvent& event) const noexcept
{
if (diagnostic != nullptr) {
diagnostic(state, event);
}
}
};
inline constexpr ObservationHooks kNullObservationHooks{};
enum class DrainStatus : std::uint8_t {
drained = 0,
not_found,
would_deadlock
};
using HookRegistrationId = std::uint64_t;
namespace Detail
{
struct HookControl {
HookRegistrationId id{0};
ObservationHooks raw_hooks{};
std::function<void(const MetricPoint&)> guarded_record{};
std::function<void(const DiagnosticEvent&)> guarded_diagnostic{};
bool is_guarded{false};
std::shared_ptr<const void> owner{};
std::atomic<bool> detached{false};
std::atomic<bool> quarantined{false};
std::atomic<std::size_t> active_calls{0};
std::atomic<std::uint64_t> failed_calls{0};
std::mutex drain_mutex;
std::condition_variable drain_cv;
};
inline thread_local std::vector<const HookControl*> t_active_hook_controls;
struct HookCallScope {
const HookControl* control{nullptr};
explicit HookCallScope(const HookControl* ctrl) : control(ctrl)
{
if (control != nullptr) {
t_active_hook_controls.push_back(control);
}
}
~HookCallScope() noexcept
{
if (control != nullptr && !t_active_hook_controls.empty()) {
t_active_hook_controls.pop_back();
}
}
HookCallScope(const HookCallScope&) = delete;
HookCallScope& operator=(const HookCallScope&) = delete;
[[nodiscard]] static bool is_active_on_thread(const HookControl* ctrl) noexcept
{
for (const auto* entry : t_active_hook_controls) {
if (entry == ctrl) {
return true;
}
}
return false;
}
};
} // namespace Detail
/// Move-only RAII lease retaining hook callback/owner state across an invocation
/// outside any internal configuration mutex.
class HookLease
{
public:
HookLease() noexcept = default;
~HookLease() noexcept { reset(); }
HookLease(HookLease&& other) noexcept
: control_(std::exchange(other.control_, nullptr))
{
}
HookLease& operator=(HookLease&& other) noexcept
{
if (this != &other) {
reset();
control_ = std::exchange(other.control_, nullptr);
}
return *this;
}
HookLease(const HookLease&) = delete;
HookLease& operator=(const HookLease&) = delete;
[[nodiscard]] explicit operator bool() const noexcept
{
return control_ != nullptr;
}
[[nodiscard]] HookRegistrationId registration_id() const noexcept
{
return control_ != nullptr ? control_->id : 0;
}
[[nodiscard]] bool is_quarantined() const noexcept
{
return control_ != nullptr &&
control_->quarantined.load(std::memory_order_acquire);
}
void reset() noexcept
{
auto ctrl = std::exchange(control_, nullptr);
if (!ctrl) {
return;
}
if (ctrl->active_calls.fetch_sub(1, std::memory_order_acq_rel) == 1) {
std::lock_guard lock{ctrl->drain_mutex};
ctrl->drain_cv.notify_all();
}
}
private:
friend class HookSlot;
explicit HookLease(std::shared_ptr<Detail::HookControl> ctrl) noexcept
: control_(std::move(ctrl))
{
}
std::shared_ptr<Detail::HookControl> control_{};
};
/// Thread-safe hook registration owner supporting safe replacement, explicit
/// detach-and-drain synchronization, recursion suppression, and exception quarantine.
class HookSlot
{
public:
HookSlot() = default;
~HookSlot() noexcept { (void)detach_and_drain(0); }
HookSlot(const HookSlot&) = delete;
HookSlot& operator=(const HookSlot&) = delete;
HookSlot(HookSlot&&) = delete;
HookSlot& operator=(HookSlot&&) = delete;
HookRegistrationId install(ObservationHooks hooks,
std::shared_ptr<const void> owner = {})
{
if (!hooks.active() && !owner) {
std::shared_ptr<Detail::HookControl> old;
{
std::lock_guard lock{mutex_};
old = std::exchange(active_, nullptr);
if (old) {
old->detached.store(true, std::memory_order_release);
}
}
return 0;
}
auto next = std::make_shared<Detail::HookControl>();
next->raw_hooks = hooks;
next->owner = std::move(owner);
next->is_guarded = false;
return swap_active(std::move(next));
}
HookRegistrationId install_guarded(
std::function<void(const MetricPoint&)> record_fn,
std::function<void(const DiagnosticEvent&)> diagnostic_fn = {},
std::shared_ptr<const void> owner = {})
{
auto next = std::make_shared<Detail::HookControl>();
next->guarded_record = std::move(record_fn);
next->guarded_diagnostic = std::move(diagnostic_fn);
next->owner = std::move(owner);
next->is_guarded = true;
return swap_active(std::move(next));
}
[[nodiscard]] HookLease acquire_lease() const noexcept
{
std::lock_guard lock{mutex_};
if (!active_ || active_->detached.load(std::memory_order_acquire)) {
return {};
}
active_->active_calls.fetch_add(1, std::memory_order_acq_rel);
return HookLease{active_};
}
DrainStatus detach_and_drain(HookRegistrationId id = 0) noexcept
{
std::shared_ptr<Detail::HookControl> target;
{
std::lock_guard lock{mutex_};
prune_retired_locked();
if (id == 0) {
target = active_;
} else if (active_ && active_->id == id) {
target = active_;
} else if (const auto it = known_.find(id); it != known_.end()) {
target = it->second.lock();
}
if (!target) {
return DrainStatus::not_found;
}
if (Detail::HookCallScope::is_active_on_thread(target.get())) {
return DrainStatus::would_deadlock;
}
target->detached.store(true, std::memory_order_release);
if (target == active_) {
active_.reset();
}
known_.erase(target->id);
}
{
std::unique_lock drain_lock{target->drain_mutex};
target->drain_cv.wait(drain_lock, [&target] {
return target->active_calls.load(std::memory_order_acquire) == 0;
});
}
target.reset();
return DrainStatus::drained;
}
void invoke_metric(const MetricPoint& point) noexcept
{
auto lease = acquire_lease();
if (!lease) {
return;
}
auto* ctrl = lease.control_.get();
if (ctrl->quarantined.load(std::memory_order_acquire)) {
return;
}
if (Detail::HookCallScope::is_active_on_thread(ctrl)) {
reentrant_calls_.fetch_add(1, std::memory_order_relaxed);
return;
}
Detail::HookCallScope scope{ctrl};
if (!ctrl->is_guarded) {
ctrl->raw_hooks.emit_metric(point);
return;
}
if (!ctrl->guarded_record) {
return;
}
try {
ctrl->guarded_record(point);
} catch (...) {
ctrl->failed_calls.fetch_add(1, std::memory_order_relaxed);
failed_calls_.fetch_add(1, std::memory_order_relaxed);
ctrl->quarantined.store(true, std::memory_order_release);
}
}
void invoke_diagnostic(const DiagnosticEvent& event) noexcept
{
auto lease = acquire_lease();
if (!lease) {
return;
}
auto* ctrl = lease.control_.get();
if (ctrl->quarantined.load(std::memory_order_acquire)) {
return;
}
if (Detail::HookCallScope::is_active_on_thread(ctrl)) {
reentrant_calls_.fetch_add(1, std::memory_order_relaxed);
return;
}
Detail::HookCallScope scope{ctrl};
if (!ctrl->is_guarded) {
ctrl->raw_hooks.emit_diagnostic(event);
return;
}
if (!ctrl->guarded_diagnostic) {
return;
}
try {
ctrl->guarded_diagnostic(event);
} catch (...) {
ctrl->failed_calls.fetch_add(1, std::memory_order_relaxed);
failed_calls_.fetch_add(1, std::memory_order_relaxed);
ctrl->quarantined.store(true, std::memory_order_release);
}
}
[[nodiscard]] bool active() const noexcept
{
std::lock_guard lock{mutex_};
return active_ != nullptr && !active_->detached.load(std::memory_order_acquire);
}
[[nodiscard]] bool is_quarantined() const noexcept
{
std::lock_guard lock{mutex_};
return active_ != nullptr &&
active_->quarantined.load(std::memory_order_acquire);
}
void reset_quarantine() noexcept
{
std::lock_guard lock{mutex_};
if (active_) {
active_->quarantined.store(false, std::memory_order_release);
}
}
[[nodiscard]] std::uint64_t failed_calls() const noexcept
{
return failed_calls_.load(std::memory_order_relaxed);
}
[[nodiscard]] std::uint64_t reentrant_calls() const noexcept
{
return reentrant_calls_.load(std::memory_order_relaxed);
}
private:
HookRegistrationId swap_active(std::shared_ptr<Detail::HookControl> next)
{
std::shared_ptr<Detail::HookControl> old;
HookRegistrationId id = 0;
{
std::lock_guard lock{mutex_};
prune_retired_locked();
id = ++next_id_;
next->id = id;
known_.emplace(id, next);
old = std::exchange(active_, std::move(next));
if (old) {
old->detached.store(true, std::memory_order_release);
}
}
old.reset();
return id;
}
void prune_retired_locked()
{
for (auto it = known_.begin(); it != known_.end();) {
if (it->second.expired()) {
it = known_.erase(it);
} else {
++it;
}
}
}
mutable std::mutex mutex_;
HookRegistrationId next_id_{0};
std::shared_ptr<Detail::HookControl> active_{};
std::unordered_map<HookRegistrationId, std::weak_ptr<Detail::HookControl>> known_;
std::atomic<std::uint64_t> failed_calls_{0};
std::atomic<std::uint64_t> reentrant_calls_{0};
};
} // namespace Void::Observability
+144
View File
@@ -0,0 +1,144 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Observability/Context.hpp>
#include <Void/Observability/Hooks.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Observability
{
struct MetricsLimits {
std::size_t max_instruments{256};
std::size_t max_series_per_instrument{1024};
std::size_t max_total_series{4096};
std::size_t max_labels_per_point{8};
std::size_t max_key_bytes{128};
std::size_t max_value_bytes{256};
std::size_t max_producer_shards{32};
std::size_t max_storage_bytes{32ULL * 1024ULL * 1024ULL};
[[nodiscard]] Void::Result::Result<void> validate() const;
};
[[nodiscard]] inline std::vector<double> default_duration_buckets_seconds()
{
return {0.0001, 0.0005, 0.001, 0.005, 0.01, 0.025, 0.05,
0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0};
}
struct InstrumentSpec {
std::string name{};
std::string unit{};
MetricKind kind{MetricKind::counter};
std::vector<std::string> label_keys{};
std::vector<double> bucket_bounds{};
};
struct InstrumentHandle {
std::size_t index{0};
std::uint64_t registry_id{0};
[[nodiscard]] constexpr bool valid() const noexcept
{
return registry_id != 0;
}
};
struct HistogramSnapshot {
std::vector<double> bounds{};
std::vector<std::uint64_t> bucket_counts{};
std::uint64_t count{0};
double sum{0.0};
};
struct SeriesSnapshot {
std::vector<std::pair<std::string, std::string>> labels{};
bool is_overflow{false};
std::uint64_t counter_value{0};
bool counter_saturated{false};
double gauge_value{0.0};
bool has_gauge_sample{false};
Void::Time::MonotonicClock::time_point gauge_timestamp{};
HistogramSnapshot histogram{};
};
struct InstrumentSnapshot {
InstrumentSpec spec{};
std::vector<SeriesSnapshot> series{};
std::uint64_t dropped_series{0};
std::uint64_t overflow_events{0};
};
struct MetricsSnapshot {
std::uint64_t epoch{1};
std::vector<InstrumentSnapshot> instruments{};
std::uint64_t dropped_series{0};
std::uint64_t overflow_events{0};
std::uint64_t rejected_invalid_points{0};
std::uint64_t shared_shard_fallbacks{0};
std::uint64_t unregistered_hook_points{0};
std::size_t shard_count{0};
std::size_t estimated_bytes{0};
};
/// Thread-safe, sharded, cardinality- and byte-bounded metric registry with
/// frozen schemas and cumulative snapshot export.
class MetricRegistry
{
public:
[[nodiscard]] static Void::Result::Result<MetricRegistry> create(
MetricsLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
MetricRegistry(MetricRegistry&&) noexcept = default;
MetricRegistry& operator=(MetricRegistry&&) noexcept = default;
MetricRegistry(const MetricRegistry&) = delete;
MetricRegistry& operator=(const MetricRegistry&) = delete;
~MetricRegistry();
[[nodiscard]] Void::Result::Result<InstrumentHandle>
register_instrument(InstrumentSpec spec);
[[nodiscard]] Void::Result::Result<void> add_counter(
InstrumentHandle handle,
std::uint64_t delta,
std::span<const AttributeView> attributes = {});
[[nodiscard]] Void::Result::Result<void> set_gauge(
InstrumentHandle handle,
double value,
std::span<const AttributeView> attributes = {});
[[nodiscard]] Void::Result::Result<void> observe_histogram(
InstrumentHandle handle,
double value,
std::span<const AttributeView> attributes = {});
[[nodiscard]] MetricsSnapshot snapshot() const;
void reset_epoch();
[[nodiscard]] ObservationHooks make_hooks() const noexcept;
[[nodiscard]] std::shared_ptr<const void> keepalive() const noexcept;
[[nodiscard]] const MetricsLimits& limits() const noexcept;
private:
struct Impl;
explicit MetricRegistry(std::shared_ptr<Impl> impl) noexcept;
std::shared_ptr<Impl> impl_;
};
} // namespace Void::Observability
@@ -0,0 +1,7 @@
#pragma once
#include <Void/Observability/AsyncContext.hpp>
#include <Void/Observability/Context.hpp>
#include <Void/Observability/Hooks.hpp>
#include <Void/Observability/Metrics.hpp>
#include <Void/Observability/Tracing.hpp>
+243
View File
@@ -0,0 +1,243 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Observability/Context.hpp>
#include <Void/Observability/Metrics.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Observability
{
struct TracingLimits {
std::size_t max_active_spans{1024};
std::size_t max_active_bytes{8ULL * 1024ULL * 1024ULL};
std::size_t max_completed_spans{8192};
std::size_t max_completed_bytes{16ULL * 1024ULL * 1024ULL};
std::size_t max_attributes_per_span{32};
std::size_t max_events_per_span{32};
std::size_t max_bytes_per_span{8ULL * 1024ULL};
std::size_t max_key_bytes{128};
std::size_t max_value_bytes{256};
std::size_t max_export_batch_spans{256};
std::size_t max_export_batch_bytes{512ULL * 1024ULL};
std::uint64_t root_sample_denominator{100};
std::size_t max_export_retries{2};
std::chrono::nanoseconds export_retry_budget{std::chrono::seconds{5}};
[[nodiscard]] Void::Result::Result<void> validate() const;
};
enum class SpanStatus : std::uint8_t {
unset = 0,
ok,
error,
abandoned
};
struct SpanSpec {
std::string name{};
std::vector<std::pair<std::string, std::string>> attributes{};
std::optional<TraceId> explicit_root_trace_id{};
};
struct SpanEvent {
std::string name{};
Void::Time::MonotonicClock::time_point timestamp{};
};
struct CompletedSpan {
TraceContext context{};
std::optional<SpanId> parent_span_id{};
std::string name{};
Void::Time::MonotonicClock::time_point start_time{};
Void::Time::MonotonicClock::time_point end_time{};
Void::Time::CivilClock::time_point civil_start_time{};
SpanStatus status{SpanStatus::unset};
std::vector<std::pair<std::string, std::string>> attributes{};
std::vector<SpanEvent> events{};
bool truncated{false};
std::size_t estimated_bytes{0};
};
struct ExportBatch {
std::vector<CompletedSpan> spans{};
std::size_t estimated_bytes{0};
};
struct ExportReport {
std::uint64_t exported_spans{0};
std::uint64_t failed_spans{0};
std::uint64_t dropped_spans{0};
std::uint64_t duplicate_ends{0};
std::uint64_t retries{0};
bool timed_out{false};
bool cancelled{false};
};
struct ExportOptions {
std::stop_token stop{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
};
struct TracerStats {
std::size_t active_spans{0};
std::size_t active_bytes{0};
std::size_t completed_spans{0};
std::size_t completed_bytes{0};
std::size_t in_flight_export_bytes{0};
std::uint64_t dropped_active_spans{0};
std::uint64_t dropped_completed_spans{0};
std::uint64_t duplicate_ends{0};
std::uint64_t abandoned_spans{0};
std::uint64_t exported_spans{0};
std::uint64_t failed_exports{0};
std::uint64_t reentrant_export_drops{0};
bool closed{false};
};
class SpanExporter
{
public:
virtual ~SpanExporter() = default;
[[nodiscard]] virtual Void::Result::Result<void>
export_spans(std::span<const CompletedSpan> spans) = 0;
};
class CallbackSpanExporter final : public SpanExporter
{
public:
using Callback =
std::function<Void::Result::Result<void>(std::span<const CompletedSpan>)>;
explicit CallbackSpanExporter(Callback callback);
[[nodiscard]] Void::Result::Result<void>
export_spans(std::span<const CompletedSpan> spans) override;
[[nodiscard]] std::uint64_t reentrant_drops() const noexcept
{
return reentrant_drops_.load(std::memory_order_relaxed);
}
private:
Callback callback_;
std::atomic<std::uint64_t> reentrant_drops_{0};
};
class TextSnapshotExporter final : public SpanExporter
{
public:
explicit TextSnapshotExporter(
std::size_t max_output_bytes = 64ULL * 1024ULL);
[[nodiscard]] Void::Result::Result<void>
export_spans(std::span<const CompletedSpan> spans) override;
[[nodiscard]] static std::string render_metrics(
const MetricsSnapshot& metrics,
std::size_t max_output_bytes = 64ULL * 1024ULL);
[[nodiscard]] static std::string render_spans(
std::span<const CompletedSpan> spans,
std::size_t max_output_bytes = 64ULL * 1024ULL);
[[nodiscard]] std::string text() const;
void clear();
private:
std::size_t max_output_bytes_;
mutable std::mutex mutex_;
std::string buffer_;
};
class Tracer;
/// Move-only span handle owning child TraceContext (never a raw parent pointer).
/// Destroying an active unended handle terminates it with SpanStatus::abandoned.
class Span
{
public:
Span() = default;
~Span() noexcept;
Span(Span&& other) noexcept;
Span& operator=(Span&& other) noexcept;
Span(const Span&) = delete;
Span& operator=(const Span&) = delete;
[[nodiscard]] const ContextSnapshot& context() const noexcept
{
return context_;
}
[[nodiscard]] bool is_recording() const noexcept
{
return state_ != nullptr && !ended_;
}
void set_attribute(std::string_view key, std::string_view value);
void add_event(std::string_view name);
void end(SpanStatus status = SpanStatus::ok) noexcept;
private:
friend class Tracer;
struct State;
Span(ContextSnapshot context, std::shared_ptr<State> state) noexcept;
ContextSnapshot context_{};
std::shared_ptr<State> state_{};
bool ended_{false};
};
/// Head-sampled, byte-bounded tracer with explicit synchronous batch export
/// and no implicit background worker threads.
class Tracer
{
public:
[[nodiscard]] static Void::Result::Result<Tracer> create(
TracingLimits limits = {},
std::shared_ptr<SpanExporter> exporter = nullptr,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
const Void::Time::CivilClock& civil_clock =
Void::Time::SystemCivilClock::instance());
Tracer(Tracer&&) noexcept = default;
Tracer& operator=(Tracer&&) noexcept = default;
Tracer(const Tracer&) = delete;
Tracer& operator=(const Tracer&) = delete;
~Tracer();
[[nodiscard]] Span start_span(const ContextSnapshot& parent, SpanSpec spec);
[[nodiscard]] ExportReport flush(ExportOptions options = {});
[[nodiscard]] ExportReport close(ExportOptions options = {});
[[nodiscard]] TracerStats stats() const;
private:
friend class Span;
struct Impl;
explicit Tracer(std::shared_ptr<Impl> impl) noexcept;
std::shared_ptr<Impl> impl_;
};
} // namespace Void::Observability
+712
View File
@@ -0,0 +1,712 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Retry.hpp>
#include <Void/Resilience/Resilience.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <stop_token>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Resilience
{
struct BulkheadConfig {
std::size_t max_active{64};
std::size_t max_waiting{128};
std::size_t max_retained_bytes{8ULL * 1024ULL * 1024ULL};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (max_active == 0 || max_retained_bytes == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BulkheadConfig::max_active and max_retained_bytes must be positive"));
}
return {};
}
};
class Bulkhead;
namespace Detail
{
struct BulkheadState;
struct BulkheadAccess;
} // namespace Detail
class BulkheadPermit
{
public:
BulkheadPermit() noexcept = default;
~BulkheadPermit() noexcept { release(); }
BulkheadPermit(BulkheadPermit&& other) noexcept
: state_(std::move(other.state_))
, active_(std::exchange(other.active_, false))
{
}
BulkheadPermit& operator=(BulkheadPermit&& other) noexcept
{
if (this != &other) {
release();
state_ = std::move(other.state_);
active_ = std::exchange(other.active_, false);
}
return *this;
}
BulkheadPermit(const BulkheadPermit&) = delete;
BulkheadPermit& operator=(const BulkheadPermit&) = delete;
void release() noexcept;
[[nodiscard]] explicit operator bool() const noexcept { return active_; }
private:
friend class Bulkhead;
friend struct Detail::BulkheadState;
friend struct Detail::BulkheadAccess;
BulkheadPermit(std::shared_ptr<Detail::BulkheadState> state,
bool active) noexcept
: state_(std::move(state)), active_(active)
{
}
std::shared_ptr<Detail::BulkheadState> state_{};
bool active_{false};
};
namespace Detail
{
struct WaiterNode;
struct BulkheadState : std::enable_shared_from_this<BulkheadState> {
static constexpr std::size_t kWaiterFootprintBytes = 256;
BulkheadConfig config{};
const Void::Time::MonotonicClock* clock{nullptr};
std::mutex mutex{};
bool closed{false};
std::size_t active{0};
std::size_t retained_bytes{0};
std::deque<std::shared_ptr<WaiterNode>> waiters{};
std::uint64_t expired_evictions{0};
BulkheadState(BulkheadConfig cfg, const Void::Time::MonotonicClock* clk)
: config(cfg)
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
{
}
};
struct WaiterNode {
std::shared_ptr<Async::OperationState<BulkheadPermit>> op{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
std::atomic<bool> resolved{false};
struct StopHandler {
std::weak_ptr<BulkheadState> state;
std::weak_ptr<WaiterNode> node;
void operator()() const noexcept;
};
std::optional<std::stop_callback<StopHandler>> stop_cb{};
};
struct PendingSettlement {
std::shared_ptr<Async::OperationState<BulkheadPermit>> op;
bool granted{false};
ResilienceErrorCode err_code{ResilienceErrorCode::cancelled};
std::string message{};
};
struct BulkheadAccess {
[[nodiscard]] static BulkheadPermit make_permit(
std::shared_ptr<BulkheadState> state) noexcept
{
return BulkheadPermit{std::move(state), true};
}
};
inline void dispatch_settlements(const std::shared_ptr<BulkheadState>& state,
std::vector<PendingSettlement>& list) noexcept
{
for (auto& item : list) {
if (!item.op) {
continue;
}
if (item.granted) {
if (auto ticket = item.op->try_commit_value(
BulkheadAccess::make_permit(state));
ticket.has_value()) {
ticket->dispatch();
}
} else {
const auto kind =
item.err_code == ResilienceErrorCode::timeout
? Async::DomainOutcomeKind::failed
: Async::DomainOutcomeKind::cancelled;
if (auto ticket = item.op->try_commit_error(
make_resilience_error(item.err_code, std::move(item.message)),
kind);
ticket.has_value()) {
ticket->dispatch();
}
}
}
}
inline void evict_expired_locked(BulkheadState& st,
std::vector<PendingSettlement>& settlements)
{
const auto now = st.clock->now();
std::deque<std::shared_ptr<WaiterNode>> remaining;
while (!st.waiters.empty()) {
auto node = std::move(st.waiters.front());
st.waiters.pop_front();
if (node->resolved.load(std::memory_order_acquire)) {
continue;
}
const bool stopped = node->op->stop_requested();
const bool timed_out =
node->deadline.has_value() && now >= *node->deadline;
if (stopped || timed_out) {
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
st.retained_bytes =
st.retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st.retained_bytes - BulkheadState::kWaiterFootprintBytes)
: 0;
if (timed_out) {
++st.expired_evictions;
}
settlements.push_back(PendingSettlement{
node->op,
false,
timed_out ? ResilienceErrorCode::timeout
: ResilienceErrorCode::cancelled,
timed_out ? "Bulkhead waiter deadline expired"
: "Bulkhead waiter cancelled"});
}
} else {
remaining.push_back(std::move(node));
}
}
st.waiters = std::move(remaining);
}
inline void grant_available_locked(BulkheadState& st,
std::vector<PendingSettlement>& settlements)
{
while (!st.closed && st.active < st.config.max_active && !st.waiters.empty()) {
auto node = std::move(st.waiters.front());
st.waiters.pop_front();
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
st.retained_bytes =
st.retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st.retained_bytes - BulkheadState::kWaiterFootprintBytes)
: 0;
++st.active;
settlements.push_back(PendingSettlement{
node->op, true, ResilienceErrorCode::cancelled, {}});
}
}
}
inline void WaiterNode::StopHandler::operator()() const noexcept
{
auto st = state.lock();
auto nd = node.lock();
if (!st || !nd) {
return;
}
std::vector<PendingSettlement> settlements;
{
std::lock_guard lock{st->mutex};
if (!nd->resolved.exchange(true, std::memory_order_acq_rel)) {
for (auto it = st->waiters.begin(); it != st->waiters.end(); ++it) {
if (it->get() == nd.get()) {
st->waiters.erase(it);
st->retained_bytes =
st->retained_bytes >= BulkheadState::kWaiterFootprintBytes
? (st->retained_bytes -
BulkheadState::kWaiterFootprintBytes)
: 0;
break;
}
}
settlements.push_back(PendingSettlement{
nd->op,
false,
ResilienceErrorCode::cancelled,
"Bulkhead waiter cancelled"});
}
}
dispatch_settlements(st, settlements);
}
} // namespace Detail
inline void BulkheadPermit::release() noexcept
{
if (!state_ || !active_) {
return;
}
active_ = false;
auto st = std::move(state_);
std::vector<Detail::PendingSettlement> settlements;
{
std::lock_guard lock{st->mutex};
if (st->active > 0) {
--st->active;
}
Detail::evict_expired_locked(*st, settlements);
Detail::grant_available_locked(*st, settlements);
}
Detail::dispatch_settlements(st, settlements);
}
/// Asynchronous FIFO concurrency bulkhead with bounded active + waiting queue,
/// expired-waiter eviction before admission, stop cancellation, and graceful close().
class Bulkhead
{
public:
[[nodiscard]] static Void::Result::Result<Bulkhead> create(
BulkheadConfig config = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance())
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
return Bulkhead{std::make_shared<Detail::BulkheadState>(config, &clock)};
}
[[nodiscard]] Void::Result::Result<BulkheadPermit> try_acquire()
{
std::vector<Detail::PendingSettlement> settlements;
bool granted = false;
bool is_closed = false;
{
std::lock_guard lock{state_->mutex};
Detail::evict_expired_locked(*state_, settlements);
if (state_->closed) {
is_closed = true;
} else if (state_->waiters.empty() &&
state_->active < state_->config.max_active) {
++state_->active;
granted = true;
}
}
Detail::dispatch_settlements(state_, settlements);
if (is_closed) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::closed, "Bulkhead is closed"));
}
if (!granted) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::bulkhead_full,
"Bulkhead active concurrency limit reached"));
}
return BulkheadPermit{state_, true};
}
[[nodiscard]] Void::Coro::Task<Void::Result::Result<BulkheadPermit>>
acquire_async(Async::OperationOptions options = {},
Async::Executor* resume_exec = nullptr)
{
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Bulkhead acquisition cancelled before queueing"));
}
if (Async::is_deadline_expired(options, *state_->clock)) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Bulkhead acquisition deadline expired before queueing"));
}
std::vector<Detail::PendingSettlement> settlements;
std::shared_ptr<Detail::WaiterNode> node;
std::optional<Void::Result::Error> immediate_error;
bool immediate_grant = false;
{
std::lock_guard lock{state_->mutex};
Detail::evict_expired_locked(*state_, settlements);
if (state_->closed) {
immediate_error = make_resilience_error(
ResilienceErrorCode::closed, "Bulkhead is closed");
} else if (state_->waiters.empty() &&
state_->active < state_->config.max_active) {
++state_->active;
immediate_grant = true;
} else if (state_->waiters.size() >= state_->config.max_waiting ||
Detail::BulkheadState::kWaiterFootprintBytes >
state_->config.max_retained_bytes -
std::min(state_->retained_bytes,
state_->config.max_retained_bytes)) {
immediate_error = make_resilience_error(
ResilienceErrorCode::bulkhead_full,
"Bulkhead waiting queue full");
} else {
node = std::make_shared<Detail::WaiterNode>();
node->op = Async::OperationState<BulkheadPermit>::create(
options, resume_exec, Async::StopBehavior::notify_only);
node->deadline = options.deadline;
state_->retained_bytes += Detail::BulkheadState::kWaiterFootprintBytes;
state_->waiters.push_back(node);
if (options.stop.stop_possible()) {
node->stop_cb.emplace(
options.stop,
Detail::WaiterNode::StopHandler{state_, node});
}
}
}
Detail::dispatch_settlements(state_, settlements);
if (immediate_error.has_value()) {
co_return Void::Result::fail(std::move(*immediate_error));
}
if (immediate_grant) {
co_return BulkheadPermit{state_, true};
}
auto res = co_await node->op->awaitable(resume_exec);
node->stop_cb.reset();
co_return res;
}
std::size_t evict_expired()
{
std::vector<Detail::PendingSettlement> settlements;
std::size_t evicted = 0;
{
std::lock_guard lock{state_->mutex};
const auto before = state_->waiters.size();
Detail::evict_expired_locked(*state_, settlements);
Detail::grant_available_locked(*state_, settlements);
evicted = before >= state_->waiters.size()
? (before - state_->waiters.size())
: 0;
}
Detail::dispatch_settlements(state_, settlements);
return evicted;
}
void close()
{
std::vector<Detail::PendingSettlement> settlements;
{
std::lock_guard lock{state_->mutex};
state_->closed = true;
while (!state_->waiters.empty()) {
auto node = std::move(state_->waiters.front());
state_->waiters.pop_front();
if (!node->resolved.exchange(true, std::memory_order_acq_rel)) {
state_->retained_bytes =
state_->retained_bytes >=
Detail::BulkheadState::kWaiterFootprintBytes
? (state_->retained_bytes -
Detail::BulkheadState::kWaiterFootprintBytes)
: 0;
settlements.push_back(Detail::PendingSettlement{
node->op,
false,
ResilienceErrorCode::closed,
"Bulkhead closed"});
}
}
}
Detail::dispatch_settlements(state_, settlements);
}
[[nodiscard]] std::size_t active_count() const
{
std::lock_guard lock{state_->mutex};
return state_->active;
}
[[nodiscard]] std::size_t waiting_count() const
{
std::lock_guard lock{state_->mutex};
return state_->waiters.size();
}
[[nodiscard]] std::size_t retained_bytes() const
{
std::lock_guard lock{state_->mutex};
return state_->retained_bytes;
}
[[nodiscard]] std::uint64_t expired_evictions() const
{
std::lock_guard lock{state_->mutex};
return state_->expired_evictions;
}
private:
explicit Bulkhead(std::shared_ptr<Detail::BulkheadState> state) noexcept
: state_(std::move(state))
{
}
std::shared_ptr<Detail::BulkheadState> state_;
};
// ── Composition & Retry Pipeline ─────────────────────────────────────────────
struct ResilientRetryConfig {
std::size_t max_attempts{3};
std::chrono::milliseconds base_delay{100};
std::chrono::milliseconds max_delay{2000};
Void::Retry::JitterMode jitter{Void::Retry::JitterMode::Full};
bool replay_safe{false};
std::optional<std::uint64_t> deterministic_seed{};
};
struct AttemptClassification {
Outcome outcome{Outcome::neutral};
bool retryable{false};
};
struct ResiliencePipeline {
TokenBucket* rate_limiter{nullptr};
double rate_cost{1.0};
Bulkhead* bulkhead{nullptr};
Breaker* breaker{nullptr};
ResilientRetryConfig retry{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
Observability::HookSlot* hooks{nullptr};
std::function<bool(std::chrono::nanoseconds, const Async::OperationOptions&)>
wait_fn{};
};
namespace Detail
{
template <typename T>
struct IsCoroTask : std::false_type {};
template <typename T>
struct IsCoroTask<Void::Coro::Task<T>> : std::true_type {};
template <typename T>
struct UnwrapTask {
using type = T;
};
template <typename T>
struct UnwrapTask<Void::Coro::Task<T>> {
using type = T;
};
[[nodiscard]] inline std::chrono::nanoseconds compute_jittered_backoff(
const ResilientRetryConfig& cfg,
std::size_t attempt,
std::optional<std::mt19937_64>& seeded_rng)
{
const Void::Retry::ExponentialBackoff backoff{cfg.base_delay, cfg.max_delay, 2.0};
const auto base = backoff.delay(attempt);
if (base.count() <= 0) {
return std::chrono::nanoseconds{0};
}
const long long base_ms = base.count();
const long long floor_ms =
(cfg.jitter == Void::Retry::JitterMode::Equal) ? (base_ms / 2) : 0;
std::uniform_int_distribution<long long> dist{0, base_ms - floor_ms};
long long drawn = 0;
if (seeded_rng.has_value()) {
drawn = dist(*seeded_rng);
} else {
thread_local std::mt19937_64 tls_rng{std::random_device{}()};
drawn = dist(tls_rng);
}
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::milliseconds{floor_ms + drawn});
}
[[nodiscard]] inline bool wait_with_stop(
std::chrono::nanoseconds delay,
const Async::OperationOptions& options,
const Void::Time::MonotonicClock& clock)
{
if (delay.count() <= 0) {
return !options.stop.stop_requested() &&
!Async::is_deadline_expired(options, clock);
}
const auto slice = std::chrono::milliseconds{5};
auto remaining = delay;
while (remaining.count() > 0) {
if (options.stop.stop_requested() ||
Async::is_deadline_expired(options, clock)) {
return false;
}
const auto step = std::min<std::chrono::nanoseconds>(remaining, slice);
std::this_thread::sleep_for(step);
remaining -= step;
}
return !options.stop.stop_requested() &&
!Async::is_deadline_expired(options, clock);
}
} // namespace Detail
/// Execute `fn` under bounded composition:
/// deadline/stop -> rate_limiter -> bulkhead -> breaker -> single attempt ->
/// classify -> release permits -> retry policy (only if replay_safe && retryable).
template <typename Fn, typename Classify>
[[nodiscard]] auto execute_resilient(
ResiliencePipeline pipeline,
Fn fn,
Classify classify,
Async::OperationOptions options = {},
Async::Executor* resume_exec = nullptr)
-> Void::Coro::Task<typename Detail::UnwrapTask<std::invoke_result_t<Fn>>::type>
{
using ResultType = typename Detail::UnwrapTask<std::invoke_result_t<Fn>>::type;
const auto& clock =
pipeline.clock != nullptr
? *pipeline.clock
: Void::Time::SystemMonotonicClock::instance();
if (pipeline.retry.max_attempts == 0) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"ResilientRetryConfig::max_attempts must be >= 1"));
}
std::optional<std::mt19937_64> seeded_rng;
if (pipeline.retry.deterministic_seed.has_value()) {
seeded_rng.emplace(*pipeline.retry.deterministic_seed);
}
ResultType last_result = Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument, "No resilience attempt ran"));
for (std::size_t attempt = 0; attempt < pipeline.retry.max_attempts; ++attempt) {
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Resilient operation stopped before attempt"));
}
if (Async::is_deadline_expired(options, clock)) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation deadline expired"));
}
if (pipeline.rate_limiter != nullptr) {
auto adm = pipeline.rate_limiter->try_acquire_at_checked(
clock.now(), pipeline.rate_cost);
if (!adm) {
co_return Void::Result::fail(std::move(adm).error());
}
if (!adm->allowed) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::rate_limited,
"Resilient operation rate-limited"));
}
}
std::optional<BulkheadPermit> bulkhead_permit;
if (pipeline.bulkhead != nullptr) {
auto bh = co_await pipeline.bulkhead->acquire_async(options, resume_exec);
if (!bh) {
co_return Void::Result::fail(std::move(bh).error());
}
bulkhead_permit = std::move(*bh);
}
std::optional<BreakerPermit> breaker_permit;
if (pipeline.breaker != nullptr) {
auto br = pipeline.breaker->acquire();
if (!br) {
co_return Void::Result::fail(std::move(br).error());
}
breaker_permit = std::move(*br);
}
if constexpr (Detail::IsCoroTask<std::invoke_result_t<Fn>>::value) {
last_result = co_await fn();
} else {
last_result = fn();
}
const AttemptClassification cls = classify(last_result);
if (breaker_permit.has_value()) {
breaker_permit->finish(cls.outcome);
breaker_permit.reset();
}
if (bulkhead_permit.has_value()) {
bulkhead_permit->release();
bulkhead_permit.reset();
}
if (last_result.has_value()) {
co_return last_result;
}
if (!pipeline.retry.replay_safe || !cls.retryable ||
attempt + 1 >= pipeline.retry.max_attempts) {
co_return last_result;
}
auto delay = Detail::compute_jittered_backoff(
pipeline.retry, attempt, seeded_rng);
if (options.deadline.has_value()) {
const auto now = clock.now();
if (now >= *options.deadline) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation total deadline expired before retry"));
}
const auto rem = *options.deadline - now;
if (delay > rem) {
delay = rem;
}
}
const bool slept_ok = pipeline.wait_fn
? pipeline.wait_fn(delay, options)
: Detail::wait_with_stop(delay, options, clock);
if (!slept_ok) {
if (options.stop.stop_requested()) {
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::cancelled,
"Resilient operation cancelled during retry backoff"));
}
co_return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::timeout,
"Resilient operation timed out during retry backoff"));
}
}
co_return last_result;
}
} // namespace Void::Resilience
+419 -110
View File
@@ -1,140 +1,449 @@
#pragma once
#include <Void/Observability/Hooks.hpp>
#include <Void/Resilience/Types.hpp>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <utility>
namespace Void::Resilience
{
// ── CircuitBreaker
// ──────────────────────────────────────────────────────────── A
// three-state breaker that stops hammering a failing dependency.
//
// Closed calls flow; `failure_threshold` consecutive failures trip it
// Open. Open calls are rejected until `cooldown` elapses, then one
// probe is let
// through (HalfOpen).
// HalfOpen `success_threshold` probe successes close it; any failure
// re-opens.
//
// Use allow()/record_success()/record_failure() to gate work directly, or
// execute() to wrap a std::expected-returning step. Thread-safe; clock
// injectable for deterministic tests.
// ── CircuitBreaker (legacy compatibility) ────────────────────────────────────
template <typename R>
concept HasHasValue = requires(const R& r) {
{ r.has_value() } -> std::convertible_to<bool>;
};
template <typename R>
concept HasHasValue = requires(const R& r) {
{ r.has_value() } -> std::convertible_to<bool>;
};
class CircuitBreaker
{
public:
class CircuitBreaker
{
public:
enum class State { Closed, Open, HalfOpen };
enum class State { Closed, Open, HalfOpen };
using Clock = std::function<std::chrono::steady_clock::time_point()>;
using Duration = std::chrono::steady_clock::duration;
using TimePoint = std::chrono::steady_clock::time_point;
using Clock =
std::function<std::chrono::steady_clock::time_point()>;
using Duration = std::chrono::steady_clock::duration;
using TimePoint = std::chrono::steady_clock::time_point;
CircuitBreaker(std::size_t failure_threshold,
Duration cooldown,
std::size_t success_threshold = 1,
Clock clock = default_clock())
: failure_threshold_{failure_threshold > 0 ? failure_threshold : 1}
, cooldown_{cooldown.count() >= 0 ? cooldown : Duration::zero()}
, success_threshold_{success_threshold > 0 ? success_threshold : 1}
, clock_{std::move(clock)}
{
}
CircuitBreaker(std::size_t failure_threshold, Duration cooldown,
std::size_t success_threshold = 1,
Clock clock = default_clock())
: failure_threshold_{failure_threshold}, cooldown_{cooldown},
success_threshold_{success_threshold},
clock_{std::move(clock)}
{
}
[[nodiscard]] bool allow()
{
std::lock_guard lock{mu_};
if (state_ == State::Open) {
const auto now = clock_();
if (now >= opened_at_ && now - opened_at_ >= cooldown_) {
state_ = State::HalfOpen;
successes_ = 0;
}
}
return state_ != State::Open;
}
// Whether a call may proceed now. Transitions Open -> HalfOpen once
// the cooldown has elapsed (admitting a probe).
[[nodiscard]] bool allow()
{
std::lock_guard lock{mu_};
if (state_ == State::Open &&
clock_() - opened_at_ >= cooldown_) {
state_ = State::HalfOpen;
successes_ = 0;
}
return state_ != State::Open;
}
void record_success()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
if (++successes_ >= success_threshold_) {
state_ = State::Closed;
failures_ = 0;
}
} else {
failures_ = 0;
}
}
void record_success()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
if (++successes_ >= success_threshold_) {
state_ = State::Closed;
failures_ = 0;
}
} else {
failures_ = 0;
}
}
void record_failure()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
trip();
} else if (++failures_ >= failure_threshold_) {
trip();
}
}
void record_failure()
{
std::lock_guard lock{mu_};
if (state_ == State::HalfOpen) {
trip();
} else if (++failures_ >= failure_threshold_) {
trip();
}
}
[[nodiscard]] State state()
{
std::lock_guard lock{mu_};
return state_;
}
[[nodiscard]] State state()
{
std::lock_guard lock{mu_};
return state_;
}
template <std::invocable F>
requires HasHasValue<std::invoke_result_t<F>>
auto execute(F&& fn) -> std::optional<std::invoke_result_t<F>>
{
if (!allow()) {
return std::nullopt;
}
auto result = std::forward<F>(fn)();
if (result.has_value()) {
record_success();
} else {
record_failure();
}
return result;
}
// Gate a std::expected-returning callable. Returns nullopt when the
// circuit rejects the call; otherwise runs it, records the outcome,
// and returns its result.
template <std::invocable F>
requires HasHasValue<std::invoke_result_t<F>>
auto execute(F&& fn) -> std::optional<std::invoke_result_t<F>>
{
if (!allow()) {
return std::nullopt;
}
auto result = std::forward<F>(fn)();
if (result.has_value()) {
record_success();
} else {
record_failure();
}
return result;
}
private:
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
private:
void trip()
{
state_ = State::Open;
opened_at_ = clock_();
}
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
std::size_t failure_threshold_;
Duration cooldown_;
std::size_t success_threshold_;
Clock clock_;
void trip()
{
state_ = State::Open;
opened_at_ = clock_();
}
State state_ = State::Closed;
std::size_t failures_ = 0;
std::size_t successes_ = 0;
TimePoint opened_at_{};
std::mutex mu_;
};
std::size_t failure_threshold_;
Duration cooldown_;
std::size_t success_threshold_;
Clock clock_;
// ── P2 Generation-bound Breaker & RAII BreakerPermit ─────────────────────────
State state_ = State::Closed;
std::size_t failures_ = 0;
std::size_t successes_ = 0;
TimePoint opened_at_{};
std::mutex mu_;
};
enum class BreakerState : std::uint8_t {
closed = 0,
open,
half_open
};
using BreakerStateCallback = std::function<void(
BreakerState old_state, BreakerState new_state, std::uint64_t generation)>;
class Breaker;
namespace Detail
{
struct BreakerSharedState {
BreakerConfig config{};
const Void::Time::MonotonicClock* clock{nullptr};
Observability::HookSlot* hooks{nullptr};
std::mutex mu{};
BreakerState state{BreakerState::closed};
std::uint64_t generation{1};
std::size_t failures{0};
std::size_t half_open_in_flight{0};
std::size_t half_open_successes{0};
std::uint64_t observer_errors{0};
Void::Time::MonotonicClock::time_point opened_at{};
BreakerStateCallback on_state_change{};
BreakerSharedState(BreakerConfig cfg,
const Void::Time::MonotonicClock* clk,
Observability::HookSlot* h)
: config(std::move(cfg))
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
, hooks(h)
{
}
void emit_transition(const BreakerStateCallback& cb,
BreakerState old_st,
BreakerState new_st,
std::uint64_t gen) noexcept
{
if (cb) {
try {
cb(old_st, new_st, gen);
} catch (...) {
std::lock_guard lock{mu};
++observer_errors;
}
}
if (hooks != nullptr && !config.metric_name.empty()) {
const char* label =
new_st == BreakerState::closed ? "closed"
: new_st == BreakerState::half_open ? "half_open"
: "open";
const Observability::AttributeView attrs[] = {{"state", label}};
hooks->invoke_metric(Observability::MetricPoint{
.name = config.metric_name,
.kind = Observability::MetricKind::counter,
.integer_delta = 1,
.attributes = attrs});
}
}
void complete(std::uint64_t permit_gen, bool is_probe, Outcome outcome) noexcept
{
BreakerStateCallback cb;
bool transitioned = false;
BreakerState old_st = BreakerState::closed;
BreakerState new_st = BreakerState::closed;
std::uint64_t new_gen = 0;
{
std::lock_guard lock{mu};
if (is_probe && permit_gen == generation && half_open_in_flight > 0) {
--half_open_in_flight;
}
if (permit_gen != generation) {
return;
}
if (outcome == Outcome::neutral) {
return;
}
if (state == BreakerState::half_open) {
if (outcome == Outcome::success) {
if (++half_open_successes >= config.success_threshold) {
old_st = BreakerState::half_open;
new_st = BreakerState::closed;
state = BreakerState::closed;
failures = 0;
half_open_successes = 0;
half_open_in_flight = 0;
new_gen = ++generation;
transitioned = true;
cb = on_state_change;
}
} else {
old_st = BreakerState::half_open;
new_st = BreakerState::open;
state = BreakerState::open;
opened_at = clock->now();
half_open_successes = 0;
half_open_in_flight = 0;
new_gen = ++generation;
transitioned = true;
cb = on_state_change;
}
} else if (state == BreakerState::closed) {
if (outcome == Outcome::success) {
failures = 0;
} else if (++failures >= config.failure_threshold) {
old_st = BreakerState::closed;
new_st = BreakerState::open;
state = BreakerState::open;
opened_at = clock->now();
new_gen = ++generation;
transitioned = true;
cb = on_state_change;
}
}
}
if (transitioned) {
emit_transition(cb, old_st, new_st, new_gen);
}
}
};
} // namespace Detail
class BreakerPermit
{
public:
BreakerPermit() noexcept = default;
~BreakerPermit() noexcept
{
if (state_ && !finished_) {
finish(Outcome::neutral);
}
}
BreakerPermit(BreakerPermit&& other) noexcept
: state_(std::move(other.state_))
, generation_(other.generation_)
, is_probe_(other.is_probe_)
, finished_(std::exchange(other.finished_, true))
{
}
BreakerPermit& operator=(BreakerPermit&& other) noexcept
{
if (this != &other) {
if (state_ && !finished_) {
finish(Outcome::neutral);
}
state_ = std::move(other.state_);
generation_ = other.generation_;
is_probe_ = other.is_probe_;
finished_ = std::exchange(other.finished_, true);
}
return *this;
}
BreakerPermit(const BreakerPermit&) = delete;
BreakerPermit& operator=(const BreakerPermit&) = delete;
void finish(Outcome outcome) noexcept
{
if (!state_ || finished_) {
return;
}
finished_ = true;
auto st = std::move(state_);
st->complete(generation_, is_probe_, outcome);
}
[[nodiscard]] std::uint64_t generation() const noexcept
{
return generation_;
}
[[nodiscard]] bool is_probe() const noexcept { return is_probe_; }
[[nodiscard]] bool active() const noexcept
{
return state_ != nullptr && !finished_;
}
private:
friend class Breaker;
BreakerPermit(std::shared_ptr<Detail::BreakerSharedState> state,
std::uint64_t generation,
bool is_probe) noexcept
: state_(std::move(state))
, generation_(generation)
, is_probe_(is_probe)
, finished_(false)
{
}
std::shared_ptr<Detail::BreakerSharedState> state_{};
std::uint64_t generation_{0};
bool is_probe_{false};
bool finished_{true};
};
class Breaker
{
public:
[[nodiscard]] static Void::Result::Result<Breaker> create(
BreakerConfig config = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
Observability::HookSlot* hooks = nullptr)
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
auto st = std::make_shared<Detail::BreakerSharedState>(
std::move(config), &clock, hooks);
return Breaker{std::move(st)};
}
[[nodiscard]] Void::Result::Result<BreakerPermit> acquire()
{
BreakerStateCallback cb;
bool transitioned = false;
std::uint64_t new_gen = 0;
std::uint64_t permit_gen = 0;
bool is_probe = false;
bool admitted = false;
{
std::lock_guard lock{state_->mu};
const auto now = state_->clock->now();
if (state_->state == BreakerState::open) {
if (now >= state_->opened_at &&
now - state_->opened_at >= state_->config.cooldown) {
state_->state = BreakerState::half_open;
state_->half_open_in_flight = 0;
state_->half_open_successes = 0;
new_gen = ++state_->generation;
transitioned = true;
cb = state_->on_state_change;
}
}
if (state_->state == BreakerState::half_open) {
if (state_->half_open_in_flight <
state_->config.half_open_max_probes) {
++state_->half_open_in_flight;
permit_gen = state_->generation;
is_probe = true;
admitted = true;
}
} else if (state_->state == BreakerState::closed) {
permit_gen = state_->generation;
is_probe = false;
admitted = true;
}
}
if (transitioned) {
state_->emit_transition(
cb, BreakerState::open, BreakerState::half_open, new_gen);
}
if (!admitted) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::circuit_open,
"Circuit breaker rejected acquisition"));
}
return BreakerPermit{state_, permit_gen, is_probe};
}
void on_state_change(BreakerStateCallback callback)
{
std::lock_guard lock{state_->mu};
state_->on_state_change = std::move(callback);
}
[[nodiscard]] BreakerState state() const
{
std::lock_guard lock{state_->mu};
return state_->state;
}
[[nodiscard]] std::uint64_t generation() const
{
std::lock_guard lock{state_->mu};
return state_->generation;
}
[[nodiscard]] std::size_t half_open_in_flight() const
{
std::lock_guard lock{state_->mu};
return state_->half_open_in_flight;
}
[[nodiscard]] std::uint64_t observer_errors() const
{
std::lock_guard lock{state_->mu};
return state_->observer_errors;
}
private:
explicit Breaker(std::shared_ptr<Detail::BreakerSharedState> state) noexcept
: state_(std::move(state))
{
}
std::shared_ptr<Detail::BreakerSharedState> state_;
};
} // namespace Void::Resilience
+373 -131
View File
@@ -1,166 +1,408 @@
#pragma once
#include <Void/Observability/Hooks.hpp>
#include <Void/Resilience/RateLimiter.hpp>
#include <Void/Resilience/Types.hpp>
#include <chrono>
#include <cmath>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Resilience
{
// ── KeyedRateLimiter<Key> ───────────────────────────────────────────────
// A rate limiter that maintains an independent TokenBucket per distinct
// Key. Every key shares the same capacity + refill rate; buckets are
// created lazily on first use and can be reclaimed with cleanup(). Thread-
// safe. Generic over the key type (e.g. a client id, IP, or user name).
// ── KeyedRateLimiter<Key> ────────────────────────────────────────────────────
// Preserved compatibility rate limiter maintaining an independent TokenBucket
// per key. Use BoundedKeyedRateLimiter for new policy code requiring validated
// limits, bounded incremental cursor cleanup, and encoded key size bounds.
template <typename Key, typename Hash = std::hash<Key>>
class KeyedRateLimiter
{
public:
template <typename Key, typename Hash = std::hash<Key>>
class KeyedRateLimiter
{
public:
using Clock = TokenBucket::Clock;
using TimePoint = TokenBucket::TimePoint;
using Clock = TokenBucket::Clock;
using TimePoint = TokenBucket::TimePoint;
explicit KeyedRateLimiter(double capacity,
double refill_per_sec,
Clock clock = default_clock(),
std::size_t max_keys = 0)
: capacity_{capacity}
, rate_{refill_per_sec}
, clock_{std::move(clock)}
, max_keys_{max_keys}
{
if (max_keys_ > 0) {
map_.reserve(max_keys_);
}
}
// `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(),
std::size_t max_keys = 0)
: capacity_{capacity}, rate_{refill_per_sec},
clock_{std::move(clock)}, max_keys_{max_keys}
{
if (max_keys_ > 0) {
map_.reserve(max_keys_);
}
}
[[nodiscard]] bool allow(const Key& key, double tokens = 1.0)
{
return allow_at(key, clock_(), tokens);
}
// 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)
{
if (!std::isfinite(tokens) || tokens < 0.0 || tokens > capacity_) {
return false;
}
std::lock_guard lock{mu_};
Entry* value = entry(key, now);
return value != nullptr && value->bucket->try_acquire_at(now, tokens);
}
[[nodiscard]] bool allow_at(const Key& key, TimePoint now,
double tokens = 1.0)
{
std::lock_guard lock{mu_};
Entry* value = entry(key, now);
return value != nullptr &&
value->bucket->try_acquire_at(now, tokens);
}
[[nodiscard]] double remaining(const Key& key)
{
return remaining_at(key, clock_()).value_or(0.0);
}
// 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);
}
[[nodiscard]] std::optional<double> remaining_at(const Key& key, TimePoint now)
{
std::lock_guard lock{mu_};
Entry* value = entry(key, now);
if (value == nullptr) {
return std::nullopt;
}
return value->bucket->available_at(now);
}
// 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_};
Entry* value = entry(key, now);
if (value == nullptr) {
return std::nullopt;
}
return value->bucket->available_at(now);
}
void reset(const Key& key)
{
std::lock_guard lock{mu_};
map_.erase(key);
}
// Forget a key's bucket (its next use starts full).
void reset(const Key& key)
{
std::lock_guard lock{mu_};
map_.erase(key);
}
void reset()
{
std::lock_guard lock{mu_};
map_.clear();
}
void reset()
{
std::lock_guard lock{mu_};
map_.clear();
}
std::size_t cleanup(std::chrono::steady_clock::duration max_age)
{
return cleanup_at(clock_(), max_age);
}
// 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)
{
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 &&
now - it->second.last_seen >= max_age) {
it = map_.erase(it);
++removed;
} else {
++it;
}
}
return removed;
}
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 &&
now - it->second.last_seen >= max_age) {
it = map_.erase(it);
++removed;
} else {
++it;
}
}
return removed;
}
[[nodiscard]] std::size_t tracked() const
{
std::lock_guard lock{mu_};
return map_.size();
}
// Number of keys currently tracked.
[[nodiscard]] std::size_t tracked() const
{
std::lock_guard lock{mu_};
return map_.size();
}
private:
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
private:
struct Entry {
std::unique_ptr<TokenBucket> bucket;
std::chrono::steady_clock::time_point last_seen;
};
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
Entry* entry(const Key& key, TimePoint now)
{
auto it = map_.find(key);
if (it == map_.end()) {
if (max_keys_ > 0 && map_.size() >= max_keys_) {
return nullptr;
}
it = map_.emplace(key,
Entry{std::make_unique<TokenBucket>(
capacity_, rate_, clock_),
now})
.first;
} else {
if (now > it->second.last_seen) {
it->second.last_seen = now;
}
}
return &it->second;
}
struct Entry {
// TokenBucket owns a std::mutex (non-movable), so hold it
// by pointer to keep Entry movable for the hash map.
std::unique_ptr<TokenBucket> bucket;
std::chrono::steady_clock::time_point last_seen;
};
double capacity_;
double rate_;
Clock clock_;
std::size_t max_keys_;
mutable std::mutex mu_;
std::unordered_map<Key, Entry, Hash> map_;
};
Entry* entry(const Key& key, TimePoint now)
{
auto it = map_.find(key);
if (it == map_.end()) {
if (max_keys_ > 0 && map_.size() >= max_keys_) {
return nullptr;
}
it = map_.emplace(key,
Entry{std::make_unique<TokenBucket>(
capacity_, rate_, clock_),
now})
.first;
} else {
it->second.last_seen = now;
}
return &it->second;
}
namespace Detail
{
double capacity_;
double rate_;
Clock clock_;
std::size_t max_keys_;
mutable std::mutex mu_;
std::unordered_map<Key, Entry, Hash> map_;
};
template <typename Key>
[[nodiscard]] inline std::size_t encoded_key_size(const Key& key) noexcept
{
if constexpr (std::convertible_to<const Key&, std::string_view>) {
return std::string_view{key}.size();
} else {
return sizeof(Key);
}
}
} // namespace Detail
/// Bounded per-key rate limiter with key length caps, zero live-key eviction on
/// cap pressure, non-regressing token refill, and O(batch_limit) cursor cleanup.
template <typename Key, typename Hash = std::hash<Key>>
class BoundedKeyedRateLimiter
{
public:
using TimePoint = std::chrono::steady_clock::time_point;
[[nodiscard]] static Void::Result::Result<BoundedKeyedRateLimiter> create(
KeyedBucketConfig config = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
Observability::HookSlot* hooks = nullptr)
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
auto state = std::make_shared<State>(config, &clock, hooks);
return BoundedKeyedRateLimiter{std::move(state)};
}
[[nodiscard]] Void::Result::Result<Admission>
admit(const Key& key, double cost = 1.0)
{
return admit_at(key, state_->clock->now(), cost);
}
[[nodiscard]] Void::Result::Result<Admission>
admit_at(const Key& key, TimePoint now, double cost = 1.0)
{
if (Detail::encoded_key_size(key) > state_->config.max_key_bytes) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::key_too_large,
"Rate-limiter key exceeds max_key_bytes"));
}
if (!std::isfinite(cost) || cost <= 0.0 || cost > state_->config.capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Cost must be finite, positive, and <= capacity"));
}
Admission adm{};
bool cap_rejected = false;
{
std::lock_guard lock{state_->mu};
auto it = state_->entries.find(key);
if (it == state_->entries.end()) {
if (state_->entries.size() >= state_->config.max_keys) {
++state_->rejected_new_keys;
cap_rejected = true;
} else {
Entry created{};
created.tokens = state_->config.capacity;
created.last_refill = now;
created.last_seen = now;
it = state_->entries.emplace(key, created).first;
state_->cursor_keys.push_back(key);
}
} else {
if (now > it->second.last_seen) {
it->second.last_seen = now;
}
}
if (!cap_rejected) {
auto& entry = it->second;
if (now > entry.last_refill) {
const std::chrono::duration<double> elapsed =
now - entry.last_refill;
entry.last_refill = now;
entry.tokens = std::min(
state_->config.capacity,
entry.tokens +
elapsed.count() * state_->config.refill_per_second);
}
if (entry.tokens >= cost) {
entry.tokens -= cost;
adm = Admission{true, std::chrono::nanoseconds{0}};
} else {
adm = Admission{
false,
compute_retry_after(cost - entry.tokens)};
}
} else {
adm = Admission{false, std::chrono::nanoseconds{0}};
}
}
// Never emit raw user keys as metric labels.
emit_metric(cap_rejected ? "cap_rejected"
: (adm.allowed ? "allowed" : "rejected"));
return adm;
}
std::size_t cleanup_step()
{
return cleanup_step_at(state_->clock->now());
}
std::size_t cleanup_step_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
if (state_->cursor_keys.empty()) {
state_->cursor_idx = 0;
return 0;
}
const std::size_t scan_budget = std::min(
state_->config.cleanup_batch_limit, state_->cursor_keys.size());
std::size_t scanned = 0;
std::size_t removed = 0;
while (scanned < scan_budget && !state_->cursor_keys.empty()) {
if (state_->cursor_idx >= state_->cursor_keys.size()) {
state_->cursor_idx = 0;
}
++scanned;
const Key& k = state_->cursor_keys[state_->cursor_idx];
auto it = state_->entries.find(k);
if (it == state_->entries.end()) {
swap_remove_cursor(state_->cursor_idx);
continue;
}
if (now >= it->second.last_seen &&
now - it->second.last_seen >= state_->config.idle_retention) {
state_->entries.erase(it);
swap_remove_cursor(state_->cursor_idx);
++removed;
} else {
++state_->cursor_idx;
}
}
return removed;
}
[[nodiscard]] std::size_t tracked() const
{
std::lock_guard lock{state_->mu};
return state_->entries.size();
}
[[nodiscard]] std::uint64_t rejected_new_keys() const
{
std::lock_guard lock{state_->mu};
return state_->rejected_new_keys;
}
void reset(const Key& key)
{
std::lock_guard lock{state_->mu};
state_->entries.erase(key);
}
void reset()
{
std::lock_guard lock{state_->mu};
state_->entries.clear();
state_->cursor_keys.clear();
state_->cursor_idx = 0;
}
private:
struct Entry {
double tokens{0.0};
TimePoint last_refill{};
TimePoint last_seen{};
};
struct State {
KeyedBucketConfig config;
const Void::Time::MonotonicClock* clock;
Observability::HookSlot* hooks;
std::mutex mu;
std::unordered_map<Key, Entry, Hash> entries;
std::vector<Key> cursor_keys;
std::size_t cursor_idx{0};
std::uint64_t rejected_new_keys{0};
State(KeyedBucketConfig cfg,
const Void::Time::MonotonicClock* clk,
Observability::HookSlot* h)
: config(std::move(cfg))
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
, hooks(h)
{
entries.reserve(std::min<std::size_t>(config.max_keys, 1024));
}
};
explicit BoundedKeyedRateLimiter(std::shared_ptr<State> st) noexcept
: state_(std::move(st))
{
}
[[nodiscard]] std::chrono::nanoseconds
compute_retry_after(double deficit) const noexcept
{
if (deficit <= 0.0) {
return std::chrono::nanoseconds{0};
}
if (state_->config.refill_per_second <= 0.0) {
return std::chrono::nanoseconds::max();
}
const double sec = deficit / state_->config.refill_per_second;
if (!std::isfinite(sec) || sec * 1e9 >= 9.0e18) {
return std::chrono::nanoseconds::max();
}
const auto ns = static_cast<std::int64_t>(std::ceil(sec * 1e9));
return std::chrono::nanoseconds{std::max<std::int64_t>(1, ns)};
}
void swap_remove_cursor(std::size_t idx)
{
if (idx + 1 < state_->cursor_keys.size()) {
state_->cursor_keys[idx] = std::move(state_->cursor_keys.back());
}
state_->cursor_keys.pop_back();
}
void emit_metric(std::string_view outcome) noexcept
{
if (state_->hooks == nullptr || state_->config.metric_name.empty()) {
return;
}
const Observability::AttributeView attrs[] = {{"outcome", outcome}};
state_->hooks->invoke_metric(Observability::MetricPoint{
.name = state_->config.metric_name,
.kind = Observability::MetricKind::counter,
.integer_delta = 1,
.attributes = attrs});
}
std::shared_ptr<State> state_;
};
} // namespace Void::Resilience
+313 -80
View File
@@ -1,108 +1,341 @@
#pragma once
#include <Void/Observability/Hooks.hpp>
#include <Void/Resilience/Types.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <utility>
#include <vector>
namespace Void::Resilience
{
// ── TokenBucket
// ─────────────────────────────────────────────────────────────── A
// token-bucket rate limiter. The bucket holds up to `capacity` tokens and
// refills continuously at `refill_per_sec` tokens per second.
// try_acquire(n) consumes n tokens when available. Thread-safe; the clock
// is injectable so the refill behaviour is deterministic in tests.
// ── TokenBucket ──────────────────────────────────────────────────────────────
// A token-bucket rate limiter holding up to `capacity` tokens and refilling
// continuously at `refill_per_sec` tokens per second.
// Thread-safe; backed by stationary shared state so checked Admission queries,
// atomic multi-bucket acquisition, and legacy constructors share one model.
class TokenBucket
{
public:
class TokenBucket
{
public:
using Clock = std::function<std::chrono::steady_clock::time_point()>;
using TimePoint = std::chrono::steady_clock::time_point;
using Clock =
std::function<std::chrono::steady_clock::time_point()>;
using TimePoint = std::chrono::steady_clock::time_point;
TokenBucket(double capacity,
double refill_per_sec,
Clock clock = default_clock())
: state_(std::make_shared<State>(
std::isfinite(capacity) && capacity > 0.0 ? capacity : 0.0,
std::isfinite(refill_per_sec) && refill_per_sec >= 0.0
? refill_per_sec
: 0.0,
std::move(clock),
nullptr,
nullptr,
std::string{}))
{
}
TokenBucket(double capacity, double refill_per_sec,
Clock clock = default_clock())
: capacity_{capacity}, rate_{refill_per_sec}, tokens_{capacity},
clock_{std::move(clock)}, last_{clock_()}
{
}
[[nodiscard]] static Void::Result::Result<TokenBucket> create(
BucketConfig config,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
Observability::HookSlot* hooks = nullptr)
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
auto state = std::make_shared<State>(
config.capacity,
config.refill_per_second,
Clock{},
&clock,
hooks,
std::move(config.metric_name));
return TokenBucket{std::move(state)};
}
// Consume `tokens` if the bucket (after refilling for elapsed time)
// holds at least that many. Returns false without consuming
// anything otherwise.
[[nodiscard]] bool try_acquire(double tokens = 1.0)
{
std::lock_guard lock{mu_};
refill(clock_());
return try_acquire_locked(tokens);
}
// Legacy consume `tokens` if available; returns false without consuming on
// shortfall or invalid cost.
[[nodiscard]] bool try_acquire(double tokens = 1.0)
{
return try_acquire_at(state_->now(), 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);
}
[[nodiscard]] bool try_acquire_at(TimePoint now, double tokens = 1.0)
{
if (!std::isfinite(tokens) || tokens < 0.0 ||
tokens > state_->capacity || state_->capacity <= 0.0) {
return false;
}
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
if (state_->tokens >= tokens) {
state_->tokens -= tokens;
return true;
}
return false;
}
// Current token count after refilling for elapsed time.
[[nodiscard]] double available() { return available_at(clock_()); }
// Validated P2 admission returning retry_after on shortfall and rejecting
// invalid (NaN/Inf/non-positive/oversize) costs cleanly.
[[nodiscard]] Void::Result::Result<Admission>
try_acquire_checked(double cost = 1.0)
{
return try_acquire_at_checked(state_->now(), cost);
}
[[nodiscard]] double available_at(TimePoint now)
{
std::lock_guard lock{mu_};
refill(now);
return tokens_;
}
[[nodiscard]] Void::Result::Result<Admission>
try_acquire_at_checked(TimePoint now, double cost = 1.0)
{
if (!std::isfinite(cost) || cost <= 0.0 || cost > state_->capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Token cost must be finite, positive, and <= bucket capacity"));
}
void reset() { reset_at(clock_()); }
Admission adm{};
{
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
adm = state_->try_acquire_locked(cost);
}
emit_metric(adm.allowed);
return adm;
}
void reset_at(TimePoint now)
{
std::lock_guard lock{mu_};
tokens_ = capacity_;
last_ = now;
}
[[nodiscard]] double available()
{
return available_at(state_->now());
}
[[nodiscard]] double capacity() const noexcept { return capacity_; }
[[nodiscard]] double available_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
state_->refill_locked(now);
return state_->tokens;
}
private:
void reset() { reset_at(state_->now()); }
[[nodiscard]] bool try_acquire_locked(double tokens)
{
if (tokens_ >= tokens) {
tokens_ -= tokens;
return true;
}
return false;
}
void reset_at(TimePoint now)
{
std::lock_guard lock{state_->mu};
state_->tokens = state_->capacity;
if (now > state_->last) {
state_->last = now;
}
}
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
[[nodiscard]] double capacity() const noexcept
{
return state_->capacity;
}
void refill(TimePoint now)
{
const std::chrono::duration<double> elapsed =
now > last_ ? now - last_ : TimePoint::duration::zero();
last_ = now;
tokens_ =
std::min(capacity_, tokens_ + elapsed.count() * rate_);
}
[[nodiscard]] double refill_per_second() const noexcept
{
return state_->rate;
}
double capacity_;
double rate_;
double tokens_;
Clock clock_;
TimePoint last_;
std::mutex mu_;
};
// Atomically reserves tokens across all specified buckets or leaves every
// bucket untouched on first denial or invalid cost.
[[nodiscard]] static Void::Result::Result<Admission> try_acquire_all_at(
TimePoint now,
std::span<const std::pair<TokenBucket*, double>> requests)
{
for (const auto& [bucket, cost] : requests) {
if (bucket == nullptr || !std::isfinite(cost) || cost <= 0.0 ||
cost > bucket->state_->capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Invalid bucket or cost in try_acquire_all_at"));
}
}
if (requests.empty()) {
return Admission{true, std::chrono::nanoseconds{0}};
}
std::vector<State*> lock_order;
lock_order.reserve(requests.size());
for (const auto& [bucket, cost] : requests) {
(void)cost;
lock_order.push_back(bucket->state_.get());
}
std::sort(lock_order.begin(), lock_order.end());
lock_order.erase(std::unique(lock_order.begin(), lock_order.end()),
lock_order.end());
std::vector<std::unique_lock<std::mutex>> locks;
locks.reserve(lock_order.size());
for (auto* st : lock_order) {
locks.emplace_back(st->mu);
st->refill_locked(now);
}
std::vector<double> needed;
needed.assign(lock_order.size(), 0.0);
for (const auto& [bucket, cost] : requests) {
const auto pos = static_cast<std::size_t>(std::distance(
lock_order.begin(),
std::lower_bound(lock_order.begin(), lock_order.end(),
bucket->state_.get())));
needed[pos] += cost;
if (needed[pos] > lock_order[pos]->capacity) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"Combined cost exceeds bucket capacity"));
}
}
std::chrono::nanoseconds max_wait{0};
bool all_ok = true;
for (std::size_t i = 0; i < lock_order.size(); ++i) {
auto* st = lock_order[i];
if (st->tokens < needed[i]) {
all_ok = false;
const auto wait = st->compute_retry_after_locked(needed[i] - st->tokens);
if (wait > max_wait) {
max_wait = wait;
}
}
}
if (all_ok) {
for (std::size_t i = 0; i < lock_order.size(); ++i) {
lock_order[i]->tokens -= needed[i];
}
}
locks.clear();
for (const auto& [bucket, cost] : requests) {
(void)cost;
bucket->emit_metric(all_ok);
}
return Admission{all_ok, all_ok ? std::chrono::nanoseconds{0} : max_wait};
}
[[nodiscard]] static Void::Result::Result<Admission> try_acquire_all(
std::span<const std::pair<TokenBucket*, double>> requests,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance())
{
return try_acquire_all_at(clock.now(), requests);
}
private:
struct State {
double capacity{0.0};
double rate{0.0};
double tokens{0.0};
Clock clock_fn{};
const Void::Time::MonotonicClock* clock_ptr{nullptr};
Observability::HookSlot* hooks{nullptr};
std::string metric_name{};
TimePoint last{};
std::mutex mu{};
State(double cap,
double r,
Clock clk_fn,
const Void::Time::MonotonicClock* clk_ptr,
Observability::HookSlot* h,
std::string mname)
: capacity(cap)
, rate(r)
, tokens(cap)
, clock_fn(std::move(clk_fn))
, clock_ptr(clk_ptr)
, hooks(h)
, metric_name(std::move(mname))
, last(now())
{
}
[[nodiscard]] TimePoint now() const
{
if (clock_ptr != nullptr) {
return clock_ptr->now();
}
if (clock_fn) {
return clock_fn();
}
return std::chrono::steady_clock::now();
}
void refill_locked(TimePoint now_tp)
{
// Clock moving backwards must never reset `last` backward or grant
// extra credits on recovery.
if (now_tp <= last) {
return;
}
const std::chrono::duration<double> elapsed = now_tp - last;
last = now_tp;
tokens = std::min(capacity, tokens + elapsed.count() * rate);
}
[[nodiscard]] std::chrono::nanoseconds
compute_retry_after_locked(double deficit) const noexcept
{
if (deficit <= 0.0) {
return std::chrono::nanoseconds{0};
}
if (rate <= 0.0) {
return std::chrono::nanoseconds::max();
}
const double sec = deficit / rate;
if (!std::isfinite(sec) || sec * 1e9 >= 9.0e18) {
return std::chrono::nanoseconds::max();
}
const auto ns = static_cast<std::int64_t>(std::ceil(sec * 1e9));
return std::chrono::nanoseconds{std::max<std::int64_t>(1, ns)};
}
[[nodiscard]] Admission try_acquire_locked(double cost) noexcept
{
if (tokens >= cost) {
tokens -= cost;
return Admission{true, std::chrono::nanoseconds{0}};
}
return Admission{false, compute_retry_after_locked(cost - tokens)};
}
};
explicit TokenBucket(std::shared_ptr<State> st) noexcept
: state_(std::move(st))
{
}
static Clock default_clock()
{
return [] { return std::chrono::steady_clock::now(); };
}
void emit_metric(bool allowed) noexcept
{
if (state_->hooks == nullptr || state_->metric_name.empty()) {
return;
}
const Observability::AttributeView attrs[] = {
{"outcome", allowed ? "allowed" : "rejected"}};
state_->hooks->invoke_metric(Observability::MetricPoint{
.name = state_->metric_name,
.kind = Observability::MetricKind::counter,
.integer_delta = 1,
.attributes = attrs});
}
std::shared_ptr<State> state_;
};
} // namespace Void::Resilience
+5 -3
View File
@@ -1,10 +1,12 @@
#pragma once
// Umbrella header for the Resilience module: rate limiting, circuit breaking,
// and resource monitoring. These complement Functional/Retry.hpp (retry with
// backoff) rather than replacing it.
// Umbrella header for synchronous Resilience primitives: validated configs,
// rate limiting, circuit breaking, and resource monitoring. For optional Async
// bulkhead + retry composition, link Void::ResilienceAsync and include
// <Void/Resilience/AsyncPolicy.hpp>.
#include <Void/Resilience/CircuitBreaker.hpp>
#include <Void/Resilience/KeyedRateLimiter.hpp>
#include <Void/Resilience/RateLimiter.hpp>
#include <Void/Resilience/ResourceMonitor.hpp>
#include <Void/Resilience/Types.hpp>
+278 -94
View File
@@ -1,117 +1,301 @@
#pragma once
#include <Void/Resilience/Types.hpp>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <utility>
namespace Void::Resilience
{
// ── ResourceMonitor
// ─────────────────────────────────────────────────────────── Tracks usage
// of a bounded resource (memory budget, in-flight requests, queue depth,
// ...) against a limit, with hysteresis watermark callbacks.
//
// try_acquire() refuses to exceed the limit. Crossing the high watermark
// upward fires on_high_watermark once; dropping back to the low watermark
// fires on_low_watermark once (the gap prevents callback flapping).
// Callbacks run outside the internal lock.
class ResourceMonitor;
class ResourceMonitor
{
public:
namespace Detail
{
using Callback = std::function<void(std::uint64_t usage)>;
struct MonitorState {
using Callback = std::function<void(std::uint64_t usage)>;
// high/low are fractions of `limit` in [0, 1]; high should exceed
// low.
explicit ResourceMonitor(std::uint64_t limit, double high = 0.9,
double low = 0.7)
: limit_{limit}, high_{static_cast<std::uint64_t>(
static_cast<double>(limit) * high)},
low_{static_cast<std::uint64_t>(static_cast<double>(limit) *
low)}
{
}
std::uint64_t limit{0};
std::uint64_t high{0};
std::uint64_t low{0};
std::uint64_t usage{0};
bool alarmed{false};
std::uint64_t observer_errors{0};
Callback on_high{};
Callback on_low{};
mutable std::mutex mu{};
void on_high_watermark(Callback cb) { on_high_ = std::move(cb); }
void on_low_watermark(Callback cb) { on_low_ = std::move(cb); }
MonitorState(std::uint64_t lim, std::uint64_t hi, std::uint64_t lo) noexcept
: limit(lim), high(hi), low(lo)
{
}
// Reserve `amount`. Returns false (reserving nothing) if it would
// exceed the limit. May fire the high-watermark callback when
// crossing upward.
[[nodiscard]] bool try_acquire(std::uint64_t amount = 1)
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{mu_};
if (usage_ + amount > limit_) {
return false;
}
usage_ += amount;
if (!alarmed_ && usage_ >= high_) {
alarmed_ = true;
fire = on_high_;
at = usage_;
}
}
if (fire) {
fire(at);
}
return true;
}
void invoke_callback(const Callback& cb, std::uint64_t at) noexcept
{
if (!cb) {
return;
}
try {
cb(at);
} catch (...) {
std::lock_guard lock{mu};
++observer_errors;
}
}
// Release `amount` (clamped at zero). May fire the low-watermark
// callback when dropping back through the low threshold.
void release(std::uint64_t amount = 1)
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{mu_};
usage_ = (amount >= usage_) ? 0 : usage_ - amount;
if (alarmed_ && usage_ <= low_) {
alarmed_ = false;
fire = on_low_;
at = usage_;
}
}
if (fire) {
fire(at);
}
}
void release_amount(std::uint64_t amount, bool clamp) noexcept
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{mu};
if (amount >= usage) {
usage = clamp ? 0 : (usage - std::min(usage, amount));
} else {
usage -= amount;
}
if (alarmed && usage <= low) {
alarmed = false;
fire = on_low;
at = usage;
}
}
invoke_callback(fire, at);
}
};
[[nodiscard]] std::uint64_t usage() const
{
std::lock_guard lock{mu_};
return usage_;
}
} // namespace Detail
[[nodiscard]] std::uint64_t limit() const noexcept
{
return limit_;
}
class ResourcePermit
{
public:
ResourcePermit() noexcept = default;
[[nodiscard]] double utilization() const
{
std::lock_guard lock{mu_};
return limit_ == 0 ? 0.0
: static_cast<double>(usage_) /
static_cast<double>(limit_);
}
~ResourcePermit() noexcept { release(); }
private:
ResourcePermit(ResourcePermit&& other) noexcept
: state_(std::move(other.state_))
, amount_(std::exchange(other.amount_, 0))
{
}
std::uint64_t limit_;
std::uint64_t high_;
std::uint64_t low_;
std::uint64_t usage_ = 0;
bool alarmed_ = false;
Callback on_high_;
Callback on_low_;
mutable std::mutex mu_;
};
ResourcePermit& operator=(ResourcePermit&& other) noexcept
{
if (this != &other) {
release();
state_ = std::move(other.state_);
amount_ = std::exchange(other.amount_, 0);
}
return *this;
}
ResourcePermit(const ResourcePermit&) = delete;
ResourcePermit& operator=(const ResourcePermit&) = delete;
void release() noexcept
{
if (!state_ || amount_ == 0) {
return;
}
const auto amt = std::exchange(amount_, 0);
auto st = std::move(state_);
st->release_amount(amt, false);
}
[[nodiscard]] std::uint64_t amount() const noexcept { return amount_; }
[[nodiscard]] bool active() const noexcept
{
return state_ != nullptr && amount_ > 0;
}
private:
friend class ResourceMonitor;
ResourcePermit(std::shared_ptr<Detail::MonitorState> state,
std::uint64_t amount) noexcept
: state_(std::move(state)), amount_(amount)
{
}
std::shared_ptr<Detail::MonitorState> state_{};
std::uint64_t amount_{0};
};
// ── ResourceMonitor ──────────────────────────────────────────────────────────
// Tracks usage of a bounded resource against a limit, with synchronized
// watermark callbacks executed outside the internal mutex.
class ResourceMonitor
{
public:
using Callback = std::function<void(std::uint64_t usage)>;
explicit ResourceMonitor(std::uint64_t limit,
double high = 0.9,
double low = 0.7)
: state_(std::make_shared<Detail::MonitorState>(
limit,
clamp_fraction(limit, high, 0.9),
clamp_fraction(limit, low, 0.7)))
{
}
[[nodiscard]] static Void::Result::Result<ResourceMonitor> create(
MonitorConfig config)
{
if (auto v = config.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
const auto hi = clamp_fraction(config.limit, config.high_fraction, 0.9);
const auto lo = std::min(hi, clamp_fraction(config.limit, config.low_fraction, 0.7));
return ResourceMonitor{
std::make_shared<Detail::MonitorState>(config.limit, hi, lo)};
}
void on_high_watermark(Callback cb)
{
std::lock_guard lock{state_->mu};
state_->on_high = std::move(cb);
}
void on_low_watermark(Callback cb)
{
std::lock_guard lock{state_->mu};
state_->on_low = std::move(cb);
}
[[nodiscard]] bool try_acquire(std::uint64_t amount = 1)
{
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{state_->mu};
if (amount > state_->limit - state_->usage) {
return false;
}
state_->usage += amount;
if (!state_->alarmed && state_->usage >= state_->high) {
state_->alarmed = true;
fire = state_->on_high;
at = state_->usage;
}
}
state_->invoke_callback(fire, at);
return true;
}
[[nodiscard]] Void::Result::Result<ResourcePermit>
try_acquire_checked(std::uint64_t amount = 1)
{
if (amount == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"ResourceMonitor::try_acquire_checked requires amount > 0"));
}
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{state_->mu};
if (amount > state_->limit - state_->usage) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::overflow,
"ResourceMonitor reservation exceeds configured limit"));
}
state_->usage += amount;
if (!state_->alarmed && state_->usage >= state_->high) {
state_->alarmed = true;
fire = state_->on_high;
at = state_->usage;
}
}
state_->invoke_callback(fire, at);
return ResourcePermit{state_, amount};
}
void release(std::uint64_t amount = 1)
{
state_->release_amount(amount, true);
}
[[nodiscard]] Void::Result::Result<void>
release_checked(std::uint64_t amount = 1)
{
if (amount == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"ResourceMonitor::release_checked requires amount > 0"));
}
Callback fire;
std::uint64_t at = 0;
{
std::lock_guard lock{state_->mu};
if (amount > state_->usage) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::over_release,
"ResourceMonitor release amount exceeds active usage"));
}
state_->usage -= amount;
if (state_->alarmed && state_->usage <= state_->low) {
state_->alarmed = false;
fire = state_->on_low;
at = state_->usage;
}
}
state_->invoke_callback(fire, at);
return {};
}
[[nodiscard]] std::uint64_t usage() const
{
std::lock_guard lock{state_->mu};
return state_->usage;
}
[[nodiscard]] std::uint64_t limit() const noexcept
{
return state_->limit;
}
[[nodiscard]] double utilization() const
{
std::lock_guard lock{state_->mu};
return state_->limit == 0
? 0.0
: static_cast<double>(state_->usage) /
static_cast<double>(state_->limit);
}
[[nodiscard]] std::uint64_t observer_errors() const
{
std::lock_guard lock{state_->mu};
return state_->observer_errors;
}
private:
explicit ResourceMonitor(std::shared_ptr<Detail::MonitorState> state) noexcept
: state_(std::move(state))
{
}
[[nodiscard]] static std::uint64_t clamp_fraction(std::uint64_t limit,
double frac,
double fallback) noexcept
{
const double chosen =
(std::isfinite(frac) && frac >= 0.0 && frac <= 1.0) ? frac : fallback;
return static_cast<std::uint64_t>(
std::clamp(static_cast<double>(limit) * chosen,
0.0,
static_cast<double>(limit)));
}
std::shared_ptr<Detail::MonitorState> state_;
};
} // namespace Void::Resilience
+176
View File
@@ -0,0 +1,176 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <string>
namespace Void::Resilience
{
enum class ResilienceErrorCode : std::int32_t {
invalid_argument = 1,
rate_limited = 2,
circuit_open = 3,
bulkhead_full = 4,
capacity_exceeded = 5,
overflow = 6,
over_release = 7,
closed = 8,
cancelled = 9,
timeout = 10,
key_too_large = 11
};
[[nodiscard]] inline Void::Result::Error
make_resilience_error(ResilienceErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case ResilienceErrorCode::invalid_argument:
case ResilienceErrorCode::key_too_large:
kind = ErrorKind::invalid_argument;
break;
case ResilienceErrorCode::rate_limited:
case ResilienceErrorCode::circuit_open:
case ResilienceErrorCode::bulkhead_full:
kind = ErrorKind::overloaded;
break;
case ResilienceErrorCode::capacity_exceeded:
case ResilienceErrorCode::overflow:
kind = ErrorKind::exhausted;
break;
case ResilienceErrorCode::over_release:
kind = ErrorKind::conflict;
break;
case ResilienceErrorCode::closed:
case ResilienceErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case ResilienceErrorCode::timeout:
kind = ErrorKind::timeout;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kResilienceErrorDomain,
static_cast<std::int32_t>(code)}};
}
enum class Outcome : std::uint8_t {
success = 0,
dependency_failure,
neutral
};
struct Admission {
bool allowed{false};
std::chrono::nanoseconds retry_after{0};
};
struct BucketConfig {
double capacity{100.0};
double refill_per_second{100.0};
std::string metric_name{};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (!std::isfinite(capacity) || capacity <= 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BucketConfig::capacity must be finite and positive"));
}
if (!std::isfinite(refill_per_second) || refill_per_second < 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BucketConfig::refill_per_second must be finite and non-negative"));
}
return {};
}
};
struct KeyedBucketConfig {
double capacity{100.0};
double refill_per_second{100.0};
std::size_t max_keys{10'000};
std::size_t max_key_bytes{256};
std::chrono::nanoseconds idle_retention{std::chrono::minutes{5}};
std::size_t cleanup_batch_limit{256};
std::string metric_name{};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (!std::isfinite(capacity) || capacity <= 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"KeyedBucketConfig::capacity must be finite and positive"));
}
if (!std::isfinite(refill_per_second) || refill_per_second < 0.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"KeyedBucketConfig::refill_per_second must be finite and non-negative"));
}
if (max_keys == 0 || max_key_bytes == 0 || cleanup_batch_limit == 0 ||
idle_retention.count() < 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"KeyedBucketConfig limits must be positive"));
}
return {};
}
};
struct BreakerConfig {
std::size_t failure_threshold{5};
std::chrono::nanoseconds cooldown{std::chrono::seconds{5}};
std::size_t half_open_max_probes{1};
std::size_t success_threshold{2};
std::string metric_name{};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (failure_threshold == 0 || half_open_max_probes == 0 ||
success_threshold == 0 || cooldown.count() < 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"BreakerConfig thresholds/probes must be positive and cooldown non-negative"));
}
return {};
}
};
struct MonitorConfig {
std::uint64_t limit{0};
double high_fraction{0.9};
double low_fraction{0.7};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if (limit == 0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"MonitorConfig::limit must be non-zero"));
}
if (!std::isfinite(high_fraction) || !std::isfinite(low_fraction) ||
low_fraction < 0.0 || low_fraction > high_fraction ||
high_fraction > 1.0) {
return Void::Result::fail(make_resilience_error(
ResilienceErrorCode::invalid_argument,
"MonitorConfig watermarks must satisfy 0.0 <= low <= high <= 1.0"));
}
return {};
}
};
} // namespace Void::Resilience
+201 -18
View File
@@ -1,31 +1,214 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <optional>
#include <ostream>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Stacktrace
{
struct StackFrame {
std::string function_name;
std::string source_file;
int source_line{0};
std::string source_snippet;
};
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames = 0,
unsigned max_frames = 32);
inline constexpr std::size_t kMaxCaptureFrames = 256;
inline constexpr std::size_t kDefaultMaxSnippetBytes = 4096;
inline constexpr std::size_t kDefaultMaxRenderedBytes = 65536;
inline constexpr std::size_t kDefaultMaxSourceScanBytes = 1048576;
inline constexpr std::size_t kDefaultMaxLineLength = 4096;
inline constexpr std::size_t kDefaultResolverCacheEntries = 1024;
inline constexpr std::size_t kDefaultResolverCacheBytes = 4ULL * 1024ULL * 1024ULL;
/// Read a snippet of source around `line`. On failure (file missing,
/// not readable, etc.) returns Failure<Error> instead of an empty
/// string — callers that want the silent fallback can still do
/// `read_source_snippet(...).value_or("")`.
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file, int line,
int context_lines = 3);
enum class StacktraceErrorCode : std::int32_t {
invalid_argument = 1,
unsafe_path = 2,
source_unreadable = 3,
scan_limit_exceeded = 4,
cancelled = 5,
timeout = 6,
backend_failed = 7
};
[[nodiscard]] inline Void::Result::Error
make_stacktrace_error(StacktraceErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case StacktraceErrorCode::invalid_argument:
case StacktraceErrorCode::unsafe_path:
kind = ErrorKind::invalid_argument;
break;
case StacktraceErrorCode::source_unreadable:
kind = ErrorKind::not_found;
break;
case StacktraceErrorCode::scan_limit_exceeded:
kind = ErrorKind::exhausted;
break;
case StacktraceErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case StacktraceErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case StacktraceErrorCode::backend_failed:
kind = ErrorKind::internal;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kStacktraceErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct Capabilities {
bool raw_capture{true};
bool symbols{true};
bool line_info{true};
bool async_signal_safe{false};
std::string_view backend_name{"boost.stacktrace"};
};
[[nodiscard]] Capabilities capabilities() noexcept;
struct CaptureOptions {
unsigned skip{0};
unsigned max_frames{32};
};
struct RawFrame {
std::uintptr_t address{0};
std::uintptr_t module_offset{0};
std::string module_path{};
std::string module_id{};
};
struct RawTrace {
std::vector<RawFrame> frames{};
bool truncated{false};
};
/// Capture raw instruction addresses and owned module identity metadata without
/// reading source files or emitting Void::Log events.
[[nodiscard]] Void::Result::Result<RawTrace>
capture(CaptureOptions options = {});
enum class FrameResolveStatus : std::uint8_t {
resolved = 0,
symbols_only,
unresolved,
unsupported,
cancelled,
timed_out
};
struct ResolveOptions {
bool resolve_symbols{true};
bool source_snippets{false};
std::vector<std::filesystem::path> allowed_source_roots{};
std::vector<std::string> redact_prefixes{};
int context_lines{3};
std::size_t max_snippet_bytes{kDefaultMaxSnippetBytes};
std::size_t max_bytes{kDefaultMaxRenderedBytes};
std::size_t max_source_scan_bytes{kDefaultMaxSourceScanBytes};
std::size_t max_line_bytes{kDefaultMaxLineLength};
std::stop_token stop{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
};
struct ResolvedFrame {
RawFrame raw{};
std::string function_name{};
std::string source_file{};
int source_line{0};
std::string source_snippet{};
FrameResolveStatus status{FrameResolveStatus::unresolved};
std::optional<Void::Result::Error> diagnostic{};
};
struct ResolvedTrace {
std::vector<ResolvedFrame> frames{};
bool truncated{false};
bool incomplete{false};
std::size_t rendered_bytes{0};
};
/// Stateful bounded LRU resolver cache keyed by owned (module_id, module_offset).
class Resolver
{
public:
explicit Resolver(std::size_t max_entries = kDefaultResolverCacheEntries,
std::size_t max_bytes = kDefaultResolverCacheBytes);
~Resolver();
Resolver(const Resolver&) = delete;
Resolver& operator=(const Resolver&) = delete;
Resolver(Resolver&&) noexcept = delete;
Resolver& operator=(Resolver&&) noexcept = delete;
[[nodiscard]] Void::Result::Result<ResolvedTrace>
resolve(const RawTrace& raw, const ResolveOptions& options = {});
std::size_t invalidate_module(std::string_view module_id);
void clear_cache();
[[nodiscard]] std::size_t cache_entries() const;
[[nodiscard]] std::size_t cache_bytes() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
[[nodiscard]] Void::Result::Result<ResolvedTrace>
resolve(const RawTrace& raw, const ResolveOptions& options = {});
[[nodiscard]] Void::Result::Result<std::string>
read_source_snippet_checked(const std::filesystem::path& file,
int line,
const ResolveOptions& options);
[[nodiscard]] std::string format_resolved_trace(
const ResolvedTrace& trace,
std::size_t max_bytes = kDefaultMaxRenderedBytes);
/// Async-signal-safe fixed-buffer fatal diagnostic marker writer using only
/// stack storage and raw descriptor write().
bool write_fatal_signal_marker(int fd, int sig) noexcept;
// ── Legacy compatibility API ─────────────────────────────────────────────────
struct StackFrame {
std::string function_name;
std::string source_file;
int source_line{0};
std::string source_snippet;
};
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames = 0,
unsigned max_frames = 32);
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file,
int line,
int context_lines = 3);
std::string format_stacktrace(const std::vector<StackFrame>& frames);
void print_stacktrace(std::ostream& os,
const std::vector<StackFrame>& frames);
std::string format_stacktrace(const std::vector<StackFrame>& frames);
void print_stacktrace(std::ostream& os,
const std::vector<StackFrame>& frames);
} // namespace Void::Stacktrace
+119 -8
View File
@@ -1,7 +1,15 @@
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Log.hpp>
#ifndef _WIN32
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <format>
#include <mutex>
#include <stdexcept>
namespace Void::Logging
@@ -20,6 +28,18 @@ namespace Void::Logging
Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string());
}
FileLogger::FileLogger(const std::filesystem::path& path,
LoggerOptions options)
: Logger(std::move(options)), m_path(path), m_file(path, std::ios::app)
{
if (!m_file.is_open()) {
Void::Log::warn("Logging", "FileLogger: cannot open '{}'", path.string());
throw std::runtime_error(
std::format("FileLogger: cannot open '{}'", path.string()));
}
Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string());
}
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
FileLogger::open(const std::filesystem::path& path,
Mode mode,
@@ -29,7 +49,21 @@ namespace Void::Logging
return Void::Result::ok(
std::make_unique<FileLogger>(path, mode, capacity));
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
FileLogger::open(const std::filesystem::path& path,
LoggerOptions options)
{
try {
return Void::Result::ok(
std::make_unique<FileLogger>(path, std::move(options)));
} catch (const std::exception& e) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
@@ -37,13 +71,70 @@ namespace Void::Logging
{
flush();
Void::Log::debug("Logging", "FileLogger: closed '{}'",
m_path.string());
m_path.string());
}
Void::Result::Result<void> FileLogger::reopen()
{
flush();
m_file.close();
m_file.clear();
m_file.open(m_path, std::ios::app);
if (!m_file.is_open()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::reopen failed for '{}'",
m_path.string())));
}
return {};
}
Void::Result::Result<void> FileLogger::sync_files()
{
flush();
if (is_quarantined()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, last_error_summary()));
}
m_file.flush();
if (!m_file.good()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files flush failure for '{}'",
m_path.string())));
}
#ifndef _WIN32
const int fd = ::open(m_path.c_str(), O_RDONLY);
if (fd < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files open('{}') failed: {}",
m_path.string(), std::strerror(errno))));
}
int rc = 0;
do {
rc = ::fsync(fd);
} while (rc < 0 && errno == EINTR);
const int saved_err = errno;
::close(fd);
if (rc < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files fsync('{}') failed: {}",
m_path.string(), std::strerror(saved_err))));
}
#endif
return {};
}
void FileLogger::write(const Entry& entry)
{
append(entry);
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: flush failure on '{}'", m_path.string()));
}
}
void FileLogger::on_flush(std::span<const Entry> entries)
@@ -52,17 +143,37 @@ namespace Void::Logging
append(e);
}
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: batch flush failure on '{}'", m_path.string()));
}
}
void FileLogger::append(const Entry& entry)
{
if (m_formatter) {
m_file << m_formatter->format(entry) << '\n';
if (!m_file.is_open()) {
throw std::runtime_error(std::format(
"FileLogger: file not open for '{}'", m_path.string()));
}
else {
m_file << std::format(
"[{}] {}\n", to_string(entry.level), entry.message);
std::string line;
if (m_formatter) {
auto bounded = format_bounded(
*m_formatter,
entry,
delivery_limits().max_format_scratch_bytes,
delivery_limits().truncate_oversize);
if (!bounded) {
throw std::runtime_error(bounded.error().message());
}
line = std::move(*bounded);
} else {
line = std::format("[{}] {}", to_string(entry.level), entry.message);
}
m_file << line << '\n';
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: write failure on '{}'", m_path.string()));
}
}
} // namespace Void::Logging
} // namespace Void::Logging
+114 -73
View File
@@ -1,9 +1,11 @@
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Logger.hpp>
#include <Void/Data/Json.hpp>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <format>
#include <sstream>
@@ -12,8 +14,6 @@
namespace Void::Logging
{
// ── colour ────────────────────────────────────────────────────────────
AnsiColor parse_color(std::string_view name) noexcept
{
struct Pair {
@@ -43,7 +43,6 @@ namespace Void::Logging
return c;
}
}
// "dim"/"gray" aliases
if (name == "dim" || name == "gray" || name == "grey") {
return AnsiColor::BrightBlack;
}
@@ -53,40 +52,23 @@ namespace Void::Logging
std::string_view ansi_code(AnsiColor color) noexcept
{
switch (color) {
case AnsiColor::Default:
return "";
case AnsiColor::Black:
return "\x1b[30m";
case AnsiColor::Red:
return "\x1b[31m";
case AnsiColor::Green:
return "\x1b[32m";
case AnsiColor::Yellow:
return "\x1b[33m";
case AnsiColor::Blue:
return "\x1b[34m";
case AnsiColor::Magenta:
return "\x1b[35m";
case AnsiColor::Cyan:
return "\x1b[36m";
case AnsiColor::White:
return "\x1b[37m";
case AnsiColor::BrightBlack:
return "\x1b[90m";
case AnsiColor::BrightRed:
return "\x1b[91m";
case AnsiColor::BrightGreen:
return "\x1b[92m";
case AnsiColor::BrightYellow:
return "\x1b[93m";
case AnsiColor::BrightBlue:
return "\x1b[94m";
case AnsiColor::BrightMagenta:
return "\x1b[95m";
case AnsiColor::BrightCyan:
return "\x1b[96m";
case AnsiColor::BrightWhite:
return "\x1b[97m";
case AnsiColor::Default: return "";
case AnsiColor::Black: return "\x1b[30m";
case AnsiColor::Red: return "\x1b[31m";
case AnsiColor::Green: return "\x1b[32m";
case AnsiColor::Yellow: return "\x1b[33m";
case AnsiColor::Blue: return "\x1b[34m";
case AnsiColor::Magenta: return "\x1b[35m";
case AnsiColor::Cyan: return "\x1b[36m";
case AnsiColor::White: return "\x1b[37m";
case AnsiColor::BrightBlack: return "\x1b[90m";
case AnsiColor::BrightRed: return "\x1b[91m";
case AnsiColor::BrightGreen: return "\x1b[92m";
case AnsiColor::BrightYellow: return "\x1b[93m";
case AnsiColor::BrightBlue: return "\x1b[94m";
case AnsiColor::BrightMagenta: return "\x1b[95m";
case AnsiColor::BrightCyan: return "\x1b[96m";
case AnsiColor::BrightWhite: return "\x1b[97m";
}
return "";
}
@@ -103,13 +85,10 @@ namespace Void::Logging
{Level::Error, AnsiColor::BrightRed},
{Level::Fatal, AnsiColor::BrightMagenta},
};
// The level token defaults to the level's own colour.
p.token_colors = {};
return p;
}
// ── FormatDetail ──────────────────────────────────────────────────────
namespace FormatDetail
{
@@ -143,12 +122,9 @@ namespace Void::Logging
std::string_view kind_str(Kind kind)
{
switch (kind) {
case Kind::Message:
return "Message";
case Kind::ScopeEnter:
return "ScopeEnter";
case Kind::ScopeExit:
return "ScopeExit";
case Kind::Message: return "Message";
case Kind::ScopeEnter: return "ScopeEnter";
case Kind::ScopeExit: return "ScopeExit";
}
return "?";
}
@@ -168,7 +144,7 @@ namespace Void::Logging
const std::string* found = nullptr;
for (const auto& [k, v] : entry.fields) {
if (k == key) {
found = &v; // later duplicates win
found = &v;
}
}
return found;
@@ -177,8 +153,6 @@ namespace Void::Logging
} // namespace FormatDetail
// ── PatternFormatter ──────────────────────────────────────────────────
PatternFormatter::PatternFormatter(std::string pattern)
{
std::string literal;
@@ -206,10 +180,9 @@ namespace Void::Logging
literal += rest;
break;
}
const auto body = rest.substr(1, close - 1); // inside braces
const auto body = rest.substr(1, close - 1);
rest.remove_prefix(close + 1);
// Split "token:spec".
std::string_view token = body;
std::string_view spec;
if (const auto colon = body.find(':');
@@ -222,7 +195,6 @@ namespace Void::Logging
seg.literal = false;
seg.text = std::string{token};
// spec = [align][width][,colour]
std::string_view color_name;
if (const auto comma = spec.find(',');
comma != std::string_view::npos) {
@@ -292,15 +264,18 @@ namespace Void::Logging
if (name == "kind") {
return std::string{kind_str(entry.kind)};
}
// Custom token?
if (const auto it = m_custom.find(name); it != m_custom.end()) {
return it->second(entry);
}
// Structured field?
if (const auto* v = find_field(entry, name)) {
if (!m_fields.allows(name)) {
return {};
}
if (m_fields.is_redacted(name)) {
return m_fields.redaction_mask;
}
return *v;
}
// Unknown — keep literal so misspellings are visible.
return "{" + name + "}";
}
@@ -315,7 +290,6 @@ namespace Void::Logging
std::string text = render_token(seg, entry);
// Width / alignment.
if (seg.width > text.size()) {
const std::size_t pad = seg.width - text.size();
switch (seg.align) {
@@ -337,7 +311,6 @@ namespace Void::Logging
}
}
// Colour.
if (m_colors.enabled && seg.color_mode != ColorMode::None) {
AnsiColor color = AnsiColor::Default;
if (seg.color_mode == ColorMode::Auto) {
@@ -355,7 +328,6 @@ namespace Void::Logging
continue;
}
}
// Per-token colour from the policy (no inline ,colour spec).
if (m_colors.enabled && seg.color_mode == ColorMode::None) {
if (const auto it = m_colors.token_colors.find(seg.text);
it != m_colors.token_colors.end() &&
@@ -371,8 +343,6 @@ namespace Void::Logging
return out;
}
// ── JsonLinesFormatter ────────────────────────────────────────────────
std::string JsonLinesFormatter::format(const Entry& entry) const
{
auto obj = Json::object();
@@ -383,6 +353,9 @@ namespace Void::Logging
o.emplace_back("kind", Json::Value{FormatDetail::kind_str(entry.kind)});
o.emplace_back("thread",
Json::Value{FormatDetail::thread_str(entry.thread_id)});
if (entry.truncated) {
o.emplace_back("truncated", Json::Value{true});
}
if (!entry.scopes.empty()) {
auto arr = Json::array();
arr.as_array().reserve(entry.scopes.size());
@@ -397,7 +370,11 @@ namespace Void::Logging
if (!m_fields.allows(k)) {
continue;
}
fobj.as_object().emplace_back(k, Json::Value{v});
fobj.as_object().emplace_back(
k,
Json::Value{m_fields.is_redacted(k)
? m_fields.redaction_mask
: v});
}
if (!fobj.as_object().empty()) {
o.emplace_back("fields", std::move(fobj));
@@ -408,26 +385,56 @@ namespace Void::Logging
o.emplace_back("file", Json::Value{file});
o.emplace_back(
"line",
Json::Value{static_cast<double>(entry.location.line())});
Json::Value{static_cast<std::int64_t>(entry.location.line())});
}
return Json::serialize(obj);
}
// ── LogfmtFormatter ───────────────────────────────────────────────────
namespace
{
void append_quoted(std::string& out, std::string_view value)
{
out += '"';
for (const char c : value) {
if (c == '"' || c == '\\') {
out += '\\';
for (const unsigned char uc : value) {
switch (uc) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (uc < 0x20 || uc == 0x7F) {
out += std::format("\\u{:04x}", uc);
} else {
out += static_cast<char>(uc);
}
break;
}
out += c;
}
out += '"';
}
[[nodiscard]] bool is_safe_bare_token(std::string_view sv) noexcept
{
if (sv.empty()) {
return false;
}
for (const unsigned char uc : sv) {
if (uc <= 0x20 || uc == 0x7F || uc == '=' || uc == '"') {
return false;
}
}
return true;
}
void append_key_or_token(std::string& out, std::string_view token)
{
if (is_safe_bare_token(token)) {
out += token;
} else {
append_quoted(out, token);
}
}
} // namespace
std::string LogfmtFormatter::format(const Entry& entry) const
@@ -439,23 +446,27 @@ namespace Void::Logging
out += to_string(entry.level);
out += " thread=";
out += FormatDetail::thread_str(entry.thread_id);
if (entry.truncated) {
out += " truncated=true";
}
if (auto crumb = FormatDetail::scope_breadcrumb(entry.scopes);
!crumb.empty()) {
out += " scopes=";
out += crumb;
append_key_or_token(out, crumb);
}
for (const auto& [k, v] : entry.fields) {
if (!m_fields.allows(k)) {
continue;
}
out += ' ';
out += k;
append_key_or_token(out, k);
out += '=';
append_quoted(out, v);
append_quoted(
out, m_fields.is_redacted(k) ? m_fields.redaction_mask : v);
}
if (auto file = FormatDetail::file_basename(entry); !file.empty()) {
out += " file=";
out += file;
append_key_or_token(out, file);
out += ':';
out += std::to_string(entry.location.line());
}
@@ -464,4 +475,34 @@ namespace Void::Logging
return out;
}
} // namespace Void::Logging
Void::Result::Result<std::string>
format_bounded(const Formatter& formatter,
const Entry& entry,
std::size_t max_bytes,
bool truncate)
{
if (max_bytes == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"format_bounded requires max_bytes > 0"));
}
std::string rendered = formatter.format(entry);
if (rendered.size() <= max_bytes) {
return rendered;
}
if (!truncate) {
return Void::Result::fail(make_log_error(
LogErrorCode::entry_too_large,
"Formatted log entry exceeds max_format_scratch_bytes"));
}
constexpr std::string_view kMarker = "...[truncated]";
if (max_bytes <= kMarker.size()) {
rendered.resize(max_bytes);
return rendered;
}
rendered.resize(max_bytes - kMarker.size());
rendered += kMarker;
return rendered;
}
} // namespace Void::Logging
-325
View File
@@ -1,325 +0,0 @@
#include <Void/Log/FromConfig.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/History.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Log/SyslogLogger.hpp>
#include <format>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace Void::Logging
{
namespace
{
std::vector<std::string> split_list(std::string_view csv)
{
std::vector<std::string> out;
std::size_t start = 0;
while (start <= csv.size()) {
auto comma = csv.find(',', start);
if (comma == std::string_view::npos) {
comma = csv.size();
}
auto item = csv.substr(start, comma - start);
while (!item.empty() && item.front() == ' ') {
item.remove_prefix(1);
}
while (!item.empty() && item.back() == ' ') {
item.remove_suffix(1);
}
if (!item.empty()) {
out.emplace_back(item);
}
start = comma + 1;
}
return out;
}
std::optional<Level> parse_level(std::string_view name)
{
std::string lower;
for (const char c : name) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "trace") {
return Level::Trace;
}
if (lower == "debug") {
return Level::Debug;
}
if (lower == "info") {
return Level::Info;
}
if (lower == "warning" || lower == "warn") {
return Level::Warning;
}
if (lower == "error") {
return Level::Error;
}
if (lower == "fatal") {
return Level::Fatal;
}
if (lower == "disabled" || lower == "off") {
return Level::Disabled;
}
return std::nullopt;
}
std::optional<Void::Log::Level>
parse_facade_level(std::string_view name)
{
const auto l = parse_level(name);
if (!l.has_value()) {
return std::nullopt;
}
switch (*l) {
case Level::Trace:
return Void::Log::Level::Trace;
case Level::Debug:
return Void::Log::Level::Debug;
case Level::Info:
return Void::Log::Level::Info;
case Level::Warning:
return Void::Log::Level::Warning;
case Level::Error:
return Void::Log::Level::Error;
case Level::Fatal:
return Void::Log::Level::Fatal;
case Level::Disabled:
return Void::Log::Level::Disabled;
}
return std::nullopt;
}
// Field allow/deny lists for the structured (json/logfmt) sinks, from
// the per-sink keys `fields.include` / `fields.exclude` (comma lists).
FieldFilter make_field_filter(const Configuration::Config& cfg)
{
FieldFilter f;
f.include = split_list(cfg.get_or("fields.include", ""));
f.exclude = split_list(cfg.get_or("fields.exclude", ""));
return f;
}
std::shared_ptr<const Formatter>
make_formatter(const Configuration::Config& cfg)
{
const auto format = cfg.get_or("format", "default");
if (format == "pattern") {
auto fmt =
std::make_shared<PatternFormatter>(std::string{cfg.get_or(
"pattern", "{time} [{level}] {scopes}{message}")});
if (cfg.get_or_as<bool>("color", false)) {
fmt->set_color_policy(ColorPolicy::defaults());
}
return fmt;
}
if (format == "json") {
auto fmt = std::make_shared<JsonLinesFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
if (format == "logfmt") {
auto fmt = std::make_shared<LogfmtFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
return nullptr; // "default": per-sink built-in rendering
}
struct Dispatch {
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::Block;
};
Dispatch make_dispatch(const Configuration::Config& cfg)
{
Dispatch d;
if (!cfg.get_or_as<bool>("async", true)) {
d.mode = Mode::Immediate;
}
d.capacity = cfg.get_or_as<std::size_t>("capacity", 512);
const auto overflow = cfg.get_or("overflow", "block");
if (overflow == "drop_newest") {
d.policy = OverflowPolicy::DropNewest;
} else if (overflow == "drop_oldest") {
d.policy = OverflowPolicy::DropOldest;
}
return d;
}
} // namespace
Void::Result::Result<std::shared_ptr<Logger>, Void::Result::Error>
from_config(const Configuration::Config& cfg, std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
const auto dispatch = make_dispatch(sub);
const auto formatter = make_formatter(sub);
std::vector<std::shared_ptr<Logger>> sinks;
for (const auto& name : split_list(sub.get_or("sinks", "console"))) {
if (name == "console") {
const bool to_stdout =
sub.get_or("console.stream", "stderr") == "stdout";
auto sink = std::make_shared<ConsoleLogger>(
to_stdout ? std::cout : std::cerr, dispatch.mode,
dispatch.capacity);
if (formatter) {
sink->set_formatter(formatter);
}
sinks.push_back(std::move(sink));
} else if (name == "file") {
const auto path = sub.get_or("file.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'file' needs "
"file.path");
}
auto sink = FileLogger::open(std::filesystem::path{path},
dispatch.mode,
dispatch.capacity);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "rotating") {
const auto path = sub.get_or("rotating.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'rotating' needs "
"rotating.path");
}
RotatingFileLogger::Options opt;
opt.max_bytes =
sub.get_or_as<std::size_t>("rotating.max_kb", 1024) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("rotating.max_files", 5);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
RotatingFileLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "split") {
const auto dir = sub.get_or("split.dir");
if (dir.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'split' needs "
"split.dir");
}
SplitFileLogger::Options opt;
opt.combined = sub.get_or_as<bool>("split.combined", true);
opt.max_bytes =
sub.get_or_as<std::size_t>("split.max_kb", 1024) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("split.max_files", 5);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
SplitFileLogger::open(std::filesystem::path{dir}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "history") {
const auto path = sub.get_or("history.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'history' needs "
"history.path");
}
HistoryLogger::Options opt;
opt.max_bytes =
sub.get_or_as<std::size_t>("history.max_kb", 8192) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("history.max_files", 10);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
HistoryLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "syslog") {
#ifdef VOID_HAS_SYSLOG
const auto identity = sub.get_or("syslog.identity");
if (identity.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'syslog' needs "
"syslog.identity");
}
sinks.push_back(std::make_shared<SyslogLogger>(
std::string{identity}, dispatch.mode, dispatch.capacity));
#else
return Void::Result::fail(
"Logging::from_config: syslog is not available on "
"this platform");
#endif
} else {
return Void::Result::fail(std::format(
"Logging::from_config: unknown sink '{}'", name));
}
}
std::shared_ptr<Logger> root;
if (sinks.empty()) {
root = std::make_shared<NullLogger>();
} else if (sinks.size() == 1) {
root = std::move(sinks.front());
} else {
root = std::make_shared<MultiLogger>(std::move(sinks));
}
if (const auto level = parse_level(sub.get_or("level", "trace"));
level.has_value()) {
root->set_level(*level);
}
Void::Log::debug("Logging", "from_config: built logger tree");
return Void::Result::ok(std::move(root));
}
void apply_facade_config(const Configuration::Config& cfg,
std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
if (const auto level = parse_facade_level(sub.get_or("level", ""));
level.has_value()) {
Void::Log::set_min_level(*level);
}
for (const auto& key : sub.subtree("module_levels").keys()) {
const auto value = sub.get_or(std::string{"module_levels."} + key);
if (const auto level = parse_facade_level(value);
level.has_value()) {
Void::Log::set_module_level(key, *level);
}
}
}
} // namespace Void::Logging
+712 -241
View File
File diff suppressed because it is too large. Load diff
+86 -10
View File
@@ -1,9 +1,18 @@
#include <Void/Log/Detail/RollingFile.hpp>
#include <Void/Log/Logger.hpp>
#ifndef _WIN32
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <chrono>
#include <ctime>
#include <format>
#include <stdexcept>
#include <system_error>
#include <utility>
#include <vector>
@@ -46,25 +55,46 @@ namespace Void::Logging::Detail
bool RollingFile::open()
{
std::error_code ec;
if (m_path.has_parent_path()) {
if (m_opt.create_directories && m_path.has_parent_path()) {
std::filesystem::create_directories(m_path.parent_path(), ec);
if (ec) {
return false;
}
}
if (std::filesystem::exists(m_path, ec)) {
m_current_bytes = static_cast<std::size_t>(
std::filesystem::file_size(m_path, ec));
} else {
m_current_bytes = 0;
}
m_file.clear();
m_file.open(m_path, std::ios::app);
m_creationTime = std::chrono::system_clock::now();
return m_file.is_open();
}
bool RollingFile::reopen()
{
if (m_file.is_open()) {
m_file.flush();
m_file.close();
}
m_file.clear();
return open();
}
void RollingFile::write(std::string_view line)
{
if (!m_file.is_open()) {
return;
throw std::runtime_error(std::format(
"RollingFile: stream closed for '{}'", m_path.string()));
}
m_file.write(line.data(), static_cast<std::streamsize>(line.size()));
m_file.put('\n');
if (!m_file.good()) {
throw std::runtime_error(std::format(
"RollingFile: write failure on '{}'", m_path.string()));
}
m_current_bytes += line.size() + 1;
if (m_self_rotate && m_current_bytes >= m_opt.max_bytes) {
rotate();
@@ -73,9 +103,46 @@ namespace Void::Logging::Detail
void RollingFile::flush()
{
if (m_file.is_open()) {
m_file.flush();
if (!m_file.is_open()) {
return;
}
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"RollingFile: flush failure on '{}'", m_path.string()));
}
}
Void::Result::Result<void> RollingFile::sync()
{
try {
flush();
} catch (const std::exception& e) {
return Void::Result::fail(
make_log_error(LogErrorCode::io_error, e.what()));
}
#ifndef _WIN32
const int fd = ::open(m_path.c_str(), O_RDONLY);
if (fd < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RollingFile::sync open('{}') failed: {}",
m_path.string(), std::strerror(errno))));
}
int rc = 0;
do {
rc = ::fsync(fd);
} while (rc < 0 && errno == EINTR);
const int saved_err = errno;
::close(fd);
if (rc < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RollingFile::sync fsync('{}') failed: {}",
m_path.string(), std::strerror(saved_err))));
}
#endif
return {};
}
void RollingFile::rotate()
@@ -85,12 +152,15 @@ namespace Void::Logging::Detail
std::error_code ec;
if (m_opt.max_files > 0) {
// Create the history/ subdirectory next to the original file
auto parent = m_path.parent_path();
auto history_dir = parent / "history";
std::filesystem::create_directories(history_dir, ec);
if (ec) {
throw std::runtime_error(std::format(
"RollingFile: cannot create history dir '{}'",
history_dir.string()));
}
// Build new name: <stem>-<timestamp>.<ext>
auto stem = m_path.stem();
auto ext = m_path.extension();
auto new_filename = stem.string() + "-" +
@@ -98,19 +168,24 @@ namespace Void::Logging::Detail
auto archived = history_dir / new_filename;
std::filesystem::rename(m_path, archived, ec);
prune_archives(); // now looks inside history/
prune_archives();
} else {
std::filesystem::remove(m_path, ec);
}
m_file.clear();
m_file.open(m_path, std::ios::trunc);
if (!m_file.is_open()) {
throw std::runtime_error(std::format(
"RollingFile: reopen after rotate failed on '{}'",
m_path.string()));
}
m_current_bytes = 0;
m_creationTime = m_rotationTime;
}
void RollingFile::prune_archives()
{
// Prune only from the history/ subdirectory
auto parent = m_path.parent_path();
auto history_dir = parent / "history";
if (!std::filesystem::exists(history_dir)) {
@@ -132,7 +207,7 @@ namespace Void::Logging::Detail
}
}
} catch (const std::filesystem::filesystem_error&) {
return; // best-effort pruning only
return;
}
std::sort(archives.begin(), archives.end());
@@ -150,9 +225,10 @@ namespace Void::Logging::Detail
std::filesystem::create_directories(dir, ec);
std::filesystem::rename(m_path, dir / m_path.filename(), ec);
m_file.clear();
m_file.open(m_path, std::ios::trunc);
m_current_bytes = 0;
m_creationTime = m_rotationTime;
}
} // namespace Void::Logging::Detail
} // namespace Void::Logging::Detail
+51 -6
View File
@@ -9,9 +9,23 @@ namespace Void::Logging
RotatingFileLogger::RotatingFileLogger(const std::filesystem::path& path,
Options options)
: Logger(options.mode, options.capacity, options.policy), m_path(path),
m_file(path, Detail::RollingFileOptions{options.max_bytes,
options.max_files})
: Logger(LoggerOptions{
.mode = options.mode,
.policy = options.policy,
.limits = DeliveryLimits{
.entries = options.capacity > 0 ? options.capacity : 1,
.owned_bytes = std::max<std::size_t>(
8ULL * 1024ULL * 1024ULL,
(options.capacity > 0 ? options.capacity : 1) * 1024ULL),
.max_fields = 64,
.max_scopes = 64},
.failure_policy = FailurePolicy::Quarantine,
.suppress_reentrancy = false}),
m_path(path),
m_file(path,
Detail::RollingFileOptions{options.max_bytes,
options.max_files,
options.create_directories})
{
if (!m_file.open()) {
throw std::runtime_error(std::format(
@@ -29,12 +43,35 @@ namespace Void::Logging
return Void::Result::ok(
std::make_unique<RotatingFileLogger>(path, options));
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
RotatingFileLogger::~RotatingFileLogger() noexcept { flush(); }
Void::Result::Result<void> RotatingFileLogger::reopen()
{
flush();
if (!m_file.reopen()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RotatingFileLogger::reopen failed for '{}'",
m_path.string())));
}
return {};
}
Void::Result::Result<void> RotatingFileLogger::sync_files()
{
flush();
if (is_quarantined()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, last_error_summary()));
}
return m_file.sync();
}
void RotatingFileLogger::write(const Entry& entry)
{
append(entry);
@@ -52,11 +89,19 @@ namespace Void::Logging
void RotatingFileLogger::append(const Entry& entry)
{
if (m_formatter) {
m_file.write(m_formatter->format(entry));
auto bounded = format_bounded(
*m_formatter,
entry,
delivery_limits().max_format_scratch_bytes,
delivery_limits().truncate_oversize);
if (!bounded) {
throw std::runtime_error(bounded.error().message());
}
m_file.write(*bounded);
} else {
m_file.write(
std::format("[{}] {}", to_string(entry.level), entry.message));
}
}
} // namespace Void::Logging
} // namespace Void::Logging
+2 -2
View File
@@ -1,5 +1,5 @@
void_add_module(Log
INTERNAL_DEPS Async Core Data Functional Configuration LogState
INTERNAL_DEPS Async Core Data Functional Memory Time LogState
OPTIONAL_DEPS Stacktrace
EXCLUDE_HEADERS Void/Log/Log.hpp
EXCLUDE_HEADERS Void/Log/Log.hpp Void/Log/FromConfig.hpp
)
+449
View File
@@ -0,0 +1,449 @@
#include <Void/Log/FromConfig.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/History.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Log/SyslogLogger.hpp>
#include <cctype>
#include <format>
#include <iostream>
#include <string>
#include <vector>
namespace Void::Logging
{
namespace
{
std::vector<std::string> split_list(std::string_view csv)
{
std::vector<std::string> out;
std::size_t start = 0;
while (start <= csv.size()) {
auto comma = csv.find(',', start);
if (comma == std::string_view::npos) {
comma = csv.size();
}
auto item = csv.substr(start, comma - start);
while (!item.empty() && item.front() == ' ') {
item.remove_prefix(1);
}
while (!item.empty() && item.back() == ' ') {
item.remove_suffix(1);
}
if (!item.empty()) {
out.emplace_back(item);
}
start = comma + 1;
}
return out;
}
std::optional<Level> parse_level(std::string_view name)
{
std::string lower;
for (const char c : name) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "trace") {
return Level::Trace;
}
if (lower == "debug") {
return Level::Debug;
}
if (lower == "info") {
return Level::Info;
}
if (lower == "warning" || lower == "warn") {
return Level::Warning;
}
if (lower == "error") {
return Level::Error;
}
if (lower == "fatal") {
return Level::Fatal;
}
if (lower == "disabled" || lower == "off") {
return Level::Disabled;
}
return std::nullopt;
}
std::optional<Void::Log::Level>
parse_facade_level(std::string_view name)
{
const auto l = parse_level(name);
if (!l.has_value()) {
return std::nullopt;
}
switch (*l) {
case Level::Trace: return Void::Log::Level::Trace;
case Level::Debug: return Void::Log::Level::Debug;
case Level::Info: return Void::Log::Level::Info;
case Level::Warning: return Void::Log::Level::Warning;
case Level::Error: return Void::Log::Level::Error;
case Level::Fatal: return Void::Log::Level::Fatal;
case Level::Disabled: return Void::Log::Level::Disabled;
}
return std::nullopt;
}
FieldFilter make_field_filter(const Configuration::Config& cfg)
{
FieldFilter f;
f.include = split_list(cfg.get_or("fields.include", ""));
f.exclude = split_list(cfg.get_or("fields.exclude", ""));
f.redact = split_list(cfg.get_or("fields.redact", ""));
return f;
}
Void::Result::Result<std::shared_ptr<const Formatter>,
Void::Result::Error>
make_formatter(const Configuration::Config& cfg)
{
const auto format = cfg.get_or("format", "default");
if (format == "default") {
return Void::Result::ok<std::shared_ptr<const Formatter>>(nullptr);
}
if (format == "pattern") {
auto fmt = std::make_shared<PatternFormatter>(std::string{
cfg.get_or("pattern",
"{time} [{level}] {scopes}{message}")});
if (const auto col = cfg.get_as<std::string>("color");
col.has_value()) {
const auto parsed = cfg.get_as<bool>("color");
if (!parsed.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: invalid bool "
"'{}' for color",
*col)));
}
if (*parsed) {
fmt->set_color_policy(ColorPolicy::defaults());
}
}
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
if (format == "json") {
auto fmt = std::make_shared<JsonLinesFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
if (format == "logfmt") {
auto fmt = std::make_shared<LogfmtFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown format '{}'",
format)));
}
struct Dispatch {
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::DropNewest;
};
Void::Result::Result<Dispatch, Void::Result::Error>
make_dispatch(const Configuration::Config& cfg)
{
Dispatch d;
if (cfg.get_as<std::string>("async").has_value()) {
const auto async_val = cfg.get_as<bool>("async");
if (!async_val.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: invalid async bool"));
}
d.mode = *async_val ? Mode::Async : Mode::Immediate;
}
if (cfg.get_as<std::string>("capacity").has_value()) {
const auto cap_val = cfg.get_as<std::size_t>("capacity");
if (!cap_val.has_value() || *cap_val == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: capacity must be positive"));
}
d.capacity = *cap_val;
}
if (const auto overflow = cfg.get_as<std::string>("overflow");
overflow.has_value()) {
if (*overflow == "block") {
d.policy = OverflowPolicy::Block;
} else if (*overflow == "drop_newest") {
d.policy = OverflowPolicy::DropNewest;
} else if (*overflow == "drop_oldest") {
d.policy = OverflowPolicy::DropOldest;
} else {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown overflow "
"policy '{}'",
*overflow)));
}
}
return d;
}
Void::Result::Result<std::size_t, Void::Result::Error>
positive_size_or(const Configuration::Config& cfg,
std::string_view key,
std::size_t fallback)
{
if (!cfg.get_as<std::string>(key).has_value()) {
return fallback;
}
const auto parsed = cfg.get_as<std::size_t>(key);
if (!parsed.has_value() || *parsed == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: '{}' must be > 0",
key)));
}
return *parsed;
}
} // namespace
Void::Result::Result<std::shared_ptr<Logger>, Void::Result::Error>
from_config(const Configuration::Config& cfg, std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
Level parsed_level = Level::Trace;
if (const auto raw_lvl = sub.get_as<std::string>("level");
raw_lvl.has_value()) {
const auto lvl = parse_level(*raw_lvl);
if (!lvl.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown level '{}'",
*raw_lvl)));
}
parsed_level = *lvl;
}
auto dispatch_res = make_dispatch(sub);
if (!dispatch_res.has_value()) {
return Void::Result::fail(std::move(dispatch_res).error());
}
const auto dispatch = *dispatch_res;
auto formatter_res = make_formatter(sub);
if (!formatter_res.has_value()) {
return Void::Result::fail(std::move(formatter_res).error());
}
const auto formatter = std::move(*formatter_res);
const LoggerOptions base_opts{
.mode = dispatch.mode,
.policy = dispatch.policy,
.limits = DeliveryLimits{
.entries = dispatch.capacity,
.owned_bytes = std::max<std::size_t>(
8ULL * 1024ULL * 1024ULL, dispatch.capacity * 1024ULL),
.max_fields = 64,
.max_scopes = 64},
.failure_policy = FailurePolicy::Quarantine,
.suppress_reentrancy = true};
std::vector<std::shared_ptr<Logger>> sinks;
for (const auto& name : split_list(sub.get_or("sinks", "console"))) {
if (name == "console") {
const auto stream = sub.get_or("console.stream", "stderr");
if (stream != "stderr" && stream != "stdout") {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown "
"console.stream '{}'",
stream)));
}
auto sink = std::make_shared<ConsoleLogger>(
stream == "stdout" ? std::cout : std::cerr, dispatch.mode,
dispatch.capacity);
if (formatter) {
sink->set_formatter(formatter);
}
sinks.push_back(std::move(sink));
} else if (name == "file") {
const auto path = sub.get_or("file.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'file' needs file.path"));
}
auto sink =
FileLogger::open(std::filesystem::path{path}, base_opts);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "rotating") {
const auto path = sub.get_or("rotating.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'rotating' needs "
"rotating.path"));
}
auto max_kb = positive_size_or(sub, "rotating.max_kb", 1024);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files =
positive_size_or(sub, "rotating.max_files", 5);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
RotatingFileLogger::Options opt;
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
RotatingFileLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "split") {
const auto dir = sub.get_or("split.dir");
if (dir.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'split' needs split.dir"));
}
auto max_kb = positive_size_or(sub, "split.max_kb", 1024);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files = positive_size_or(sub, "split.max_files", 5);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
SplitFileLogger::Options opt;
opt.combined = sub.get_or_as<bool>("split.combined", true);
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
SplitFileLogger::open(std::filesystem::path{dir}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "history") {
const auto path = sub.get_or("history.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'history' needs "
"history.path"));
}
auto max_kb = positive_size_or(sub, "history.max_kb", 8192);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files =
positive_size_or(sub, "history.max_files", 10);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
HistoryLogger::Options opt;
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
HistoryLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "syslog") {
#ifdef VOID_HAS_SYSLOG
const auto identity = sub.get_or("syslog.identity");
if (identity.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'syslog' needs "
"syslog.identity"));
}
sinks.push_back(std::make_shared<SyslogLogger>(
std::string{identity}, dispatch.mode, dispatch.capacity));
#else
return Void::Result::fail(make_log_error(
LogErrorCode::unsupported_capability,
"Logging::from_config: syslog is not available on "
"this platform"));
#endif
} else {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown sink '{}'",
name)));
}
}
std::shared_ptr<Logger> root;
if (sinks.empty()) {
root = std::make_shared<NullLogger>(base_opts);
} else if (sinks.size() == 1) {
root = std::move(sinks.front());
} else {
if (sinks.size() > kDefaultMaxFanoutChildren) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: too many sinks"));
}
root = std::make_shared<MultiLogger>(std::move(sinks));
}
root->set_level(parsed_level);
Void::Log::debug("Logging", "from_config: built logger tree");
return Void::Result::ok(std::move(root));
}
void apply_facade_config(const Configuration::Config& cfg,
std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
if (const auto level = parse_facade_level(sub.get_or("level", ""));
level.has_value()) {
Void::Log::set_min_level(*level);
}
for (const auto& key : sub.subtree("module_levels").keys()) {
const auto value = sub.get_or(std::string{"module_levels."} + key);
if (const auto level = parse_facade_level(value);
level.has_value()) {
Void::Log::set_module_level(key, *level);
}
}
}
} // namespace Void::Logging
+4
View File
@@ -0,0 +1,4 @@
void_add_module(LogConfig
INTERNAL_DEPS Log Configuration Functional
EXTRA_HEADERS Void/Log/FromConfig.hpp
)
+7 -1
View File
@@ -12,4 +12,10 @@ namespace Void::Log::Detail
static State s;
return s;
}
} // namespace Void::Log::Detail
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept
{
static thread_local std::vector<const SinkRegistration*> stack;
return stack;
}
} // namespace Void::Log::Detail
+808
View File
@@ -0,0 +1,808 @@
#include <Void/Observability/Metrics.hpp>
#include <algorithm>
#include <atomic>
#include <cmath>
#include <limits>
#include <mutex>
#include <shared_mutex>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Observability
{
namespace
{
constexpr std::size_t kPerSeriesOverheadBytes = 128;
[[nodiscard]] bool valid_token(std::string_view sv) noexcept
{
for (const unsigned char ch : sv) {
if (ch < 0x20 || ch == 0x7F) {
return false;
}
}
return true;
}
[[nodiscard]] bool valid_label_name(std::string_view sv) noexcept
{
if (sv.empty() || !valid_token(sv)) {
return false;
}
for (const char ch : sv) {
if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') {
return false;
}
}
return true;
}
struct CanonicalLabels {
std::string key;
std::vector<std::string> values;
};
[[nodiscard]] std::uint64_t saturating_add_u64(
std::uint64_t lhs,
std::uint64_t rhs,
bool& saturated) noexcept
{
constexpr auto kMax = std::numeric_limits<std::uint64_t>::max();
if (rhs > kMax - lhs) {
saturated = true;
return kMax;
}
return lhs + rhs;
}
} // namespace
Void::Result::Result<void> MetricsLimits::validate() const
{
if (max_instruments == 0 || max_series_per_instrument == 0 ||
max_total_series == 0 || max_labels_per_point == 0 ||
max_key_bytes == 0 || max_value_bytes == 0 ||
max_producer_shards == 0 || max_storage_bytes == 0) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"MetricsLimits values must be non-zero"));
}
return {};
}
struct MetricRegistry::Impl {
struct SeriesMeta {
std::size_t series_id{0};
bool is_overflow{false};
std::vector<std::pair<std::string, std::string>> labels{};
std::size_t byte_cost{0};
};
struct InstrumentData {
InstrumentSpec spec{};
std::vector<SeriesMeta> series{};
std::unordered_map<std::string, std::size_t> key_to_series{};
std::atomic<bool> overflow_seen{false};
std::atomic<std::uint64_t> dropped_series{0};
std::atomic<std::uint64_t> overflow_events{0};
};
struct SeriesAccumulator {
std::uint64_t counter_value{0};
bool counter_saturated{false};
double gauge_value{0.0};
bool has_gauge_sample{false};
std::uint64_t gauge_seq{0};
Void::Time::MonotonicClock::time_point gauge_timestamp{};
std::vector<std::uint64_t> hist_buckets{};
std::uint64_t hist_count{0};
double hist_sum{0.0};
};
struct Shard {
std::mutex mutex;
// Indexed by [instrument_idx][series_id]
std::vector<std::vector<SeriesAccumulator>> data;
};
struct TlsShardEntry {
std::uint64_t registry_id{0};
std::weak_ptr<Shard> shard{};
};
static std::uint64_t next_id() noexcept
{
static std::atomic<std::uint64_t> seq{1};
return seq.fetch_add(1, std::memory_order_relaxed);
}
explicit Impl(MetricsLimits lim, const Void::Time::MonotonicClock* clk)
: id(next_id())
, limits(lim)
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
, fallback_shard(std::make_shared<Shard>())
{
}
std::shared_ptr<Shard> acquire_shard()
{
static thread_local std::vector<TlsShardEntry> tls_cache;
for (auto it = tls_cache.begin(); it != tls_cache.end();) {
if (it->shard.expired()) {
it = tls_cache.erase(it);
continue;
}
if (it->registry_id == id) {
if (auto locked = it->shard.lock()) {
return locked;
}
it = tls_cache.erase(it);
continue;
}
++it;
}
std::shared_ptr<Shard> assigned;
{
std::lock_guard lock{shards_mutex};
if (shards.size() < limits.max_producer_shards) {
assigned = std::make_shared<Shard>();
shards.push_back(assigned);
} else {
shared_shard_fallbacks.fetch_add(1, std::memory_order_relaxed);
assigned = fallback_shard;
}
}
tls_cache.push_back(TlsShardEntry{id, assigned});
return assigned;
}
[[nodiscard]] Void::Result::Result<CanonicalLabels> build_canonical_labels(
const InstrumentData& inst,
std::span<const AttributeView> attributes) const
{
if (attributes.size() > limits.max_labels_per_point) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Attribute count exceeds max_labels_per_point"));
}
CanonicalLabels result;
result.values.resize(inst.spec.label_keys.size());
std::vector<bool> seen(inst.spec.label_keys.size(), false);
for (const auto& attr : attributes) {
if (attr.key.empty() || attr.key.size() > limits.max_key_bytes ||
!valid_token(attr.key)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid attribute key"));
}
if (attr.value.size() > limits.max_value_bytes ||
!valid_token(attr.value)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid attribute value"));
}
const auto key_it = std::find(inst.spec.label_keys.begin(),
inst.spec.label_keys.end(),
attr.key);
if (key_it == inst.spec.label_keys.end()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Undeclared metric label key"));
}
const auto pos = static_cast<std::size_t>(
std::distance(inst.spec.label_keys.begin(), key_it));
if (seen[pos]) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Duplicate metric label key in single observation"));
}
seen[pos] = true;
result.values[pos].assign(attr.value);
}
std::size_t total_len = result.values.size() * 4;
for (const auto& v : result.values) {
total_len += v.size();
}
result.key.reserve(total_len);
for (const auto& v : result.values) {
result.key.append(std::to_string(v.size()));
result.key.push_back(':');
result.key.append(v);
result.key.push_back('\x1f');
}
return result;
}
[[nodiscard]] std::size_t resolve_or_create_series(
std::size_t inst_idx,
const CanonicalLabels& canonical)
{
std::unique_lock dir_lock{dir_mutex};
auto& inst = *instruments[inst_idx];
if (const auto it = inst.key_to_series.find(canonical.key);
it != inst.key_to_series.end()) {
return it->second;
}
const std::size_t current_normal =
inst.series.empty() ? 0 : (inst.series.size() - 1);
std::size_t label_bytes = 0;
for (std::size_t i = 0; i < inst.spec.label_keys.size(); ++i) {
label_bytes += inst.spec.label_keys[i].size() + canonical.values[i].size();
}
const std::size_t series_cost =
kPerSeriesOverheadBytes + canonical.key.size() + label_bytes +
(inst.spec.bucket_bounds.size() + 1) * sizeof(std::uint64_t);
const std::size_t used_bytes = estimated_bytes.load(std::memory_order_relaxed);
const std::size_t used_series = total_series.load(std::memory_order_relaxed);
if (current_normal >= limits.max_series_per_instrument ||
used_series >= limits.max_total_series ||
series_cost > limits.max_storage_bytes - std::min(used_bytes, limits.max_storage_bytes)) {
inst.overflow_seen.store(true, std::memory_order_release);
inst.dropped_series.fetch_add(1, std::memory_order_relaxed);
inst.overflow_events.fetch_add(1, std::memory_order_relaxed);
dropped_series.fetch_add(1, std::memory_order_relaxed);
overflow_events.fetch_add(1, std::memory_order_relaxed);
return 0; // pre-registered __overflow__ slot
}
const std::size_t new_id = inst.series.size();
SeriesMeta meta;
meta.series_id = new_id;
meta.is_overflow = false;
meta.byte_cost = series_cost;
meta.labels.reserve(inst.spec.label_keys.size());
for (std::size_t i = 0; i < inst.spec.label_keys.size(); ++i) {
meta.labels.emplace_back(inst.spec.label_keys[i], canonical.values[i]);
}
inst.key_to_series.emplace(canonical.key, new_id);
inst.series.push_back(std::move(meta));
total_series.fetch_add(1, std::memory_order_relaxed);
estimated_bytes.fetch_add(series_cost, std::memory_order_relaxed);
return new_id;
}
template <typename Fn>
void mutate_slot(std::size_t inst_idx,
std::size_t series_id,
std::size_t hist_bucket_count,
Fn&& fn)
{
auto shard = acquire_shard();
std::lock_guard lock{shard->mutex};
if (shard->data.size() <= inst_idx) {
shard->data.resize(inst_idx + 1);
}
auto& inst_vec = shard->data[inst_idx];
if (inst_vec.size() <= series_id) {
inst_vec.resize(series_id + 1);
}
auto& slot = inst_vec[series_id];
if (hist_bucket_count > 0 && slot.hist_buckets.size() != hist_bucket_count) {
slot.hist_buckets.assign(hist_bucket_count, 0);
}
fn(slot);
}
Void::Result::Result<void> add_counter_impl(
std::size_t inst_idx,
std::uint64_t delta,
std::span<const AttributeView> attributes)
{
std::shared_lock dir_lock{dir_mutex};
if (inst_idx >= instruments.size()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid InstrumentHandle index"));
}
const auto& inst = *instruments[inst_idx];
if (inst.spec.kind != MetricKind::counter) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::schema_conflict,
"Instrument is not a counter"));
}
auto canonical = build_canonical_labels(inst, attributes);
if (!canonical) {
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
return Void::Result::fail(std::move(canonical).error());
}
dir_lock.unlock();
const auto sid = resolve_or_create_series(inst_idx, *canonical);
mutate_slot(inst_idx, sid, 0, [delta](SeriesAccumulator& slot) {
slot.counter_value = saturating_add_u64(
slot.counter_value, delta, slot.counter_saturated);
});
return {};
}
Void::Result::Result<void> set_gauge_impl(
std::size_t inst_idx,
double value,
std::span<const AttributeView> attributes)
{
if (!std::isfinite(value)) {
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Gauge value must be finite"));
}
std::shared_lock dir_lock{dir_mutex};
if (inst_idx >= instruments.size()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid InstrumentHandle index"));
}
const auto& inst = *instruments[inst_idx];
if (inst.spec.kind != MetricKind::gauge) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::schema_conflict,
"Instrument is not a gauge"));
}
auto canonical = build_canonical_labels(inst, attributes);
if (!canonical) {
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
return Void::Result::fail(std::move(canonical).error());
}
dir_lock.unlock();
const auto sid = resolve_or_create_series(inst_idx, *canonical);
const auto ts = clock->now();
const auto seq = gauge_seq_gen.fetch_add(1, std::memory_order_relaxed) + 1;
mutate_slot(inst_idx, sid, 0, [value, ts, seq](SeriesAccumulator& slot) {
slot.gauge_value = value;
slot.has_gauge_sample = true;
slot.gauge_timestamp = ts;
slot.gauge_seq = seq;
});
return {};
}
Void::Result::Result<void> observe_histogram_impl(
std::size_t inst_idx,
double value,
std::span<const AttributeView> attributes)
{
if (!std::isfinite(value)) {
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Histogram observation must be finite"));
}
std::shared_lock dir_lock{dir_mutex};
if (inst_idx >= instruments.size()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid InstrumentHandle index"));
}
const auto& inst = *instruments[inst_idx];
if (inst.spec.kind != MetricKind::histogram) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::schema_conflict,
"Instrument is not a histogram"));
}
const auto bounds = inst.spec.bucket_bounds;
auto canonical = build_canonical_labels(inst, attributes);
if (!canonical) {
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
return Void::Result::fail(std::move(canonical).error());
}
dir_lock.unlock();
const auto sid = resolve_or_create_series(inst_idx, *canonical);
std::size_t bucket_idx = bounds.size();
for (std::size_t i = 0; i < bounds.size(); ++i) {
if (value <= bounds[i]) {
bucket_idx = i;
break;
}
}
const std::size_t total_buckets = bounds.size() + 1;
mutate_slot(inst_idx, sid, total_buckets, [value, bucket_idx](SeriesAccumulator& slot) {
++slot.hist_buckets[bucket_idx];
++slot.hist_count;
slot.hist_sum += value;
});
return {};
}
static void hook_record(void* state, const MetricPoint& pt) noexcept
{
if (state == nullptr) {
return;
}
auto* self = static_cast<Impl*>(state);
try {
std::optional<std::size_t> idx;
{
std::shared_lock lock{self->dir_mutex};
if (const auto it = self->name_to_index.find(std::string{pt.name});
it != self->name_to_index.end()) {
idx = it->second;
}
}
if (!idx.has_value()) {
self->unregistered_hook_points.fetch_add(1, std::memory_order_relaxed);
return;
}
switch (pt.kind) {
case MetricKind::counter: {
const std::uint64_t delta = pt.integer_delta != 0
? pt.integer_delta
: (pt.value >= 0.0 && std::isfinite(pt.value)
? static_cast<std::uint64_t>(pt.value)
: 0ULL);
(void)self->add_counter_impl(*idx, delta, pt.attributes);
break;
}
case MetricKind::gauge:
(void)self->set_gauge_impl(*idx, pt.value, pt.attributes);
break;
case MetricKind::histogram:
(void)self->observe_histogram_impl(*idx, pt.value, pt.attributes);
break;
}
} catch (...) {
self->rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
}
}
const std::uint64_t id;
MetricsLimits limits;
const Void::Time::MonotonicClock* clock;
mutable std::shared_mutex dir_mutex;
std::vector<std::unique_ptr<InstrumentData>> instruments;
std::unordered_map<std::string, std::size_t> name_to_index;
mutable std::mutex shards_mutex;
std::vector<std::shared_ptr<Shard>> shards;
std::shared_ptr<Shard> fallback_shard;
std::atomic<std::uint64_t> epoch{1};
std::atomic<std::size_t> total_series{0};
std::atomic<std::size_t> estimated_bytes{0};
std::atomic<std::uint64_t> dropped_series{0};
std::atomic<std::uint64_t> overflow_events{0};
std::atomic<std::uint64_t> rejected_invalid_points{0};
std::atomic<std::uint64_t> shared_shard_fallbacks{0};
std::atomic<std::uint64_t> unregistered_hook_points{0};
std::atomic<std::uint64_t> gauge_seq_gen{0};
};
MetricRegistry::MetricRegistry(std::shared_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
MetricRegistry::~MetricRegistry() = default;
Void::Result::Result<MetricRegistry> MetricRegistry::create(
MetricsLimits limits,
const Void::Time::MonotonicClock& clock)
{
if (auto v = limits.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
auto impl = std::make_shared<Impl>(limits, &clock);
return MetricRegistry{std::move(impl)};
}
Void::Result::Result<InstrumentHandle>
MetricRegistry::register_instrument(InstrumentSpec spec)
{
if (!impl_) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::closed,
"MetricRegistry is moved-from"));
}
if (spec.name.empty() || spec.name.size() > impl_->limits.max_key_bytes ||
!valid_label_name(spec.name)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid instrument name"));
}
if (spec.unit.size() > impl_->limits.max_key_bytes || !valid_token(spec.unit)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid instrument unit"));
}
if (spec.label_keys.size() > impl_->limits.max_labels_per_point) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Instrument label key count exceeds max_labels_per_point"));
}
for (std::size_t i = 0; i < spec.label_keys.size(); ++i) {
const auto& k = spec.label_keys[i];
if (k.size() > impl_->limits.max_key_bytes || !valid_label_name(k)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Invalid instrument label key"));
}
for (std::size_t j = 0; j < i; ++j) {
if (spec.label_keys[j] == k) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Duplicate label key in InstrumentSpec"));
}
}
}
if (spec.kind == MetricKind::histogram) {
if (spec.bucket_bounds.empty()) {
spec.bucket_bounds = default_duration_buckets_seconds();
} else {
for (std::size_t i = 0; i < spec.bucket_bounds.size(); ++i) {
if (!std::isfinite(spec.bucket_bounds[i]) ||
(i > 0 && spec.bucket_bounds[i] <= spec.bucket_bounds[i - 1])) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Histogram bucket bounds must be strictly increasing finite numbers"));
}
}
}
} else if (!spec.bucket_bounds.empty()) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"Only histogram instruments accept bucket bounds"));
}
std::unique_lock lock{impl_->dir_mutex};
if (const auto it = impl_->name_to_index.find(spec.name);
it != impl_->name_to_index.end()) {
const auto idx = it->second;
const auto& existing = impl_->instruments[idx]->spec;
if (existing.kind != spec.kind || existing.unit != spec.unit ||
existing.label_keys != spec.label_keys ||
existing.bucket_bounds != spec.bucket_bounds) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::schema_conflict,
"Instrument already registered with conflicting schema: " + spec.name));
}
return InstrumentHandle{idx, impl_->id};
}
if (impl_->instruments.size() >= impl_->limits.max_instruments) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::capacity_exceeded,
"MetricRegistry max_instruments reached"));
}
const std::size_t meta_cost =
kPerSeriesOverheadBytes + spec.name.size() + spec.unit.size() +
(spec.bucket_bounds.size() + 1) * sizeof(double);
const std::size_t used_bytes = impl_->estimated_bytes.load(std::memory_order_relaxed);
if (meta_cost > impl_->limits.max_storage_bytes - std::min(used_bytes, impl_->limits.max_storage_bytes)) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::capacity_exceeded,
"MetricRegistry max_storage_bytes exceeded"));
}
auto inst = std::make_unique<Impl::InstrumentData>();
inst->spec = std::move(spec);
// Pre-register dedicated __overflow__ slot at index 0.
Impl::SeriesMeta overflow_meta;
overflow_meta.series_id = 0;
overflow_meta.is_overflow = true;
overflow_meta.labels = {{"__overflow__", "true"}};
overflow_meta.byte_cost = meta_cost;
inst->series.push_back(std::move(overflow_meta));
const std::size_t idx = impl_->instruments.size();
impl_->name_to_index.emplace(inst->spec.name, idx);
impl_->instruments.push_back(std::move(inst));
impl_->estimated_bytes.fetch_add(meta_cost, std::memory_order_relaxed);
return InstrumentHandle{idx, impl_->id};
}
Void::Result::Result<void> MetricRegistry::add_counter(
InstrumentHandle handle,
std::uint64_t delta,
std::span<const AttributeView> attributes)
{
if (!impl_ || handle.registry_id != impl_->id) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"InstrumentHandle does not belong to this MetricRegistry"));
}
return impl_->add_counter_impl(handle.index, delta, attributes);
}
Void::Result::Result<void> MetricRegistry::set_gauge(
InstrumentHandle handle,
double value,
std::span<const AttributeView> attributes)
{
if (!impl_ || handle.registry_id != impl_->id) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"InstrumentHandle does not belong to this MetricRegistry"));
}
return impl_->set_gauge_impl(handle.index, value, attributes);
}
Void::Result::Result<void> MetricRegistry::observe_histogram(
InstrumentHandle handle,
double value,
std::span<const AttributeView> attributes)
{
if (!impl_ || handle.registry_id != impl_->id) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"InstrumentHandle does not belong to this MetricRegistry"));
}
return impl_->observe_histogram_impl(handle.index, value, attributes);
}
MetricsSnapshot MetricRegistry::snapshot() const
{
MetricsSnapshot snap;
if (!impl_) {
return snap;
}
std::shared_lock dir_lock{impl_->dir_mutex};
std::vector<std::shared_ptr<Impl::Shard>> all_shards;
{
std::lock_guard slock{impl_->shards_mutex};
all_shards = impl_->shards;
all_shards.push_back(impl_->fallback_shard);
}
snap.epoch = impl_->epoch.load(std::memory_order_acquire);
snap.dropped_series = impl_->dropped_series.load(std::memory_order_relaxed);
snap.overflow_events = impl_->overflow_events.load(std::memory_order_relaxed);
snap.rejected_invalid_points =
impl_->rejected_invalid_points.load(std::memory_order_relaxed);
snap.shared_shard_fallbacks =
impl_->shared_shard_fallbacks.load(std::memory_order_relaxed);
snap.unregistered_hook_points =
impl_->unregistered_hook_points.load(std::memory_order_relaxed);
snap.estimated_bytes = impl_->estimated_bytes.load(std::memory_order_relaxed);
snap.shard_count = all_shards.size() - 1;
snap.instruments.resize(impl_->instruments.size());
std::vector<std::vector<std::uint64_t>> gauge_seqs(impl_->instruments.size());
for (std::size_t i = 0; i < impl_->instruments.size(); ++i) {
const auto& inst = *impl_->instruments[i];
auto& out_inst = snap.instruments[i];
out_inst.spec = inst.spec;
out_inst.dropped_series = inst.dropped_series.load(std::memory_order_relaxed);
out_inst.overflow_events = inst.overflow_events.load(std::memory_order_relaxed);
out_inst.series.resize(inst.series.size());
gauge_seqs[i].assign(inst.series.size(), 0);
for (std::size_t s = 0; s < inst.series.size(); ++s) {
out_inst.series[s].labels = inst.series[s].labels;
out_inst.series[s].is_overflow = inst.series[s].is_overflow;
if (inst.spec.kind == MetricKind::histogram) {
out_inst.series[s].histogram.bounds = inst.spec.bucket_bounds;
out_inst.series[s].histogram.bucket_counts.assign(
inst.spec.bucket_bounds.size() + 1, 0);
}
}
}
for (const auto& shard : all_shards) {
std::lock_guard lock{shard->mutex};
const std::size_t max_inst =
std::min(shard->data.size(), impl_->instruments.size());
for (std::size_t i = 0; i < max_inst; ++i) {
const auto& kind = impl_->instruments[i]->spec.kind;
const auto& src_series = shard->data[i];
const std::size_t max_ser =
std::min(src_series.size(), snap.instruments[i].series.size());
for (std::size_t s = 0; s < max_ser; ++s) {
const auto& src = src_series[s];
auto& dst = snap.instruments[i].series[s];
switch (kind) {
case MetricKind::counter:
dst.counter_value = saturating_add_u64(
dst.counter_value, src.counter_value, dst.counter_saturated);
dst.counter_saturated = dst.counter_saturated || src.counter_saturated;
break;
case MetricKind::gauge:
if (src.has_gauge_sample && src.gauge_seq >= gauge_seqs[i][s]) {
gauge_seqs[i][s] = src.gauge_seq;
dst.gauge_value = src.gauge_value;
dst.gauge_timestamp = src.gauge_timestamp;
dst.has_gauge_sample = true;
}
break;
case MetricKind::histogram:
dst.histogram.count += src.hist_count;
dst.histogram.sum += src.hist_sum;
for (std::size_t b = 0;
b < std::min(src.hist_buckets.size(),
dst.histogram.bucket_counts.size());
++b) {
dst.histogram.bucket_counts[b] += src.hist_buckets[b];
}
break;
}
}
}
}
// Omit the pre-registered __overflow__ entry when no overflow occurred.
for (std::size_t i = 0; i < impl_->instruments.size(); ++i) {
auto& out_inst = snap.instruments[i];
if (!impl_->instruments[i]->overflow_seen.load(std::memory_order_acquire) &&
!out_inst.series.empty() && out_inst.series.front().is_overflow) {
out_inst.series.erase(out_inst.series.begin());
}
}
return snap;
}
void MetricRegistry::reset_epoch()
{
if (!impl_) {
return;
}
std::unique_lock dir_lock{impl_->dir_mutex};
std::vector<std::shared_ptr<Impl::Shard>> all_shards;
{
std::lock_guard slock{impl_->shards_mutex};
all_shards = impl_->shards;
all_shards.push_back(impl_->fallback_shard);
}
for (const auto& shard : all_shards) {
std::lock_guard lock{shard->mutex};
for (auto& inst_vec : shard->data) {
for (auto& slot : inst_vec) {
slot.counter_value = 0;
slot.counter_saturated = false;
slot.gauge_value = 0.0;
slot.has_gauge_sample = false;
slot.gauge_seq = 0;
std::fill(slot.hist_buckets.begin(), slot.hist_buckets.end(), 0);
slot.hist_count = 0;
slot.hist_sum = 0.0;
}
}
}
for (const auto& inst : impl_->instruments) {
inst->overflow_seen.store(false, std::memory_order_release);
inst->dropped_series.store(0, std::memory_order_relaxed);
inst->overflow_events.store(0, std::memory_order_relaxed);
}
impl_->dropped_series.store(0, std::memory_order_relaxed);
impl_->overflow_events.store(0, std::memory_order_relaxed);
impl_->epoch.fetch_add(1, std::memory_order_release);
}
ObservationHooks MetricRegistry::make_hooks() const noexcept
{
if (!impl_) {
return kNullObservationHooks;
}
return ObservationHooks{
impl_.get(),
&Impl::hook_record,
nullptr};
}
std::shared_ptr<const void> MetricRegistry::keepalive() const noexcept
{
return impl_;
}
const MetricsLimits& MetricRegistry::limits() const noexcept
{
static const MetricsLimits kDefault{};
return impl_ ? impl_->limits : kDefault;
}
} // namespace Void::Observability
+700
View File
@@ -0,0 +1,700 @@
#include <Void/Observability/Tracing.hpp>
#include <Void/Core/Hash.hpp>
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <deque>
#include <format>
#include <mutex>
#include <utility>
#include <vector>
namespace Void::Observability
{
namespace
{
constexpr std::size_t kBaseSpanBytes = 192;
[[nodiscard]] bool is_valid_text(std::string_view sv) noexcept
{
for (const unsigned char ch : sv) {
if (ch < 0x20 || ch == 0x7F) {
return false;
}
}
return true;
}
[[nodiscard]] std::string truncate_with_marker(std::string_view sv,
std::size_t max_bytes,
bool& truncated)
{
if (sv.size() <= max_bytes) {
return std::string{sv};
}
truncated = true;
constexpr std::string_view kMarker = "...[truncated]";
if (max_bytes <= kMarker.size()) {
return std::string{sv.substr(0, max_bytes)};
}
std::string out{sv.substr(0, max_bytes - kMarker.size())};
out += kMarker;
return out;
}
[[nodiscard]] std::string_view status_str(SpanStatus s) noexcept
{
switch (s) {
case SpanStatus::unset: return "unset";
case SpanStatus::ok: return "ok";
case SpanStatus::error: return "error";
case SpanStatus::abandoned: return "abandoned";
}
return "unset";
}
inline thread_local std::vector<const void*> t_active_exporters;
struct ExporterRecursionGuard {
const void* ptr{nullptr};
bool reentered{false};
explicit ExporterRecursionGuard(const void* p) : ptr(p)
{
for (const auto* active : t_active_exporters) {
if (active == ptr) {
reentered = true;
return;
}
}
t_active_exporters.push_back(ptr);
}
~ExporterRecursionGuard() noexcept
{
if (!reentered && !t_active_exporters.empty()) {
t_active_exporters.pop_back();
}
}
ExporterRecursionGuard(const ExporterRecursionGuard&) = delete;
ExporterRecursionGuard& operator=(const ExporterRecursionGuard&) = delete;
};
} // namespace
Void::Result::Result<void> TracingLimits::validate() const
{
if (max_active_spans == 0 || max_active_bytes == 0 ||
max_completed_spans == 0 || max_completed_bytes == 0 ||
max_attributes_per_span == 0 || max_events_per_span == 0 ||
max_bytes_per_span == 0 || max_key_bytes == 0 ||
max_value_bytes == 0 || max_export_batch_spans == 0 ||
max_export_batch_bytes == 0 || root_sample_denominator == 0 ||
export_retry_budget.count() < 0) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::invalid_argument,
"TracingLimits values must be positive"));
}
return {};
}
CallbackSpanExporter::CallbackSpanExporter(Callback callback)
: callback_(std::move(callback))
{
}
Void::Result::Result<void> CallbackSpanExporter::export_spans(
std::span<const CompletedSpan> spans)
{
ExporterRecursionGuard guard{this};
if (guard.reentered) {
reentrant_drops_.fetch_add(1, std::memory_order_relaxed);
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::would_deadlock,
"Reentrant span export suppressed"));
}
if (!callback_) {
return {};
}
try {
return callback_(spans);
} catch (const std::exception& e) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::quarantined,
std::string{"Span exporter callback threw: "} + e.what()));
} catch (...) {
return Void::Result::fail(make_observability_error(
ObservabilityErrorCode::quarantined,
"Span exporter callback threw unknown exception"));
}
}
TextSnapshotExporter::TextSnapshotExporter(std::size_t max_output_bytes)
: max_output_bytes_(max_output_bytes)
{
}
Void::Result::Result<void> TextSnapshotExporter::export_spans(
std::span<const CompletedSpan> spans)
{
const auto rendered = render_spans(spans, max_output_bytes_);
std::lock_guard lock{mutex_};
if (buffer_.size() < max_output_bytes_) {
const std::size_t rem = max_output_bytes_ - buffer_.size();
if (rendered.size() <= rem) {
buffer_ += rendered;
} else {
buffer_.append(rendered.data(), rem);
}
}
return {};
}
std::string TextSnapshotExporter::render_metrics(
const MetricsSnapshot& metrics,
std::size_t max_output_bytes)
{
std::string out;
out += std::format("epoch={} instruments={} dropped_series={} overflow_events={}\n",
metrics.epoch,
metrics.instruments.size(),
metrics.dropped_series,
metrics.overflow_events);
for (const auto& inst : metrics.instruments) {
for (const auto& ser : inst.series) {
std::string line = inst.spec.name;
line += '{';
for (std::size_t i = 0; i < ser.labels.size(); ++i) {
if (i > 0) {
line += ',';
}
line += ser.labels[i].first;
line += '=';
line += ser.labels[i].second;
}
line += '}';
switch (inst.spec.kind) {
case MetricKind::counter:
line += std::format(" {}\n", ser.counter_value);
break;
case MetricKind::gauge:
line += std::format(" {}\n", ser.gauge_value);
break;
case MetricKind::histogram:
line += std::format(" count={} sum={}\n",
ser.histogram.count,
ser.histogram.sum);
break;
}
if (out.size() + line.size() > max_output_bytes) {
return out;
}
out += line;
}
}
return out;
}
std::string TextSnapshotExporter::render_spans(
std::span<const CompletedSpan> spans,
std::size_t max_output_bytes)
{
std::string out;
for (const auto& sp : spans) {
const auto dur_us =
std::chrono::duration_cast<std::chrono::microseconds>(
sp.end_time >= sp.start_time ? (sp.end_time - sp.start_time)
: std::chrono::nanoseconds{0})
.count();
std::string line = std::format(
"span trace={} span={} name={} status={} duration_us={} attrs={} events={} truncated={}\n",
sp.context.trace_id.to_hex(),
sp.context.span_id.to_hex(),
sp.name,
status_str(sp.status),
dur_us,
sp.attributes.size(),
sp.events.size(),
sp.truncated ? 1 : 0);
if (out.size() + line.size() > max_output_bytes) {
break;
}
out += line;
}
return out;
}
std::string TextSnapshotExporter::text() const
{
std::lock_guard lock{mutex_};
return buffer_;
}
void TextSnapshotExporter::clear()
{
std::lock_guard lock{mutex_};
buffer_.clear();
}
struct Tracer::Impl {
Impl(TracingLimits lim,
std::shared_ptr<SpanExporter> exp,
const Void::Time::MonotonicClock* clk,
const Void::Time::CivilClock* civil)
: limits(lim)
, exporter(std::move(exp))
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
, civil_clock(civil != nullptr ? civil : &Void::Time::SystemCivilClock::instance())
{
}
void complete_span(CompletedSpan span, std::size_t reserved_active_bytes) noexcept
{
std::lock_guard lock{mutex};
if (active_spans > 0) {
--active_spans;
}
active_bytes =
active_bytes >= reserved_active_bytes
? (active_bytes - reserved_active_bytes)
: 0;
if (span.status == SpanStatus::abandoned) {
++abandoned_spans;
}
const std::size_t budget_used = completed_bytes + in_flight_export_bytes;
if (completed.size() >= limits.max_completed_spans ||
span.estimated_bytes >
limits.max_completed_bytes -
std::min(budget_used, limits.max_completed_bytes)) {
++dropped_completed_spans;
return;
}
completed_bytes += span.estimated_bytes;
completed.push_back(std::move(span));
}
TracingLimits limits;
std::shared_ptr<SpanExporter> exporter;
const Void::Time::MonotonicClock* clock;
const Void::Time::CivilClock* civil_clock;
mutable std::mutex mutex;
std::size_t active_spans{0};
std::size_t active_bytes{0};
std::deque<CompletedSpan> completed{};
std::size_t completed_bytes{0};
std::size_t in_flight_export_bytes{0};
bool closed{false};
std::uint64_t dropped_active_spans{0};
std::uint64_t dropped_completed_spans{0};
std::uint64_t duplicate_ends{0};
std::uint64_t abandoned_spans{0};
std::uint64_t exported_spans{0};
std::uint64_t failed_exports{0};
std::uint64_t reentrant_export_drops{0};
};
struct Span::State {
std::shared_ptr<Tracer::Impl> tracer;
std::mutex mutex;
CompletedSpan data{};
std::size_t reserved_bytes{0};
std::atomic<bool> ended{false};
};
Span::Span(ContextSnapshot context, std::shared_ptr<State> state) noexcept
: context_(std::move(context))
, state_(std::move(state))
{
}
Span::~Span() noexcept
{
if (state_ && !ended_) {
end(SpanStatus::abandoned);
}
}
Span::Span(Span&& other) noexcept
: context_(std::move(other.context_))
, state_(std::move(other.state_))
, ended_(std::exchange(other.ended_, true))
{
}
Span& Span::operator=(Span&& other) noexcept
{
if (this != &other) {
if (state_ && !ended_) {
end(SpanStatus::abandoned);
}
context_ = std::move(other.context_);
state_ = std::move(other.state_);
ended_ = std::exchange(other.ended_, true);
}
return *this;
}
void Span::set_attribute(std::string_view key, std::string_view value)
{
if (!state_ || ended_ || key.empty() || !is_valid_text(key)) {
return;
}
const auto& lim = state_->tracer->limits;
std::lock_guard lock{state_->mutex};
if (state_->ended.load(std::memory_order_acquire) ||
state_->data.attributes.size() >= lim.max_attributes_per_span ||
key.size() > lim.max_key_bytes) {
return;
}
bool trunc = false;
auto val_str = truncate_with_marker(value, lim.max_value_bytes, trunc);
const std::size_t delta = key.size() + val_str.size();
if (delta > lim.max_bytes_per_span -
std::min(state_->data.estimated_bytes, lim.max_bytes_per_span)) {
state_->data.truncated = true;
return;
}
if (trunc) {
state_->data.truncated = true;
}
state_->data.estimated_bytes += delta;
state_->data.attributes.emplace_back(std::string{key}, std::move(val_str));
}
void Span::add_event(std::string_view name)
{
if (!state_ || ended_ || name.empty() || !is_valid_text(name)) {
return;
}
const auto& lim = state_->tracer->limits;
std::lock_guard lock{state_->mutex};
if (state_->ended.load(std::memory_order_acquire) ||
state_->data.events.size() >= lim.max_events_per_span) {
return;
}
bool trunc = false;
auto evt_name = truncate_with_marker(name, lim.max_key_bytes, trunc);
const std::size_t delta = evt_name.size() + sizeof(SpanEvent);
if (delta > lim.max_bytes_per_span -
std::min(state_->data.estimated_bytes, lim.max_bytes_per_span)) {
state_->data.truncated = true;
return;
}
if (trunc) {
state_->data.truncated = true;
}
state_->data.estimated_bytes += delta;
state_->data.events.push_back(
SpanEvent{std::move(evt_name), state_->tracer->clock->now()});
}
void Span::end(SpanStatus status) noexcept
{
if (!state_) {
return;
}
bool expected = false;
if (!state_->ended.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
ended_ = true;
std::lock_guard lock{state_->tracer->mutex};
++state_->tracer->duplicate_ends;
return;
}
ended_ = true;
CompletedSpan finalized;
std::size_t reserved = 0;
{
std::lock_guard lock{state_->mutex};
state_->data.end_time = state_->tracer->clock->now();
state_->data.status = status;
finalized = std::move(state_->data);
reserved = state_->reserved_bytes;
}
state_->tracer->complete_span(std::move(finalized), reserved);
}
Tracer::Tracer(std::shared_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
Tracer::~Tracer() = default;
Void::Result::Result<Tracer> Tracer::create(
TracingLimits limits,
std::shared_ptr<SpanExporter> exporter,
const Void::Time::MonotonicClock& clock,
const Void::Time::CivilClock& civil_clock)
{
if (auto v = limits.validate(); !v) {
return Void::Result::fail(std::move(v).error());
}
return Tracer{
std::make_shared<Impl>(limits, std::move(exporter), &clock, &civil_clock)};
}
Span Tracer::start_span(const ContextSnapshot& parent, SpanSpec spec)
{
if (!impl_) {
return Span{};
}
TraceId tid{};
std::optional<SpanId> parent_sid;
bool sampled = false;
if (const auto& ptrace = parent.trace(); ptrace.has_value() && ptrace->valid()) {
tid = ptrace->trace_id;
parent_sid = ptrace->span_id;
sampled = ptrace->sampled();
} else {
if (spec.explicit_root_trace_id.has_value() &&
!spec.explicit_root_trace_id->is_zero()) {
tid = *spec.explicit_root_trace_id;
} else if (auto gen = TraceId::generate()) {
tid = *gen;
} else {
tid = TraceId::generate_seeded(1);
}
const std::uint64_t h = Void::Hash::fnv1a64(
std::span<const std::byte>{tid.bytes.data(), tid.bytes.size()});
sampled = (h % impl_->limits.root_sample_denominator) == 0;
}
SpanId sid{};
if (auto gen_sid = SpanId::generate()) {
sid = *gen_sid;
} else {
sid = SpanId::generate_seeded(1);
}
const std::uint8_t flags = sampled ? kTraceFlagSampled : 0;
ContextSnapshot child_ctx =
parent.with_trace(TraceContext{tid, sid, flags});
if (!sampled) {
return Span{std::move(child_ctx), nullptr};
}
const auto& lim = impl_->limits;
bool trunc = false;
std::string clean_name =
spec.name.empty() ? std::string{"unnamed"}
: truncate_with_marker(spec.name, lim.max_key_bytes, trunc);
std::size_t initial_bytes = kBaseSpanBytes + clean_name.size();
std::vector<std::pair<std::string, std::string>> clean_attrs;
for (const auto& [k, v] : spec.attributes) {
if (clean_attrs.size() >= lim.max_attributes_per_span) {
trunc = true;
break;
}
if (k.empty() || k.size() > lim.max_key_bytes || !is_valid_text(k)) {
continue;
}
bool attr_trunc = false;
auto val = truncate_with_marker(v, lim.max_value_bytes, attr_trunc);
const std::size_t add = k.size() + val.size();
if (initial_bytes + add > lim.max_bytes_per_span) {
trunc = true;
break;
}
if (attr_trunc) {
trunc = true;
}
initial_bytes += add;
clean_attrs.emplace_back(k, std::move(val));
}
const std::size_t active_reserve = lim.max_bytes_per_span;
{
std::lock_guard lock{impl_->mutex};
if (impl_->closed ||
impl_->active_spans >= lim.max_active_spans ||
active_reserve >
lim.max_active_bytes -
std::min(impl_->active_bytes, lim.max_active_bytes)) {
++impl_->dropped_active_spans;
child_ctx = parent.with_trace(TraceContext{tid, sid, 0});
return Span{std::move(child_ctx), nullptr};
}
++impl_->active_spans;
impl_->active_bytes += active_reserve;
}
auto state = std::make_shared<Span::State>();
state->tracer = impl_;
state->reserved_bytes = active_reserve;
state->data.context = TraceContext{tid, sid, flags};
state->data.parent_span_id = parent_sid;
state->data.name = std::move(clean_name);
state->data.start_time = impl_->clock->now();
state->data.end_time = state->data.start_time;
state->data.civil_start_time = impl_->civil_clock->now();
state->data.attributes = std::move(clean_attrs);
state->data.truncated = trunc;
state->data.estimated_bytes = initial_bytes;
return Span{std::move(child_ctx), std::move(state)};
}
ExportReport Tracer::flush(ExportOptions options)
{
ExportReport report;
if (!impl_) {
return report;
}
std::size_t remaining_to_drain = 0;
{
std::lock_guard lock{impl_->mutex};
report.duplicate_ends = impl_->duplicate_ends;
report.dropped_spans =
impl_->dropped_active_spans + impl_->dropped_completed_spans;
remaining_to_drain = impl_->completed.size();
}
while (remaining_to_drain > 0) {
if (options.stop.stop_requested()) {
report.cancelled = true;
break;
}
if (options.deadline.has_value() && impl_->clock->now() >= *options.deadline) {
report.timed_out = true;
break;
}
ExportBatch batch;
{
std::lock_guard lock{impl_->mutex};
if (impl_->completed.empty()) {
break;
}
const std::size_t cap_spans =
std::min(remaining_to_drain, impl_->limits.max_export_batch_spans);
while (!impl_->completed.empty() && batch.spans.size() < cap_spans) {
const auto& front = impl_->completed.front();
if (!batch.spans.empty() &&
batch.estimated_bytes + front.estimated_bytes >
impl_->limits.max_export_batch_bytes) {
break;
}
batch.estimated_bytes += front.estimated_bytes;
impl_->completed_bytes =
impl_->completed_bytes >= front.estimated_bytes
? (impl_->completed_bytes - front.estimated_bytes)
: 0;
batch.spans.push_back(std::move(impl_->completed.front()));
impl_->completed.pop_front();
--remaining_to_drain;
}
impl_->in_flight_export_bytes += batch.estimated_bytes;
}
if (batch.spans.empty()) {
break;
}
bool ok = true;
if (impl_->exporter) {
const auto retry_start = impl_->clock->now();
ok = false;
for (std::size_t attempt = 0;
attempt <= impl_->limits.max_export_retries;
++attempt) {
if (options.stop.stop_requested()) {
report.cancelled = true;
break;
}
if (options.deadline.has_value() &&
impl_->clock->now() >= *options.deadline) {
report.timed_out = true;
break;
}
if (attempt > 0) {
if (impl_->clock->now() - retry_start >=
impl_->limits.export_retry_budget) {
report.timed_out = true;
break;
}
++report.retries;
}
const auto res = impl_->exporter->export_spans(batch.spans);
if (res.has_value()) {
ok = true;
break;
}
if (res.error().code().value ==
static_cast<std::int32_t>(ObservabilityErrorCode::would_deadlock)) {
std::lock_guard lock{impl_->mutex};
++impl_->reentrant_export_drops;
break;
}
}
}
{
std::lock_guard lock{impl_->mutex};
impl_->in_flight_export_bytes =
impl_->in_flight_export_bytes >= batch.estimated_bytes
? (impl_->in_flight_export_bytes - batch.estimated_bytes)
: 0;
if (ok) {
impl_->exported_spans += batch.spans.size();
report.exported_spans += batch.spans.size();
} else {
++impl_->failed_exports;
report.failed_spans += batch.spans.size();
}
}
if (report.cancelled || report.timed_out) {
break;
}
}
return report;
}
ExportReport Tracer::close(ExportOptions options)
{
if (!impl_) {
return {};
}
{
std::lock_guard lock{impl_->mutex};
impl_->closed = true;
}
return flush(options);
}
TracerStats Tracer::stats() const
{
TracerStats st;
if (!impl_) {
return st;
}
std::lock_guard lock{impl_->mutex};
st.active_spans = impl_->active_spans;
st.active_bytes = impl_->active_bytes;
st.completed_spans = impl_->completed.size();
st.completed_bytes = impl_->completed_bytes;
st.in_flight_export_bytes = impl_->in_flight_export_bytes;
st.dropped_active_spans = impl_->dropped_active_spans;
st.dropped_completed_spans = impl_->dropped_completed_spans;
st.duplicate_ends = impl_->duplicate_ends;
st.abandoned_spans = impl_->abandoned_spans;
st.exported_spans = impl_->exported_spans;
st.failed_exports = impl_->failed_exports;
st.reentrant_export_drops = impl_->reentrant_export_drops;
st.closed = impl_->closed;
return st;
}
} // namespace Void::Observability
+4
View File
@@ -0,0 +1,4 @@
void_add_module(Observability
INTERNAL_DEPS ObservabilityHooks Core Functional Time Memory
EXCLUDE_HEADERS Void/Observability/Hooks.hpp
)
+3
View File
@@ -0,0 +1,3 @@
void_add_module(ObservabilityHooks
EXTRA_HEADERS Void/Observability/Hooks.hpp
)
+4 -1
View File
@@ -1 +1,4 @@
void_add_module(Resilience)
void_add_module(Resilience
INTERNAL_DEPS Functional Time ObservabilityHooks
EXCLUDE_HEADERS Void/Resilience/AsyncPolicy.hpp
)
+4
View File
@@ -0,0 +1,4 @@
void_add_module(ResilienceAsync
INTERNAL_DEPS Resilience Async Functional Time ObservabilityHooks
EXTRA_HEADERS Void/Resilience/AsyncPolicy.hpp
)
+732 -102
View File
@@ -1,114 +1,744 @@
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/Stacktrace/Color.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <filesystem>
#include <format>
#include <fstream>
#include <sstream>
#include <Void/Stacktrace/Color.hpp>
#ifndef _WIN32
#include <dlfcn.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <boost/core/demangle.hpp>
#include <boost/stacktrace.hpp>
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <filesystem>
#include <format>
#include <fstream>
#include <list>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <utility>
namespace Void::Stacktrace
{
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames,
unsigned max_frames)
{
std::vector<StackFrame> result;
try {
boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames);
for (auto it = bt.begin(); it != bt.end(); ++it) {
StackFrame frame;
std::string name = it->name();
if (!name.empty()) {
frame.function_name = boost::core::demangle(name.c_str());
}
frame.source_file = it->source_file();
frame.source_line = it->source_line();
if (!frame.source_file.empty() && frame.source_line > 0) {
frame.source_snippet =
read_source_snippet(frame.source_file,
frame.source_line, 2)
.value_or(std::string{});
}
result.push_back(std::move(frame));
}
} catch (...) {
}
Void::Log::debug("Stacktrace", "captured {} frames", result.size());
return result;
}
namespace
{
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file, int line,
int context_lines)
{
std::ifstream ifs{file};
if (!ifs.is_open()) {
Void::Log::warn("Stacktrace", "read_source_snippet: cannot open '{}'", file);
return Void::Result::fail(
std::format("read_source_snippet: cannot open '{}'", file));
}
std::ostringstream result;
std::string current_line;
int line_num = 1;
int start = std::max(1, line - context_lines);
int end = line + context_lines;
while (std::getline(ifs, current_line)) {
if (line_num >= start && line_num <= end) {
std::string prefix = (line_num == line) ? " >>> " : " ";
result << std::format("{:>4}{}{}\n", line_num, prefix,
current_line);
}
if (line_num > end) {
break;
}
++line_num;
}
return Void::Result::ok(result.str());
}
[[nodiscard]] RawFrame build_raw_frame(const void* addr_ptr)
{
RawFrame rf;
rf.address = reinterpret_cast<std::uintptr_t>(addr_ptr);
if (addr_ptr == nullptr) {
return rf;
}
#ifndef _WIN32
Dl_info info{};
if (::dladdr(addr_ptr, &info) != 0 && info.dli_fname != nullptr &&
info.dli_fname[0] != '\0') {
rf.module_path.assign(info.dli_fname);
const auto base = reinterpret_cast<std::uintptr_t>(info.dli_fbase);
rf.module_offset = (rf.address >= base) ? (rf.address - base) : 0;
struct stat st {};
if (::stat(info.dli_fname, &st) == 0) {
rf.module_id = std::format(
"{}:{}:{}:{}",
static_cast<unsigned long long>(st.st_dev),
static_cast<unsigned long long>(st.st_ino),
static_cast<unsigned long long>(st.st_size),
rf.module_path);
} else {
rf.module_id = rf.module_path;
}
}
#endif
return rf;
}
std::string format_stacktrace(const std::vector<StackFrame>& frames)
{
if (frames.empty()) {
return " <no stacktrace available>\n";
}
std::ostringstream oss;
for (size_t i = 0; i < frames.size(); ++i) {
const auto& frame = frames[i];
oss << std::format(" #{:02} ", i);
if (!frame.function_name.empty()) {
oss << (Color::g_color_enabled
? Color::apply(Color::bold_cyan,
frame.function_name)
: frame.function_name);
} else {
oss << "<unknown>";
}
if (!frame.source_file.empty() && frame.source_line > 0) {
std::filesystem::path p{frame.source_file};
oss << "\n at "
<< (Color::g_color_enabled
? Color::apply(Color::dim, p.filename().string())
: p.filename().string())
<< ":" << frame.source_line;
}
oss << "\n";
if (!frame.source_snippet.empty() && i < 5) {
oss << " "
<< (Color::g_color_enabled
? Color::apply(Color::dim, frame.source_snippet)
: frame.source_snippet);
}
}
return oss.str();
}
[[nodiscard]] std::string redact_source_path(
std::string_view raw_path,
const std::vector<std::string>& redact_prefixes)
{
if (raw_path.empty()) {
return {};
}
if (redact_prefixes.empty()) {
return std::filesystem::path{raw_path}.filename().string();
}
std::string_view best_match;
for (const auto& prefix : redact_prefixes) {
if (!prefix.empty() && raw_path.starts_with(prefix) &&
prefix.size() > best_match.size()) {
best_match = prefix;
}
}
if (!best_match.empty()) {
std::string_view rest = raw_path.substr(best_match.size());
while (!rest.empty() && (rest.front() == '/' || rest.front() == '\\')) {
rest.remove_prefix(1);
}
return std::string{rest};
}
return std::filesystem::path{raw_path}.filename().string();
}
void print_stacktrace(std::ostream& os,
const std::vector<StackFrame>& frames)
{
os << format_stacktrace(frames);
}
} // namespace Void::Stacktrace
[[nodiscard]] bool is_under_allowed_roots(
const std::filesystem::path& file,
const std::vector<std::filesystem::path>& roots,
std::filesystem::path& out_canonical,
Void::Result::Error& out_error)
{
if (roots.empty()) {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
"Source snippets require non-empty allowed_source_roots");
return false;
}
for (const auto& part : file) {
if (part == "..") {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
"Path traversal ('..') is rejected for source snippets");
return false;
}
}
std::error_code ec;
const auto canon_file = std::filesystem::canonical(file, ec);
if (ec) {
out_error = make_stacktrace_error(
StacktraceErrorCode::source_unreadable,
std::format("Cannot resolve snippet path '{}': {}",
file.string(), ec.message()));
return false;
}
if (!std::filesystem::is_regular_file(canon_file, ec) || ec) {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
std::format("Snippet target '{}' is not a regular file",
canon_file.string()));
return false;
}
for (const auto& root : roots) {
std::error_code rec;
const auto canon_root = std::filesystem::canonical(root, rec);
if (rec) {
continue;
}
const auto rel = canon_file.lexically_relative(canon_root);
if (!rel.empty() && rel.native() != "." && *rel.begin() != "..") {
out_canonical = canon_file;
return true;
}
}
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
std::format("Snippet path '{}' escapes allowed_source_roots",
canon_file.string()));
return false;
}
struct CacheKey {
std::string module_id;
std::uintptr_t offset{0};
[[nodiscard]] bool operator==(const CacheKey&) const = default;
};
struct CacheKeyHash {
[[nodiscard]] std::size_t operator()(const CacheKey& k) const noexcept
{
std::size_t h1 = std::hash<std::string>{}(k.module_id);
std::size_t h2 = std::hash<std::uintptr_t>{}(k.offset);
return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2));
}
};
struct CacheValue {
std::string function_name;
std::string raw_source_file;
int source_line{0};
FrameResolveStatus status{FrameResolveStatus::unresolved};
std::size_t byte_cost{0};
};
} // namespace
Capabilities capabilities() noexcept
{
#if defined(_WIN32) && !defined(__CYGWIN__)
return Capabilities{
.raw_capture = true,
.symbols = true,
.line_info = true,
.async_signal_safe = false,
.backend_name = "boost.stacktrace.windbg"};
#else
return Capabilities{
.raw_capture = true,
.symbols = true,
.line_info = true,
.async_signal_safe = false,
.backend_name = "boost.stacktrace.addr2line"};
#endif
}
Void::Result::Result<RawTrace> capture(CaptureOptions options)
{
if (options.max_frames == 0 || options.max_frames > kMaxCaptureFrames) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
std::format("CaptureOptions::max_frames must be in [1, {}]",
kMaxCaptureFrames)));
}
RawTrace trace;
try {
const std::size_t probe_depth =
static_cast<std::size_t>(options.max_frames) + 1;
boost::stacktrace::stacktrace bt(
static_cast<std::size_t>(options.skip) + 1, probe_depth);
if (bt.size() > options.max_frames) {
trace.truncated = true;
}
const std::size_t count =
std::min<std::size_t>(bt.size(), options.max_frames);
trace.frames.reserve(count);
for (std::size_t i = 0; i < count; ++i) {
trace.frames.push_back(build_raw_frame(bt[i].address()));
}
return trace;
} catch (const std::exception& e) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::backend_failed,
std::string{"Stacktrace raw capture failed: "} + e.what()));
} catch (...) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::backend_failed,
"Stacktrace raw capture failed"));
}
}
struct Resolver::Impl {
using LruList = std::list<std::pair<CacheKey, CacheValue>>;
using LookupMap = std::unordered_map<CacheKey, LruList::iterator, CacheKeyHash>;
std::size_t max_entries;
std::size_t max_bytes;
mutable std::mutex mutex;
LruList lru;
LookupMap map;
std::size_t current_bytes{0};
Impl(std::size_t entries, std::size_t bytes)
: max_entries(entries), max_bytes(bytes)
{
}
[[nodiscard]] std::optional<CacheValue> find_and_touch(const CacheKey& key)
{
if (key.module_id.empty()) {
return std::nullopt;
}
std::lock_guard lock{mutex};
const auto it = map.find(key);
if (it == map.end()) {
return std::nullopt;
}
lru.splice(lru.begin(), lru, it->second);
return it->second->second;
}
void insert(const CacheKey& key, CacheValue val)
{
if (key.module_id.empty() || max_entries == 0 || max_bytes == 0) {
return;
}
val.byte_cost =
96 + key.module_id.size() + val.function_name.size() +
val.raw_source_file.size();
if (val.byte_cost > max_bytes) {
return;
}
std::lock_guard lock{mutex};
if (const auto it = map.find(key); it != map.end()) {
current_bytes -= std::min(current_bytes, it->second->second.byte_cost);
it->second->second = val;
current_bytes += val.byte_cost;
lru.splice(lru.begin(), lru, it->second);
return;
}
while (!lru.empty() &&
(lru.size() >= max_entries ||
val.byte_cost > max_bytes - std::min(current_bytes, max_bytes))) {
const auto last = std::prev(lru.end());
current_bytes -= std::min(current_bytes, last->second.byte_cost);
map.erase(last->first);
lru.pop_back();
}
lru.emplace_front(key, std::move(val));
map.emplace(key, lru.begin());
current_bytes += lru.front().second.byte_cost;
}
};
Resolver::Resolver(std::size_t max_entries, std::size_t max_bytes)
: impl_(std::make_unique<Impl>(max_entries, max_bytes))
{
}
Resolver::~Resolver() = default;
std::size_t Resolver::invalidate_module(std::string_view module_id)
{
std::lock_guard lock{impl_->mutex};
std::size_t removed = 0;
for (auto it = impl_->lru.begin(); it != impl_->lru.end();) {
if (it->first.module_id == module_id) {
impl_->current_bytes -=
std::min(impl_->current_bytes, it->second.byte_cost);
impl_->map.erase(it->first);
it = impl_->lru.erase(it);
++removed;
} else {
++it;
}
}
return removed;
}
void Resolver::clear_cache()
{
std::lock_guard lock{impl_->mutex};
impl_->map.clear();
impl_->lru.clear();
impl_->current_bytes = 0;
}
std::size_t Resolver::cache_entries() const
{
std::lock_guard lock{impl_->mutex};
return impl_->map.size();
}
std::size_t Resolver::cache_bytes() const
{
std::lock_guard lock{impl_->mutex};
return impl_->current_bytes;
}
Void::Result::Result<std::string>
read_source_snippet_checked(const std::filesystem::path& file,
int line,
const ResolveOptions& options)
{
if (line <= 0 || options.context_lines < 0 ||
options.max_snippet_bytes == 0 || options.max_source_scan_bytes == 0 ||
options.max_line_bytes == 0) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
"Invalid line or snippet budget options"));
}
const auto& clock =
options.clock != nullptr
? *options.clock
: Void::Time::SystemMonotonicClock::instance();
if (options.stop.stop_requested()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::cancelled,
"Source snippet read cancelled"));
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::timeout,
"Source snippet read deadline expired"));
}
std::filesystem::path canonical_file;
Void::Result::Error path_err;
if (!is_under_allowed_roots(
file, options.allowed_source_roots, canonical_file, path_err)) {
return Void::Result::fail(std::move(path_err));
}
std::ifstream ifs{canonical_file};
if (!ifs.is_open()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::source_unreadable,
std::format("Cannot open canonical snippet file '{}'",
canonical_file.string())));
}
const std::int64_t target = line;
const std::int64_t ctx = options.context_lines;
const std::int64_t start = std::max<std::int64_t>(1, target - ctx);
const std::int64_t end = target + ctx;
std::string out;
std::string current_line;
std::int64_t line_num = 1;
std::size_t scanned_bytes = 0;
while (std::getline(ifs, current_line)) {
if (options.stop.stop_requested()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::cancelled,
"Source snippet read cancelled"));
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::timeout,
"Source snippet read deadline expired"));
}
scanned_bytes += current_line.size() + 1;
if (scanned_bytes > options.max_source_scan_bytes) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::scan_limit_exceeded,
"Source file scan byte budget exceeded"));
}
if (line_num >= start && line_num <= end) {
std::string_view clipped{current_line};
bool line_clipped = false;
if (clipped.size() > options.max_line_bytes) {
clipped = clipped.substr(0, options.max_line_bytes);
line_clipped = true;
}
const char* marker = (line_num == target) ? " >>> " : " ";
std::string formatted = std::format(
"{:>4}{}{}{}\n",
line_num,
marker,
clipped,
line_clipped ? "..." : "");
if (out.size() + formatted.size() > options.max_snippet_bytes) {
const std::size_t rem =
options.max_snippet_bytes -
std::min(out.size(), options.max_snippet_bytes);
out.append(formatted.data(), rem);
break;
}
out += formatted;
}
if (line_num >= end) {
break;
}
++line_num;
}
return out;
}
Void::Result::Result<ResolvedTrace>
Resolver::resolve(const RawTrace& raw, const ResolveOptions& options)
{
if (options.max_bytes == 0) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
"ResolveOptions::max_bytes must be positive"));
}
const auto& clock =
options.clock != nullptr
? *options.clock
: Void::Time::SystemMonotonicClock::instance();
ResolvedTrace trace;
trace.truncated = raw.truncated;
trace.frames.reserve(raw.frames.size());
for (const auto& rf : raw.frames) {
ResolvedFrame out_frame;
out_frame.raw = rf;
if (options.stop.stop_requested()) {
trace.incomplete = true;
out_frame.status = FrameResolveStatus::cancelled;
trace.frames.push_back(std::move(out_frame));
continue;
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
trace.incomplete = true;
out_frame.status = FrameResolveStatus::timed_out;
trace.frames.push_back(std::move(out_frame));
continue;
}
if (!options.resolve_symbols) {
out_frame.status = FrameResolveStatus::unresolved;
trace.frames.push_back(std::move(out_frame));
continue;
}
const CacheKey key{rf.module_id, rf.module_offset};
std::optional<CacheValue> cached = impl_->find_and_touch(key);
if (!cached.has_value() && rf.address != 0) {
CacheValue resolved;
try {
boost::stacktrace::frame f{
reinterpret_cast<const void*>(rf.address)};
const std::string mangled = f.name();
if (!mangled.empty()) {
resolved.function_name =
boost::core::demangle(mangled.c_str());
}
resolved.raw_source_file = f.source_file();
resolved.source_line =
static_cast<int>(f.source_line());
if (!resolved.function_name.empty()) {
resolved.status =
(!resolved.raw_source_file.empty() &&
resolved.source_line > 0)
? FrameResolveStatus::resolved
: FrameResolveStatus::symbols_only;
} else {
resolved.status = FrameResolveStatus::unresolved;
}
} catch (...) {
resolved.status = FrameResolveStatus::unresolved;
}
impl_->insert(key, resolved);
cached = std::move(resolved);
}
if (cached.has_value()) {
out_frame.function_name = cached->function_name;
out_frame.source_line = cached->source_line;
out_frame.status = cached->status;
out_frame.source_file = redact_source_path(
cached->raw_source_file, options.redact_prefixes);
if (options.source_snippets && !cached->raw_source_file.empty() &&
cached->source_line > 0) {
auto snip = read_source_snippet_checked(
cached->raw_source_file, cached->source_line, options);
if (snip) {
out_frame.source_snippet = std::move(*snip);
} else {
out_frame.diagnostic = std::move(snip).error();
}
}
}
const std::size_t frame_bytes =
96 + out_frame.function_name.size() + out_frame.source_file.size() +
out_frame.source_snippet.size();
if (trace.rendered_bytes + frame_bytes > options.max_bytes) {
out_frame.source_snippet.clear();
trace.truncated = true;
}
trace.rendered_bytes +=
96 + out_frame.function_name.size() + out_frame.source_file.size() +
out_frame.source_snippet.size();
trace.frames.push_back(std::move(out_frame));
}
return trace;
}
Void::Result::Result<ResolvedTrace>
resolve(const RawTrace& raw, const ResolveOptions& options)
{
Resolver transient{0, 0};
return transient.resolve(raw, options);
}
std::string format_resolved_trace(
const ResolvedTrace& trace, std::size_t max_bytes)
{
if (trace.frames.empty()) {
return " <no stacktrace available>\n";
}
std::string out;
for (std::size_t i = 0; i < trace.frames.size(); ++i) {
const auto& fr = trace.frames[i];
std::string line = std::format(
" #{:02} 0x{:x} {}\n",
i,
fr.raw.address,
fr.function_name.empty() ? std::string{"<unknown>"}
: fr.function_name);
if (!fr.source_file.empty() && fr.source_line > 0) {
line += std::format(
" at {}:{}\n", fr.source_file, fr.source_line);
}
if (!fr.source_snippet.empty()) {
line += fr.source_snippet;
}
if (out.size() + line.size() > max_bytes) {
constexpr std::string_view kTrunc = " ... [truncated]\n";
if (out.size() + kTrunc.size() <= max_bytes) {
out += kTrunc;
}
break;
}
out += line;
}
return out;
}
bool write_fatal_signal_marker(int fd, int sig) noexcept
{
#ifdef _WIN32
(void)fd;
(void)sig;
return false;
#else
if (fd < 0) {
return false;
}
char buf[64]{};
std::size_t pos = 0;
constexpr char kPrefix[] = "VOID_FATAL_SIGNAL sig=";
for (std::size_t i = 0; i < sizeof(kPrefix) - 1; ++i) {
buf[pos++] = kPrefix[i];
}
unsigned int u = 0;
if (sig < 0) {
buf[pos++] = '-';
u = static_cast<unsigned int>(-(sig + 1)) + 1U;
} else {
u = static_cast<unsigned int>(sig);
}
char rev[16]{};
std::size_t rpos = 0;
do {
rev[rpos++] = static_cast<char>('0' + (u % 10U));
u /= 10U;
} while (u > 0U && rpos < sizeof(rev));
while (rpos > 0U) {
buf[pos++] = rev[--rpos];
}
buf[pos++] = '\n';
std::size_t written = 0;
while (written < pos) {
const auto n = ::write(fd, buf + written, pos - written);
if (n > 0) {
written += static_cast<std::size_t>(n);
} else if (n < 0 && errno == EINTR) {
continue;
} else {
return false;
}
}
return true;
#endif
}
// ── Legacy compatibility API ─────────────────────────────────────────────────
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames,
unsigned max_frames)
{
std::vector<StackFrame> result;
try {
boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames);
for (auto it = bt.begin(); it != bt.end(); ++it) {
StackFrame frame;
std::string name = it->name();
if (!name.empty()) {
frame.function_name = boost::core::demangle(name.c_str());
}
frame.source_file = it->source_file();
frame.source_line = it->source_line();
if (!frame.source_file.empty() && frame.source_line > 0) {
frame.source_snippet =
read_source_snippet(frame.source_file,
frame.source_line, 2)
.value_or(std::string{});
}
result.push_back(std::move(frame));
}
} catch (...) {
}
Void::Log::debug("Stacktrace", "captured {} frames", result.size());
return result;
}
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file, int line, int context_lines)
{
std::ifstream ifs{file};
if (!ifs.is_open()) {
Void::Log::warn(
"Stacktrace", "read_source_snippet: cannot open '{}'", file);
return Void::Result::fail(
std::format("read_source_snippet: cannot open '{}'", file));
}
std::ostringstream result;
std::string current_line;
int line_num = 1;
const std::int64_t start = std::max<std::int64_t>(
1, static_cast<std::int64_t>(line) - context_lines);
const std::int64_t end =
static_cast<std::int64_t>(line) + context_lines;
while (std::getline(ifs, current_line)) {
if (line_num >= start && line_num <= end) {
std::string prefix = (line_num == line) ? " >>> " : " ";
result << std::format("{:>4}{}{}\n", line_num, prefix,
current_line);
}
if (line_num > end) {
break;
}
++line_num;
}
return Void::Result::ok(result.str());
}
std::string format_stacktrace(const std::vector<StackFrame>& frames)
{
if (frames.empty()) {
return " <no stacktrace available>\n";
}
std::ostringstream oss;
for (std::size_t i = 0; i < frames.size(); ++i) {
const auto& frame = frames[i];
oss << std::format(" #{:02} ", i);
if (!frame.function_name.empty()) {
oss << (Color::g_color_enabled
? Color::apply(Color::bold_cyan, frame.function_name)
: frame.function_name);
} else {
oss << "<unknown>";
}
if (!frame.source_file.empty() && frame.source_line > 0) {
std::filesystem::path p{frame.source_file};
oss << "\n at "
<< (Color::g_color_enabled
? Color::apply(Color::dim, p.filename().string())
: p.filename().string())
<< ":" << frame.source_line;
}
oss << "\n";
if (!frame.source_snippet.empty() && i < 5) {
oss << " "
<< (Color::g_color_enabled
? Color::apply(Color::dim, frame.source_snippet)
: frame.source_snippet);
}
}
return oss.str();
}
void print_stacktrace(std::ostream& os, const std::vector<StackFrame>& frames)
{
os << format_stacktrace(frames);
}
} // namespace Void::Stacktrace
+1 -1
View File
@@ -5,7 +5,7 @@ else()
endif()
void_add_module(Stacktrace
INTERNAL_DEPS Functional LogState
INTERNAL_DEPS Functional Time LogState
EXTERNAL_DEPS ${_void_stacktrace_target}
DEPS_UNIX dl
OPTIONS_UNIX -g -fno-omit-frame-pointer
+22 -11
View File
@@ -7,20 +7,31 @@ if(NOT TARGET Void::Testing)
endif()
get_property(ACTIVE_MODULES GLOBAL PROPERTY VOID_MODULES)
get_property(ACTIVE_HEADERS GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS)
function(_void_test_requires_satisfied src_file active_modules out_var)
function(_void_test_requires_satisfied src_file active_modules active_headers out_var)
file(READ "${src_file}" _src_content)
string(REGEX MATCHALL "#[ \t]*include[ \t]*[<\"](Void/[^/\">]+)/[^>\"]+[>\"]"
string(REGEX MATCHALL "#[ \t]*include[ \t]*[<\"](Void/[^/\">]+/[^>\"]+)[>\"]"
_matches "${_src_content}")
set(_ok TRUE)
foreach(_m IN LISTS _matches)
if(_m MATCHES "Void/([^/\">]+)/")
set(_req "${CMAKE_MATCH_1}")
if(NOT _req STREQUAL "Detail" AND NOT _req IN_LIST active_modules)
set(_ok FALSE)
message(STATUS
"[VoidTests] Skipping ${src_file} (requires unselected module '${_req}')")
break()
if(_m MATCHES "(Void/([^/\">]+)/[^>\"]+)")
set(_hdr "${CMAKE_MATCH_1}")
set(_req "${CMAKE_MATCH_2}")
if(NOT _req STREQUAL "Detail")
if(EXISTS "${CMAKE_SOURCE_DIR}/include/${_hdr}")
if(NOT _hdr IN_LIST active_headers)
set(_ok FALSE)
message(STATUS
"[VoidTests] Skipping ${src_file} (requires unselected header '${_hdr}')")
break()
endif()
elseif(NOT _req IN_LIST active_modules)
set(_ok FALSE)
message(STATUS
"[VoidTests] Skipping ${src_file} (requires unselected module '${_req}')")
break()
endif()
endif()
endif()
endforeach()
@@ -49,7 +60,7 @@ foreach(mod ${ACTIVE_MODULES})
file(GLOB _test_files CONFIGURE_DEPENDS "${_mod_dir}/*.cpp")
foreach(_src ${_test_files})
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" _deps_ok)
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" "${ACTIVE_HEADERS}" _deps_ok)
if(NOT _deps_ok)
continue()
endif()
@@ -76,7 +87,7 @@ endforeach()
file(GLOB_RECURSE _internal_sources CONFIGURE_DEPENDS "internal/*.cpp")
foreach(_src ${_internal_sources})
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" _deps_ok)
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" "${ACTIVE_HEADERS}" _deps_ok)
if(NOT _deps_ok)
continue()
endif()
+20
View File
@@ -116,6 +116,26 @@ if(_has_runtime)
run_consumer(RuntimeOnly "${install_prefix}" "RuntimeOnly" ${_no_external_deps})
endif()
has_modules(_has_obs_hooks ObservabilityHooks)
if(_has_obs_hooks)
run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps})
endif()
has_modules(_has_obs Observability ObservabilityHooks Memory Time Functional Core)
if(_has_obs)
run_consumer(ObservabilityOnly "${install_prefix}" "ObservabilityOnly" ${_no_external_deps})
endif()
has_modules(_has_resilience Resilience ObservabilityHooks Time Functional Core)
if(_has_resilience)
run_consumer(ResilienceOnly "${install_prefix}" "ResilienceOnly" ${_no_external_deps})
endif()
has_modules(_has_log Log Async Data Time Memory Functional Core LogState)
if(_has_log)
run_consumer(LogOnly "${install_prefix}" "LogOnly" ${_no_external_deps})
endif()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
+10
View File
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidLogOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Log)
add_executable(void_log_only_consumer main.cpp)
target_link_libraries(void_log_only_consumer PRIVATE Void::Log)
enable_testing()
add_test(NAME VoidLogOnlyConsumer COMMAND void_log_only_consumer)
+26
View File
@@ -0,0 +1,26 @@
#include <Void/Log/Log.hpp>
#include <Void/Log/LoggingAdapter.hpp>
#include <Void/Log/Sinks.hpp>
#include <atomic>
int main()
{
std::atomic<int> seen{0};
auto sink = std::make_shared<Void::Logging::CallbackLogger>(
[&](const Void::Logging::Entry&) {
seen.fetch_add(1, std::memory_order_relaxed);
},
Void::Logging::LoggerOptions{
.mode = Void::Logging::Mode::Immediate,
.policy = Void::Logging::OverflowPolicy::DropNewest});
const auto reg = Void::Log::register_sink(Void::Log::make_sink(sink), sink);
Void::Log::info("LogOnly", "hello consumer");
const auto dr = Void::Log::detach_and_drain(reg);
const auto rep = sink->close({});
return (dr == Void::Log::DrainResult::drained && rep.has_value() &&
seen.load() == 1)
? 0
: 1;
}
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidObservabilityHooksOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS ObservabilityHooks)
add_executable(void_observability_hooks_only_consumer main.cpp)
target_link_libraries(void_observability_hooks_only_consumer PRIVATE Void::ObservabilityHooks)
enable_testing()
add_test(NAME VoidObservabilityHooksOnlyConsumer COMMAND void_observability_hooks_only_consumer)
@@ -0,0 +1,11 @@
#include <Void/Observability/Hooks.hpp>
int main()
{
Void::Observability::HookSlot slot;
Void::Observability::kNullObservationHooks.emit_metric(
Void::Observability::MetricPoint{.name = "probe", .integer_delta = 1});
slot.invoke_metric(
Void::Observability::MetricPoint{.name = "probe", .integer_delta = 1});
return slot.active() ? 1 : 0;
}
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidObservabilityOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Observability)
add_executable(void_observability_only_consumer main.cpp)
target_link_libraries(void_observability_only_consumer PRIVATE Void::Observability)
enable_testing()
add_test(NAME VoidObservabilityOnlyConsumer COMMAND void_observability_only_consumer)
+29
View File
@@ -0,0 +1,29 @@
#include <Void/Observability/Observability.hpp>
#include <memory>
int main()
{
auto reg = Void::Observability::MetricRegistry::create();
if (!reg) {
return 1;
}
auto ctr = reg->register_instrument(Void::Observability::InstrumentSpec{
.name = "consumer_ops",
.unit = "1",
.kind = Void::Observability::MetricKind::counter});
if (!ctr || !reg->add_counter(*ctr, 1)) {
return 2;
}
auto exp = std::make_shared<Void::Observability::TextSnapshotExporter>();
auto tr = Void::Observability::Tracer::create({}, exp);
if (!tr) {
return 3;
}
auto sp = tr->start_span(
Void::Observability::ContextSnapshot{},
Void::Observability::SpanSpec{.name = "root"});
sp.end();
const auto rep = tr->close();
return rep.failed_spans == 0 ? 0 : 4;
}
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidResilienceOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Resilience)
add_executable(void_resilience_only_consumer main.cpp)
target_link_libraries(void_resilience_only_consumer PRIVATE Void::Resilience)
enable_testing()
add_test(NAME VoidResilienceOnlyConsumer COMMAND void_resilience_only_consumer)
+22
View File
@@ -0,0 +1,22 @@
#include <Void/Resilience/Resilience.hpp>
int main()
{
auto b = Void::Resilience::TokenBucket::create(
Void::Resilience::BucketConfig{4.0, 1.0});
auto br = Void::Resilience::Breaker::create(Void::Resilience::BreakerConfig{});
auto mon = Void::Resilience::ResourceMonitor::create(
Void::Resilience::MonitorConfig{16, 0.9, 0.7});
if (!b || !br || !mon) {
return 1;
}
auto bp = br->acquire();
auto rp = mon->try_acquire_checked(4);
auto adm = b->try_acquire_checked(1.0);
if (!bp || !rp || !adm || !adm->allowed) {
return 2;
}
bp->finish(Void::Resilience::Outcome::success);
rp->release();
return 0;
}
+372
View File
@@ -0,0 +1,372 @@
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/Logger.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <fstream>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace Void::Logging;
using namespace std::chrono_literals;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
struct FacadeGuard {
~FacadeGuard()
{
(void)Void::Log::detach_and_drain(0);
Void::Log::set_emergency_handler(nullptr);
Void::Log::set_min_level(Void::Log::Level::Trace);
}
};
std::atomic<int> g_emergency_calls{0};
void record_emergency(std::string_view) noexcept
{
g_emergency_calls.fetch_add(1, std::memory_order_relaxed);
}
} // namespace
Void::Testing::Test log_facade_reentrant_replace_drain_and_suppression()
{
FacadeGuard guard;
g_emergency_calls.store(0, std::memory_order_relaxed);
Void::Log::set_emergency_handler(&record_emergency);
const auto before_drops = Void::Log::reentrant_dropped();
std::atomic<bool> destroyed{false};
struct OwnerFlag {
std::atomic<bool>* flag;
~OwnerFlag() { flag->store(true, std::memory_order_release); }
};
auto owner = std::make_shared<OwnerFlag>(&destroyed);
std::mutex mu;
std::condition_variable cv;
bool in_cb = false;
bool release_cb = false;
std::atomic<bool> self_drain_blocked{false};
std::atomic<int> secondary_calls{0};
const auto id = Void::Log::register_sink(
[&](Void::Log::Level,
std::string_view,
std::string_view,
const std::source_location&) {
// Reentrant log into same registration is suppressed & routed to emergency hook.
Void::Log::info("LogHardening", "recursive call");
// Synchronous self-drain detects active registration -> would_deadlock.
if (Void::Log::detach_and_drain(0) == Void::Log::DrainResult::would_deadlock) {
self_drain_blocked.store(true, std::memory_order_release);
}
// Reentrant sink replacement must NOT deadlock; old registration stays
// alive via Hook/ActiveRegistrationGuard until callback exits.
Void::Log::set_sink([&](auto, auto, auto, auto) {
secondary_calls.fetch_add(1, std::memory_order_relaxed);
});
{
std::unique_lock lock{mu};
in_cb = true;
cv.notify_all();
cv.wait(lock, [&] { return release_cb; });
}
},
owner);
owner.reset();
std::thread emitter{[&] {
Void::Log::info("LogHardening", "outer event");
}};
{
std::unique_lock lock{mu};
cv.wait(lock, [&] { return in_cb; });
}
// Even after callback called set_sink(secondary), original owner must stay alive
// until detach_and_drain(id) finishes waiting on active_calls == 0.
std::atomic<Void::Log::DrainResult> dr{Void::Log::DrainResult::not_found};
std::atomic<bool> drain_done{false};
std::thread drainer{[&] {
dr.store(Void::Log::detach_and_drain(id), std::memory_order_release);
drain_done.store(true, std::memory_order_release);
}};
std::this_thread::sleep_for(10ms);
expect(!drain_done.load(std::memory_order_acquire));
expect(!destroyed.load(std::memory_order_acquire));
{
std::lock_guard lock{mu};
release_cb = true;
}
cv.notify_all();
emitter.join();
drainer.join();
expect(self_drain_blocked.load());
expect(dr.load() == Void::Log::DrainResult::drained);
expect(destroyed.load(std::memory_order_acquire));
expect(Void::Log::reentrant_dropped() > before_drops);
expect(g_emergency_calls.load() >= 1);
Void::Log::info("LogHardening", "after replace");
expect_eq(secondary_calls.load(), 1);
}
Void::Testing::Test log_bounded_permits_drop_oldest_and_tickets()
{
std::mutex mu;
std::condition_variable cv;
bool stalled = true;
std::atomic<bool> in_sink{false};
std::vector<std::string> delivered;
LoggerOptions opt;
opt.mode = Mode::Async;
opt.policy = OverflowPolicy::DropOldest;
opt.limits.entries = 3;
opt.limits.batch_entries = 1;
opt.limits.owned_bytes = 64 * 1024;
opt.suppress_reentrancy = true;
auto sink = std::make_shared<CallbackLogger>(
[&](const Entry& e) {
in_sink.store(true, std::memory_order_release);
{
std::unique_lock lock{mu};
cv.wait(lock, [&] { return !stalled; });
}
delivered.push_back(e.message);
},
opt);
// 1st entry starts executing in worker immediately and occupies in-flight permit (1/3).
auto r1 = sink->try_submit(Entry{.level = Level::Info, .message = "first"});
require(r1.has_value() && r1->state == SubmitState::Accepted);
while (!in_sink.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(1ms);
}
// Queue 2 more -> now queued(2) + in_flight(1) == 3 (at capacity!).
auto r2 = sink->try_submit(Entry{.level = Level::Info, .message = "second"});
auto r3 = sink->try_submit(Entry{.level = Level::Info, .message = "third"});
auto r4 = sink->try_submit(Entry{.level = Level::Info, .message = "fourth"});
require(r2.has_value() && r3.has_value() && r4.has_value());
expect(r4->state == SubmitState::Accepted);
// Total active (queued + in_flight) never exceeds capacity 3; "second" was evicted.
const auto st_stall = sink->stats();
expect(st_stall.queued_entries + st_stall.in_flight_entries <= 3);
expect_eq(st_stall.dropped, std::uint64_t{1});
// Release stalled worker and verify contiguous watermark & report include evicted loss.
{
std::lock_guard lock{mu};
stalled = false;
}
cv.notify_all();
auto rep = sink->flush_through(*r4->ticket, {});
require(rep.has_value());
expect_eq(rep->delivered, std::uint64_t{3});
expect_eq(rep->dropped, std::uint64_t{1});
expect_eq(rep->watermark, *r4->ticket);
expect_eq(delivered.size(), std::size_t{3});
expect_eq(delivered[0], std::string{"first"});
expect_eq(delivered[1], std::string{"third"});
expect_eq(delivered[2], std::string{"fourth"});
// Non-file sink must report unsupported_capability for SyncFiles durability.
auto sync_res = sink->flush_through(0, FlushOptions{FlushDurability::SyncFiles, {}});
expect(!sync_res.has_value());
expect_eq(sync_res.error().code().value,
static_cast<std::int32_t>(LogErrorCode::unsupported_capability));
auto close_rep = sink->close({});
require(close_rep.has_value());
auto after_close = sink->try_submit(Entry{.level = Level::Info, .message = "late"});
require(after_close.has_value());
expect(after_close->state == SubmitState::Closed);
}
Void::Testing::Test log_quarantine_reentrancy_and_block_cancel()
{
int attempts = 0;
LoggerOptions qopt;
qopt.mode = Mode::Immediate;
qopt.failure_policy = FailurePolicy::Quarantine;
qopt.suppress_reentrancy = true;
std::shared_ptr<CallbackLogger> qsink;
bool trigger_reenter = true;
qsink = std::make_shared<CallbackLogger>(
[&](const Entry&) {
++attempts;
if (trigger_reenter) {
trigger_reenter = false;
auto sub = qsink->try_submit(Entry{.level = Level::Info, .message = "inner"});
expect(sub.has_value() && sub->state == SubmitState::Dropped);
// Synchronous self-flush must return would_deadlock.
auto sf = qsink->flush_through(0, {});
expect(!sf.has_value());
expect_eq(sf.error().code().value,
static_cast<std::int32_t>(LogErrorCode::would_deadlock));
}
throw std::runtime_error{"disk fault"};
},
qopt);
auto r = qsink->try_submit(Entry{.level = Level::Error, .message = "fail"});
require(r.has_value());
expect(qsink->is_quarantined());
expect(qsink->last_error_summary().find("disk fault") != std::string::npos);
expect_eq(qsink->stats().failed, std::uint64_t{1});
expect_eq(qsink->stats().reentrant_dropped, std::uint64_t{1});
// Subsequent submissions fail with quarantined until operator resets quarantine.
auto blocked = qsink->try_submit(Entry{.level = Level::Error, .message = "next"});
expect(!blocked.has_value());
expect_eq(blocked.error().code().value,
static_cast<std::int32_t>(LogErrorCode::quarantined));
qsink->reset_quarantine();
expect(!qsink->is_quarantined());
// Cancellable Block submit stops cleanly when stalled.
std::mutex mu;
std::condition_variable cv;
bool hold = true;
std::atomic<bool> entered{false};
LoggerOptions bopt;
bopt.mode = Mode::Async;
bopt.policy = OverflowPolicy::Block;
bopt.limits.entries = 1;
bopt.limits.batch_entries = 1;
CallbackLogger blocker{
[&](const Entry&) {
entered.store(true, std::memory_order_release);
std::unique_lock lock{mu};
cv.wait(lock, [&] { return !hold; });
},
bopt};
expect(blocker.try_submit(Entry{.level = Level::Info, .message = "fill"})->state ==
SubmitState::Accepted);
while (!entered.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(1ms);
}
std::stop_source stop_src;
std::thread stopper{[&] {
std::this_thread::sleep_for(10ms);
stop_src.request_stop();
}};
auto cancelled = blocker.try_submit(
Entry{.level = Level::Info, .message = "wait"},
Void::Async::OperationOptions{.stop = stop_src.get_token()});
stopper.join();
expect(!cancelled.has_value());
expect_eq(cancelled.error().code().value,
static_cast<std::int32_t>(LogErrorCode::cancelled));
{
std::lock_guard lock{mu};
hold = false;
}
cv.notify_all();
expect(blocker.close({}).has_value());
}
Void::Testing::Test log_formatters_multilogger_and_file_sync_reopen()
{
// 1. Logfmt escaping + redaction + format_bounded.
Entry e;
e.level = Level::Warning;
e.message = "line1\nline2\t\"q\"";
e.truncated = true;
e.fields = {{"secret", "s3cr3t"}, {"note", "a\nb\rc"}};
LogfmtFormatter logfmt;
logfmt.set_field_filter(FieldFilter{.redact = {"secret"}});
const std::string line = logfmt.format(e);
expect(line.find("truncated=true") != std::string::npos);
expect(line.find("secret=\"[REDACTED]\"") != std::string::npos);
expect(line.find("s3cr3t") == std::string::npos);
expect(line.find("\\n") != std::string::npos);
expect(line.find("\\r") != std::string::npos);
expect(line.find("\\t") != std::string::npos);
const auto too_big = format_bounded(logfmt, e, 16, false);
expect(!too_big.has_value());
const auto trunc_ok = format_bounded(logfmt, e, 24, true);
require(trunc_ok.has_value());
expect_eq(trunc_ok->size(), std::size_t{24});
expect(trunc_ok->ends_with("...[truncated]"));
// 2. MultiLogger fanout cap (8) + cycle rejection.
auto root = std::make_shared<MultiLogger>();
auto child = std::make_shared<MultiLogger>();
expect(root->try_add(child).has_value());
auto self_cycle = child->try_add(root);
expect(!self_cycle.has_value());
expect_eq(self_cycle.error().code().value,
static_cast<std::int32_t>(LogErrorCode::cycle_detected));
for (int i = 0; i < 7; ++i) {
expect(root->try_add(std::make_shared<NullLogger>()).has_value());
}
auto ninth = root->try_add(std::make_shared<NullLogger>());
expect(!ninth.has_value());
expect_eq(ninth.error().code().value,
static_cast<std::int32_t>(LogErrorCode::queue_full));
// 3. RotatingFileOptions::roadmap_defaults rejects missing dir + FileLogger sync/reopen.
const auto base = std::filesystem::temp_directory_path() / "void_log_hardening_test";
std::filesystem::remove_all(base);
auto missing_rot = RotatingFileLogger::open(
base / "no_such_dir" / "app.log",
RotatingFileOptions::roadmap_defaults());
expect(!missing_rot.has_value());
std::filesystem::create_directories(base);
const auto file_path = base / "durable.log";
{
auto fl_res = FileLogger::open(file_path, LoggerOptions{.mode = Mode::Immediate});
require(fl_res.has_value());
auto& fl = *fl_res;
auto ticket = fl->try_submit(Entry{.level = Level::Info, .message = "before-reopen"});
require(ticket.has_value() && ticket->ticket.has_value());
auto synced = fl->flush_through(*ticket->ticket, FlushOptions{FlushDurability::SyncFiles, {}});
expect(synced.has_value());
expect(fl->reopen().has_value());
expect(fl->try_submit(Entry{.level = Level::Info, .message = "after-reopen"}).has_value());
expect(fl->close({}).has_value());
}
std::ifstream ifs{file_path};
std::string content{(std::istreambuf_iterator<char>(ifs)), {}};
expect(content.find("before-reopen") != std::string::npos);
expect(content.find("after-reopen") != std::string::npos);
std::filesystem::remove_all(base);
}
@@ -15,11 +15,10 @@ using Void::Configuration::Config;
Void::Testing::Test from_config_defaults_to_console()
{
Config cfg; // empty: console sink, trace level, async
Config cfg;
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
Void::Testing::expect((*logger)->mode() ==
Void::Logging::Mode::Async);
Void::Testing::expect((*logger)->mode() == Void::Logging::Mode::Async);
}
Void::Testing::Test from_config_builds_multi_sink_tree()
@@ -33,17 +32,14 @@ Void::Testing::Test from_config_builds_multi_sink_tree()
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
Void::Testing::expect((*logger)->mode() ==
Void::Logging::Mode::Immediate);
Void::Testing::expect((*logger)->level() ==
Void::Logging::Level::Warning);
Void::Testing::expect((*logger)->mode() == Void::Logging::Mode::Immediate);
Void::Testing::expect((*logger)->level() == Void::Logging::Level::Warning);
(*logger)->warning("to both sinks");
(*logger)->flush();
std::ifstream f(tmp.path() / "a.log");
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("to both sinks") !=
std::string::npos);
Void::Testing::expect(content.find("to both sinks") != std::string::npos);
}
Void::Testing::Test from_config_split_and_history_sinks()
@@ -62,13 +58,11 @@ Void::Testing::Test from_config_split_and_history_sinks()
std::ifstream err(tmp.path() / "split" / "error.log");
std::string err_content((std::istreambuf_iterator<char>(err)), {});
Void::Testing::expect(err_content.find("split me") !=
std::string::npos);
Void::Testing::expect(err_content.find("split me") != std::string::npos);
std::ifstream hist(tmp.path() / "history.jsonl");
std::string hist_content((std::istreambuf_iterator<char>(hist)), {});
Void::Testing::expect(hist_content.find("split me") !=
std::string::npos);
Void::Testing::expect(hist_content.find("split me") != std::string::npos);
}
Void::Testing::Test from_config_json_format_applies()
@@ -78,11 +72,15 @@ Void::Testing::Test from_config_json_format_applies()
cfg.set("log.sinks", "file");
cfg.set("log.file.path", (tmp.path() / "j.log").string());
cfg.set("log.format", "json");
cfg.set("log.fields.redact", "token");
cfg.set("log.async", "false");
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
(*logger)->info("structured");
{
Void::Logging::FieldScope fs{"token", "top-secret"};
(*logger)->info("structured");
}
(*logger)->flush();
std::ifstream f(tmp.path() / "j.log");
@@ -90,6 +88,8 @@ Void::Testing::Test from_config_json_format_applies()
std::getline(f, line);
Void::Testing::expect(line.find("\"message\":\"structured\"") !=
std::string::npos);
Void::Testing::expect(line.find("top-secret") == std::string::npos);
Void::Testing::expect(line.find("[REDACTED]") != std::string::npos);
}
Void::Testing::Test from_config_missing_file_path_is_error()
@@ -106,6 +106,38 @@ Void::Testing::Test from_config_unknown_sink_is_error()
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
Void::Testing::Test from_config_rejects_invalid_values()
{
{
Config cfg;
cfg.set("log.level", "loud");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Config cfg;
cfg.set("log.format", "xml");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Config cfg;
cfg.set("log.overflow", "drop_middle");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Config cfg;
cfg.set("log.capacity", "0");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Void::FileSystem::TempDir tmp{"void_fromcfg_bad"};
Config cfg;
cfg.set("log.sinks", "rotating");
cfg.set("log.rotating.path", (tmp.path() / "r.log").string());
cfg.set("log.rotating.max_kb", "0");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
}
Void::Testing::Test apply_facade_config_sets_levels()
{
struct Reset {
@@ -122,9 +154,7 @@ Void::Testing::Test apply_facade_config_sets_levels()
Void::Logging::apply_facade_config(cfg);
Void::Log::set_sink([](auto, auto, auto, auto) {});
Void::Testing::expect(
!Void::Log::enabled(Void::Log::Level::Info, "Other"));
Void::Testing::expect(
Void::Log::enabled(Void::Log::Level::Trace, "Fsm"));
Void::Testing::expect(!Void::Log::enabled(Void::Log::Level::Info, "Other"));
Void::Testing::expect(Void::Log::enabled(Void::Log::Level::Trace, "Fsm"));
Void::Log::set_sink({});
}
@@ -0,0 +1,476 @@
#include <Void/Core/Hash.hpp>
#include <Void/Observability/Observability.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <cstdlib>
#include <limits>
#include <mutex>
#include <new>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace Void::Observability;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
[[nodiscard]] bool hex_matches_bucket_zero(const TraceId& tid,
std::uint64_t denom) noexcept
{
std::uint64_t h = Void::Hash::fnv1a64(
std::span<const std::byte>{tid.bytes.data(), tid.bytes.size()});
return (h % denom) == 0;
}
[[nodiscard]] TraceId find_seeded_trace_id(std::uint64_t denom, bool want_sampled)
{
for (std::uint64_t s = 1; s < 50000; ++s) {
auto tid = TraceId::generate_seeded(s);
if (hex_matches_bucket_zero(tid, denom) == want_sampled) {
return tid;
}
}
return TraceId::generate_seeded(1);
}
struct DetachState {
bool suspended{false};
bool resume_saw_empty_tls{false};
bool resumed_ok{false};
};
struct DetachAwaiter {
bool ready{false};
DetachState* state{nullptr};
[[nodiscard]] bool await_ready() const noexcept { return ready; }
void await_suspend(std::coroutine_handle<> h) noexcept
{
state->suspended = true;
state->resume_saw_empty_tls = ScopedContext::current().empty();
h.resume();
}
int await_resume() noexcept
{
state->resumed_ok = !ScopedContext::current().empty();
return 42;
}
};
struct OneShotCoro {
struct promise_type {
int result{0};
OneShotCoro get_return_object()
{
return OneShotCoro{
std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_never initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_value(int v) noexcept { result = v; }
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle;
~OneShotCoro()
{
if (handle) {
handle.destroy();
}
}
};
OneShotCoro run_context_awaitable(ContextSnapshot snap, DetachAwaiter& awaiter)
{
const int v = co_await with_context(std::move(snap), awaiter);
co_return v;
}
} // namespace
Void::Testing::Test observability_null_hooks_and_slot_lifecycle()
{
expect(!kNullObservationHooks.active());
const MetricPoint mp{
.name = "req",
.kind = MetricKind::counter,
.integer_delta = 1};
kNullObservationHooks.emit_metric(mp);
kNullObservationHooks.emit_diagnostic(
DiagnosticEvent{"obs", "ignored", false});
HookSlot slot;
expect(!slot.active());
slot.invoke_metric(mp);
auto owner = std::make_shared<std::atomic<bool>>(false);
struct LifetimeTracker {
std::shared_ptr<std::atomic<bool>> flag;
~LifetimeTracker() { flag->store(true, std::memory_order_release); }
};
auto tracker = std::make_shared<LifetimeTracker>(owner);
std::mutex mu;
std::condition_variable cv;
bool in_callback = false;
bool proceed = false;
std::atomic<bool> reentrant_drain_blocked{false};
const HookRegistrationId reg_id = slot.install_guarded(
[&](const MetricPoint&) {
// Reentrant emit is suppressed cleanly.
slot.invoke_metric(mp);
// Synchronous self-drain must fail with would_deadlock.
if (slot.detach_and_drain(0) == DrainStatus::would_deadlock) {
reentrant_drain_blocked.store(true, std::memory_order_release);
}
{
std::unique_lock lock{mu};
in_callback = true;
cv.notify_all();
cv.wait(lock, [&] { return proceed; });
}
},
{},
tracker);
tracker.reset();
expect(slot.active());
std::thread worker{[&] { slot.invoke_metric(mp); }};
{
std::unique_lock lock{mu};
cv.wait(lock, [&] { return in_callback; });
}
std::atomic<DrainStatus> drain_status{DrainStatus::not_found};
std::atomic<bool> drain_finished{false};
std::thread drainer{[&] {
drain_status.store(slot.detach_and_drain(reg_id),
std::memory_order_release);
drain_finished.store(true, std::memory_order_release);
}};
std::this_thread::sleep_for(std::chrono::milliseconds{10});
expect(!drain_finished.load(std::memory_order_acquire));
expect(!owner->load(std::memory_order_acquire));
{
std::lock_guard lock{mu};
proceed = true;
}
cv.notify_all();
worker.join();
drainer.join();
expect(reentrant_drain_blocked.load());
expect(drain_status.load() == DrainStatus::drained);
expect(owner->load(std::memory_order_acquire));
expect_eq(slot.reentrant_calls(), std::uint64_t{1});
// Throwing guarded hook quarantines after first exception.
int calls_before_quarantine = 0;
(void)slot.install_guarded([&](const MetricPoint&) {
++calls_before_quarantine;
throw std::runtime_error{"boom"};
});
slot.invoke_metric(mp);
slot.invoke_metric(mp);
expect_eq(calls_before_quarantine, 1);
expect(slot.is_quarantined());
expect_eq(slot.failed_calls(), std::uint64_t{1});
slot.reset_quarantine();
expect(!slot.is_quarantined());
slot.invoke_metric(mp);
expect_eq(calls_before_quarantine, 2);
}
Void::Testing::Test observability_context_traceparent_baggage_and_async()
{
const TraceId tid = TraceId::generate_seeded(123);
const SpanId sid = SpanId::generate_seeded(456);
const TraceContext tc{tid, sid, kTraceFlagSampled};
expect(tc.valid());
expect(tc.sampled());
const auto header = tc.to_traceparent();
const auto parsed = TraceContext::from_traceparent(header);
require(parsed.has_value());
expect(*parsed == tc);
// Reject malformed, wrong version, uppercase, and zero-ID traceparent inputs.
expect(!TraceContext::from_traceparent("short").has_value());
expect(!TraceContext::from_traceparent(
"00-00000000000000000000000000000000-0102030405060708-01").has_value());
expect(!TraceContext::from_traceparent(
"00-0102030405060708090a0b0c0d0e0f10-0000000000000000-01").has_value());
std::string upper = header;
upper[3] = 'A';
expect(!TraceContext::from_traceparent(upper).has_value());
std::string bad_ver = header;
bad_ver[0] = 'f';
bad_ver[1] = 'f';
expect(!TraceContext::from_traceparent(bad_ver).has_value());
ContextLimits slim_limits{};
slim_limits.max_baggage_items = 2;
slim_limits.max_baggage_bytes = 20;
const BaggageItem items[] = {{"env", "prod"}, {"tenant", "acme"}};
auto snap = ContextSnapshot::create(tc, items, slim_limits);
require(snap.has_value());
expect_eq(snap->find_baggage("tenant").value_or(""), std::string_view{"acme"});
auto over_item = snap->with_baggage("extra", "1");
expect(!over_item.has_value());
// Scope restore across thrown exception.
expect(ScopedContext::current().empty());
try {
ScopedContext outer{*snap};
expect(!ScopedContext::current().empty());
throw std::runtime_error{"unwind"};
} catch (...) {
}
expect(ScopedContext::current().empty());
// bind_context preserves snapshot on worker thread and restores afterwards.
std::optional<TraceContext> observed_on_worker;
auto task = bind_context(*snap, [&] {
observed_on_worker = ScopedContext::current().trace();
});
bool empty_after_worker = false;
std::thread t{[&] {
task();
empty_after_worker = ScopedContext::current().empty();
}};
t.join();
require(observed_on_worker.has_value());
expect(*observed_on_worker == tc);
expect(empty_after_worker);
// ContextAwaitable restores TLS during await_resume without holding it over suspend.
DetachState await_state;
DetachAwaiter awaiter{false, &await_state};
auto coro = run_context_awaitable(*snap, awaiter);
expect(await_state.suspended);
expect(await_state.resume_saw_empty_tls);
expect(await_state.resumed_ok);
expect_eq(coro.handle.promise().result, 42);
expect(ScopedContext::current().empty());
}
Void::Testing::Test observability_metrics_shards_overflow_and_epoch()
{
Void::Time::ManualClock clock;
MetricsLimits limits{};
limits.max_series_per_instrument = 2;
limits.max_total_series = 4;
std::uint64_t snapshot_total = 0;
{
auto reg_res = MetricRegistry::create(limits, clock);
require(reg_res.has_value());
auto reg = std::move(*reg_res);
auto ctr_res = reg.register_instrument(InstrumentSpec{
.name = "http_requests_total",
.unit = "1",
.kind = MetricKind::counter,
.label_keys = {"route"}});
require(ctr_res.has_value());
const auto ctr = *ctr_res;
// Schema mismatch conflict must fail.
auto conflict = reg.register_instrument(InstrumentSpec{
.name = "http_requests_total",
.unit = "1",
.kind = MetricKind::gauge,
.label_keys = {"route"}});
expect(!conflict.has_value());
auto lat_res = reg.register_instrument(InstrumentSpec{
.name = "request_duration_seconds",
.unit = "s",
.kind = MetricKind::histogram,
.label_keys = {"route"}});
require(lat_res.has_value());
auto g_res = reg.register_instrument(InstrumentSpec{
.name = "inflight",
.unit = "1",
.kind = MetricKind::gauge});
require(g_res.has_value());
// Reject NaN gauge and histogram.
expect(!reg.set_gauge(*g_res, std::numeric_limits<double>::quiet_NaN()).has_value());
expect(!reg.observe_histogram(*lat_res, std::numeric_limits<double>::infinity()).has_value());
// Hook integration.
HookSlot slot;
(void)slot.install(reg.make_hooks(), reg.keepalive());
const AttributeView r1[] = {{"route", "/a"}};
const AttributeView r2[] = {{"route", "/b"}};
const AttributeView r3[] = {{"route", "/c"}};
const AttributeView r4[] = {{"route", "/d"}};
// Exiting producer thread writes into its shard before terminating.
std::thread producer{[&] {
slot.invoke_metric(MetricPoint{
.name = "http_requests_total",
.kind = MetricKind::counter,
.integer_delta = 5,
.attributes = r1});
}};
producer.join();
expect(reg.add_counter(ctr, 3, r1).has_value());
expect(reg.add_counter(ctr, 7, r2).has_value());
// Series 3 and 4 overflow into __overflow__.
expect(reg.add_counter(ctr, 2, r3).has_value());
expect(reg.add_counter(ctr, 4, r4).has_value());
expect(reg.observe_histogram(*lat_res, 0.0005, r1).has_value());
expect(reg.observe_histogram(*lat_res, 25.0, r1).has_value());
expect(reg.set_gauge(*g_res, 9.5).has_value());
const auto snap = reg.snapshot();
expect_eq(snap.epoch, std::uint64_t{1});
expect_eq(snap.dropped_series, std::uint64_t{2});
expect_eq(snap.overflow_events, std::uint64_t{2});
const auto& ctr_snap = snap.instruments[0];
bool saw_overflow = false;
std::uint64_t r1_count = 0;
std::uint64_t overflow_count = 0;
for (const auto& s : ctr_snap.series) {
if (s.is_overflow) {
saw_overflow = true;
overflow_count = s.counter_value;
} else if (!s.labels.empty() && s.labels[0].second == "/a") {
r1_count = s.counter_value;
}
snapshot_total += s.counter_value;
}
expect(saw_overflow);
expect_eq(r1_count, std::uint64_t{8});
expect_eq(overflow_count, std::uint64_t{6});
expect_eq(snapshot_total, std::uint64_t{21});
const auto text = TextSnapshotExporter::render_metrics(snap);
expect(text.find("http_requests_total") != std::string::npos);
reg.reset_epoch();
const auto after_reset = reg.snapshot();
expect_eq(after_reset.epoch, std::uint64_t{2});
expect_eq(after_reset.dropped_series, std::uint64_t{0});
(void)slot.detach_and_drain(0);
}
}
Void::Testing::Test observability_tracer_sampling_budgets_and_exporter()
{
Void::Time::ManualClock mono_clock;
Void::Time::ManualCivilClock civil_clock;
auto exporter_calls = std::make_shared<std::atomic<int>>(0);
auto text_exp = std::make_shared<TextSnapshotExporter>(4096);
TracingLimits limits{};
limits.root_sample_denominator = 100;
limits.max_active_spans = 2;
limits.max_completed_spans = 3;
limits.max_export_retries = 2;
limits.export_retry_budget = std::chrono::seconds{5};
bool fail_first = true;
auto cb_exp = std::make_shared<CallbackSpanExporter>(
[&](std::span<const CompletedSpan> batch) -> Void::Result::Result<void> {
exporter_calls->fetch_add(1, std::memory_order_relaxed);
if (fail_first) {
fail_first = false;
return Void::Result::fail("transient export failure");
}
return text_exp->export_spans(batch);
});
auto tr_res = Tracer::create(limits, cb_exp, mono_clock, civil_clock);
require(tr_res.has_value());
auto tracer = std::move(*tr_res);
const ContextSnapshot empty_ctx{};
const TraceId unsampled_tid = find_seeded_trace_id(100, false);
const TraceId sampled_tid = find_seeded_trace_id(100, true);
{
auto unsampled = tracer.start_span(
empty_ctx,
SpanSpec{.name = "root-unsampled", .explicit_root_trace_id = unsampled_tid});
expect(!unsampled.is_recording());
expect(unsampled.context().trace().has_value());
expect(!unsampled.context().trace()->sampled());
}
auto root = tracer.start_span(
empty_ctx,
SpanSpec{.name = "root-sampled", .explicit_root_trace_id = sampled_tid});
expect(root.is_recording());
root.set_attribute("k", "v");
root.add_event("evt");
auto child = tracer.start_span(root.context(), SpanSpec{.name = "child-abandoned"});
expect(child.is_recording());
// Third active span exceeds max_active_spans (2) and returns inert span.
{
auto dropped = tracer.start_span(root.context(), SpanSpec{.name = "dropped-active"});
expect(!dropped.is_recording());
expect(dropped.context().trace().has_value());
}
root.end(SpanStatus::ok);
root.end(SpanStatus::error); // duplicate end counted without overwriting status
{
auto doomed = tracer.start_span(empty_ctx, SpanSpec{.name = "abandoned", .explicit_root_trace_id = sampled_tid});
expect(doomed.is_recording());
} // destructor abandons it
const auto st_before_flush = tracer.stats();
expect_eq(st_before_flush.duplicate_ends, std::uint64_t{1});
expect_eq(st_before_flush.abandoned_spans, std::uint64_t{1});
expect_eq(st_before_flush.dropped_active_spans, std::uint64_t{1});
const auto report = tracer.close();
expect_eq(report.exported_spans, std::uint64_t{2});
expect_eq(report.retries, std::uint64_t{1});
expect_eq(report.failed_spans, std::uint64_t{0});
expect_eq(exporter_calls->load(), 2);
const auto dumped = text_exp->text();
expect(dumped.find("root-sampled") != std::string::npos);
expect(dumped.find("abandoned") != std::string::npos);
// Closed tracer rejects active admission cleanly.
auto after_close = tracer.start_span(
empty_ctx,
SpanSpec{.name = "after-close", .explicit_root_trace_id = sampled_tid});
expect(!after_close.is_recording());
}
@@ -0,0 +1,272 @@
#include <Void/Resilience/Resilience.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace Void::Resilience;
using namespace std::chrono_literals;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
} // namespace
Void::Testing::Test resilience_bucket_config_regression_and_multi_rollback()
{
expect(!BucketConfig{0.0, 1.0}.validate().has_value());
expect(!BucketConfig{-1.0, 1.0}.validate().has_value());
expect(!BucketConfig{std::numeric_limits<double>::quiet_NaN(), 1.0}.validate().has_value());
expect(!BucketConfig{10.0, -0.5}.validate().has_value());
expect(!BucketConfig{10.0, std::numeric_limits<double>::infinity()}.validate().has_value());
// Zero refill is valid (finite non-refilling bucket).
expect(BucketConfig{10.0, 0.0}.validate().has_value());
Void::Time::ManualClock clock;
(void)clock.advance(10s);
auto b1_res = TokenBucket::create(BucketConfig{10.0, 2.0}, clock);
auto b2_res = TokenBucket::create(BucketConfig{4.0, 1.0}, clock);
require(b1_res.has_value() && b2_res.has_value());
auto b1 = std::move(*b1_res);
auto b2 = std::move(*b2_res);
// Invalid costs consume nothing.
expect(!b1.try_acquire_checked(-1.0).has_value());
expect(!b1.try_acquire_checked(0.0).has_value());
expect(!b1.try_acquire_checked(std::numeric_limits<double>::quiet_NaN()).has_value());
expect(!b1.try_acquire_checked(11.0).has_value());
expect_eq(b1.available(), 10.0);
// Spend 2 from b1, then prove backwards timestamp cannot add double credit.
auto ok1 = b1.try_acquire_checked(2.0);
require(ok1.has_value());
expect(ok1->allowed);
const auto t_now = clock.now();
const auto earlier = t_now - 5s;
expect(b1.available_at(earlier) <= 8.0001);
expect(b1.available_at(t_now) <= 8.0001);
// Multi-bucket atomic acquisition rolls back (leaves both untouched) when b2 fails.
const std::pair<TokenBucket*, double> pair_fail[] = {{&b1, 5.0}, {&b2, 5.0}};
expect(!TokenBucket::try_acquire_all(pair_fail, clock).has_value());
expect_eq(b1.available(), 8.0);
expect_eq(b2.available(), 4.0);
const std::pair<TokenBucket*, double> pair_deny[] = {{&b1, 5.0}, {&b2, 4.0}};
auto adm1 = TokenBucket::try_acquire_all(pair_deny, clock);
require(adm1.has_value());
expect(adm1->allowed);
expect_eq(b1.available(), 3.0);
expect_eq(b2.available(), 0.0);
// Now b2 cannot afford 1 -> b1 must NOT be debited!
const std::pair<TokenBucket*, double> pair_second[] = {{&b1, 2.0}, {&b2, 1.0}};
auto adm2 = TokenBucket::try_acquire_all(pair_second, clock);
require(adm2.has_value());
expect(!adm2->allowed);
expect(adm2->retry_after > 0ns);
expect_eq(b1.available(), 3.0);
}
Void::Testing::Test resilience_resource_monitor_overflow_permits_and_observers()
{
expect(!MonitorConfig{0, 0.9, 0.7}.validate().has_value());
expect(!MonitorConfig{100, 0.5, 0.8}.validate().has_value());
expect(!MonitorConfig{100, 1.5, 0.7}.validate().has_value());
// Overflow-safe check near UINT64_MAX.
const auto umax = std::numeric_limits<std::uint64_t>::max();
ResourceMonitor hugemon{umax};
expect(hugemon.try_acquire(umax - 10));
expect(!hugemon.try_acquire(20)); // previously wrapped unsigned arithmetic!
expect_eq(hugemon.usage(), umax - 10);
auto mon_res = ResourceMonitor::create(MonitorConfig{100, 0.9, 0.7});
require(mon_res.has_value());
auto mon = std::move(*mon_res);
// Observer that throws AND re-enters monitor queries must not corrupt state.
int high_calls = 0;
mon.on_high_watermark([&](std::uint64_t) {
++high_calls;
(void)mon.usage();
throw std::runtime_error{"observer failed"};
});
{
auto p = mon.try_acquire_checked(95);
require(p.has_value());
expect(p->active());
expect_eq(mon.usage(), std::uint64_t{95});
expect_eq(high_calls, 1);
expect_eq(mon.observer_errors(), std::uint64_t{1});
}
// Permit auto-released on destruction.
expect_eq(mon.usage(), std::uint64_t{0});
// Strict over-release check rejects instead of silently clamping.
expect(mon.try_acquire(10));
auto over = mon.release_checked(20);
expect(!over.has_value());
expect_eq(over.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::over_release));
expect_eq(mon.usage(), std::uint64_t{10});
}
Void::Testing::Test resilience_breaker_single_probe_generation_and_abandon()
{
expect(!BreakerConfig{0, 5s, 1, 2}.validate().has_value());
expect(!BreakerConfig{5, 5s, 0, 2}.validate().has_value());
expect(!BreakerConfig{5, 5s, 1, 0}.validate().has_value());
Void::Time::ManualClock clock;
BreakerConfig cfg{};
cfg.failure_threshold = 2;
cfg.cooldown = 5s;
cfg.half_open_max_probes = 1;
cfg.success_threshold = 2;
auto br_res = Breaker::create(cfg, clock);
require(br_res.has_value());
auto br = std::move(*br_res);
// Grab an in-flight permit at gen 1 BEFORE tripping, then trip Open with another.
auto stale_p = br.acquire();
require(stale_p.has_value());
const auto gen1 = stale_p->generation();
for (int i = 0; i < 2; ++i) {
auto p = br.acquire();
require(p.has_value());
p->finish(Outcome::dependency_failure);
}
expect(br.state() == BreakerState::open);
expect(br.generation() > gen1);
// Completing stale generation permit must not close or corrupt Open breaker.
stale_p->finish(Outcome::success);
expect(br.state() == BreakerState::open);
expect(!br.acquire().has_value());
// Advance cooldown: first acquire gets sole HalfOpen probe; concurrent 2nd fails.
(void)clock.advance(5s);
{
auto probe1 = br.acquire();
require(probe1.has_value());
expect(probe1->is_probe());
expect(br.state() == BreakerState::half_open);
expect_eq(br.half_open_in_flight(), std::size_t{1});
auto concurrent = br.acquire();
expect(!concurrent.has_value());
expect_eq(concurrent.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::circuit_open));
// Destroying probe1 without explicit finish treats it neutrally and
// frees the probe slot so HalfOpen does not deadlock.
}
expect_eq(br.half_open_in_flight(), std::size_t{0});
expect(br.state() == BreakerState::half_open);
// Two sequential successful probes close the breaker.
for (int i = 0; i < 2; ++i) {
auto probe = br.acquire();
require(probe.has_value());
expect(probe->is_probe());
probe->finish(Outcome::success);
}
expect(br.state() == BreakerState::closed);
// Multi-thread contention during HalfOpen never exceeds 1 concurrent probe.
for (int i = 0; i < 2; ++i) {
auto p = br.acquire();
require(p.has_value());
p->finish(Outcome::dependency_failure);
}
(void)clock.advance(5s);
std::atomic<int> admitted_probes{0};
std::atomic<int> rejected{0};
std::vector<std::thread> racers;
std::vector<std::optional<BreakerPermit>> acquired(16);
std::atomic<bool> go{false};
for (std::size_t i = 0; i < 16; ++i) {
racers.emplace_back([&, i] {
while (!go.load(std::memory_order_acquire)) {
}
auto r = br.acquire();
if (r.has_value()) {
admitted_probes.fetch_add(1, std::memory_order_relaxed);
acquired[i].emplace(std::move(*r));
} else {
rejected.fetch_add(1, std::memory_order_relaxed);
}
});
}
go.store(true, std::memory_order_release);
for (auto& t : racers) {
t.join();
}
expect_eq(admitted_probes.load(), 1);
expect_eq(rejected.load(), 15);
acquired.clear();
}
Void::Testing::Test resilience_bounded_keyed_limiter_churn_and_cursor_cleanup()
{
Void::Time::ManualClock clock;
KeyedBucketConfig cfg{};
cfg.capacity = 2.0;
cfg.refill_per_second = 0.0;
cfg.max_keys = 3;
cfg.max_key_bytes = 16;
cfg.idle_retention = 10s;
cfg.cleanup_batch_limit = 2;
auto kl_res = BoundedKeyedRateLimiter<std::string>::create(cfg, clock);
require(kl_res.has_value());
auto kl = std::move(*kl_res);
// Oversize key fails with key_too_large.
auto too_long = kl.admit(std::string(17, 'x'));
expect(!too_long.has_value());
expect_eq(too_long.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::key_too_large));
expect(kl.admit("k1")->allowed);
expect(kl.admit("k2")->allowed);
expect(kl.admit("k3")->allowed);
expect_eq(kl.tracked(), std::size_t{3});
// Churn keys k4..k10 must be rejected cleanly WITHOUT evicting live k1..k3!
for (int i = 4; i <= 10; ++i) {
auto r = kl.admit("k" + std::to_string(i));
require(r.has_value());
expect(!r->allowed);
}
expect_eq(kl.rejected_new_keys(), std::uint64_t{7});
expect(kl.admit("k1")->allowed); // k1's quota was NOT reset (1/2 remaining)!
expect(!kl.admit("k1")->allowed); // k1 is now genuinely empty!
// Refresh k1 at t=8s; leave k2 and k3 untouched since t=0s.
(void)clock.advance(8s);
(void)kl.admit("k2", 0.5); // consume from k2 to refresh last_seen to 8s
// Advance to t=11s: k1 (last=0s) & k3 (last=0s) are >=10s idle; k2 (last=8s) is live.
(void)clock.advance(3s);
// cleanup_batch_limit=2 removes in bounded incremental steps across turns.
const std::size_t r1 = kl.cleanup_step();
const std::size_t r2 = kl.cleanup_step();
expect_eq(r1 + r2, std::size_t{2});
expect_eq(kl.tracked(), std::size_t{1});
}
@@ -0,0 +1,252 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/ThreadPool.hpp>
#include <Void/Resilience/AsyncPolicy.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <stop_token>
#include <string>
#include <vector>
namespace Async = Void::Async;
using namespace Void::Resilience;
using namespace std::chrono_literals;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
namespace
{
Void::Coro::Task<Void::Result::Result<BulkheadPermit>> acquire_bulkhead_coro(
Bulkhead& bh,
Async::OperationOptions opts,
Async::Executor* exec)
{
co_return co_await bh.acquire_async(std::move(opts), exec);
}
Void::Coro::Task<void> spawn_acquire_to_slot(
Bulkhead* bh,
Async::OperationOptions opts,
Async::Executor* exec,
std::optional<Void::Result::Result<BulkheadPermit>>* out,
std::atomic<int>* done_count)
{
*out = co_await bh->acquire_async(std::move(opts), exec);
done_count->fetch_add(1, std::memory_order_release);
}
Void::Coro::Task<Void::Result::Result<int>> run_pipeline_coro(
ResiliencePipeline pipeline,
std::function<Void::Result::Result<int>()> fn,
std::function<AttemptClassification(const Void::Result::Result<int>&)> classify,
Async::OperationOptions opts,
Async::Executor* exec)
{
co_return co_await execute_resilient(
std::move(pipeline),
std::move(fn),
std::move(classify),
std::move(opts),
exec);
}
} // namespace
Void::Testing::Test resilience_async_bulkhead_fifo_expiry_stop_and_close()
{
Void::Time::ManualClock clock;
BulkheadConfig cfg{};
cfg.max_active = 1;
cfg.max_waiting = 2;
auto bh_res = Bulkhead::create(cfg, clock);
require(bh_res.has_value());
auto bh = std::move(*bh_res);
auto active1 = bh.try_acquire();
require(active1.has_value());
expect_eq(bh.active_count(), std::size_t{1});
Void::Async::ManualExecutor exec;
std::optional<Void::Result::Result<BulkheadPermit>> out_exp;
std::optional<Void::Result::Result<BulkheadPermit>> out_stop;
std::optional<Void::Result::Result<BulkheadPermit>> out_ok;
std::atomic<int> done{0};
std::stop_source stop_src;
Async::OperationOptions exp_opts{};
exp_opts.deadline = clock.now() + 50ms;
Async::OperationOptions stop_opts{};
stop_opts.stop = stop_src.get_token();
// Enqueue 2 waiters (limit=2): waiter1 has deadline, waiter2 has stop token.
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, exp_opts, &exec, &out_exp, &done));
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, stop_opts, &exec, &out_stop, &done));
(void)exec.drain();
expect_eq(bh.waiting_count(), std::size_t{2});
// Advance past waiter1's deadline AND request waiter2 stop before next admission.
(void)clock.advance(100ms);
stop_src.request_stop();
(void)exec.drain();
// Release active1 -> evicts expired waiter1 and cancelled waiter2, freeing slot!
active1->release();
(void)exec.drain();
expect_eq(done.load(std::memory_order_acquire), 2);
require(out_exp.has_value() && !out_exp->has_value());
require(out_stop.has_value() && !out_stop->has_value());
expect_eq(bh.waiting_count(), std::size_t{0});
expect_eq(bh.active_count(), std::size_t{0});
// Now test FIFO wait grant + close().
auto active2 = bh.try_acquire();
require(active2.has_value());
done.store(0);
std::optional<Void::Result::Result<BulkheadPermit>> out_closed;
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, {}, &exec, &out_ok, &done));
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, {}, &exec, &out_closed, &done));
(void)exec.drain();
expect_eq(bh.waiting_count(), std::size_t{2});
// 3rd waiter overflows max_waiting=2 immediately.
auto full_t = acquire_bulkhead_coro(bh, {}, &exec);
auto full_r = full_t.run();
expect(!full_r.has_value());
expect_eq(full_r.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::bulkhead_full));
// Releasing active2 grants first FIFO waiter (out_ok).
active2->release();
(void)exec.drain();
require(out_ok.has_value() && out_ok->has_value());
// close() rejects remaining waiter (out_closed) with closed error.
bh.close();
(void)exec.drain();
require(out_closed.has_value() && !out_closed->has_value());
expect_eq(out_closed->error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::closed));
out_ok->value().release();
}
Void::Testing::Test resilience_async_execute_order_replay_deadline_and_breaker()
{
Void::Time::ManualClock clock;
auto rl = TokenBucket::create(BucketConfig{10.0, 1.0}, clock);
auto bh = Bulkhead::create(BulkheadConfig{2, 4}, clock);
auto br = Breaker::create(BreakerConfig{2, 5s, 1, 1}, clock);
require(rl.has_value() && bh.has_value() && br.has_value());
// 1. Non-replay-safe write never retries even when classifier marks retryable.
int calls = 0;
std::vector<std::chrono::nanoseconds> delays;
ResiliencePipeline write_pipe{};
write_pipe.rate_limiter = &*rl;
write_pipe.bulkhead = &*bh;
write_pipe.breaker = &*br;
write_pipe.clock = &clock;
write_pipe.retry = ResilientRetryConfig{
.max_attempts = 3,
.base_delay = 100ms,
.max_delay = 2000ms,
.replay_safe = false,
.deterministic_seed = 42};
write_pipe.wait_fn = [&](std::chrono::nanoseconds d, const Async::OperationOptions&) {
delays.push_back(d);
(void)clock.advance(d);
return true;
};
auto res1 = run_pipeline_coro(
write_pipe,
[&]() -> Void::Result::Result<int> {
++calls;
return Void::Result::fail("write uncertain");
},
[](const Void::Result::Result<int>&) {
return AttemptClassification{Outcome::dependency_failure, true};
},
{},
nullptr)
.run();
expect(!res1.has_value());
expect_eq(calls, 1);
expect_eq(bh->active_count(), std::size_t{0});
// Reset breaker (or let 2nd failure trip it on replay-safe call!).
// 2. Replay-safe read retries through limits until breaker trips open!
calls = 0;
ResiliencePipeline read_pipe = write_pipe;
read_pipe.retry.replay_safe = true;
read_pipe.retry.max_attempts = 5;
auto res2 = run_pipeline_coro(
read_pipe,
[&]() -> Void::Result::Result<int> {
++calls;
return Void::Result::fail("transient downstream");
},
[](const Void::Result::Result<int>&) {
return AttemptClassification{Outcome::dependency_failure, true};
},
{},
nullptr)
.run();
// 1st attempt failed before this test -> breaker already had 1 failure, so
// this attempt trips breaker Open on attempt #1, then attempt #2 fails with circuit_open!
expect(!res2.has_value());
expect_eq(calls, 1);
expect_eq(res2.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::circuit_open));
expect_eq(bh->active_count(), std::size_t{0});
// 3. Replay-safe succeeds on attempt #3 within shared total deadline.
(void)clock.advance(5s); // cooldown elapsed -> HalfOpen probe closes breaker on 1st success!
auto br2 = Breaker::create(BreakerConfig{10, 5s, 1, 1}, clock);
require(br2.has_value());
calls = 0;
delays.clear();
ResiliencePipeline ok_pipe = read_pipe;
ok_pipe.breaker = &*br2;
ok_pipe.retry.max_attempts = 3;
ok_pipe.wait_fn = [&](std::chrono::nanoseconds d, const Async::OperationOptions&) {
delays.push_back(d);
(void)clock.advance(d);
return true;
};
Async::OperationOptions bounded_opts{};
bounded_opts.deadline = clock.now() + 5000ms;
auto res3 = run_pipeline_coro(
ok_pipe,
[&]() -> Void::Result::Result<int> {
++calls;
if (calls < 3) {
return Void::Result::fail("retryable");
}
return 99;
},
[](const Void::Result::Result<int>& r) {
return r.has_value()
? AttemptClassification{Outcome::success, false}
: AttemptClassification{Outcome::dependency_failure, true};
},
bounded_opts,
nullptr)
.run();
require(res3.has_value());
expect_eq(*res3, 99);
expect_eq(calls, 3);
expect_eq(delays.size(), std::size_t{2});
expect(delays[0] <= 100ms);
expect(delays[1] <= 200ms);
}
+237
View File
@@ -0,0 +1,237 @@
#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Subprocess.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <atomic>
#include <chrono>
#include <csignal>
#include <filesystem>
#include <fstream>
#include <limits>
#include <stop_token>
#include <string>
#include <vector>
namespace
{
using namespace Void::Stacktrace;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
[[gnu::noinline]] Void::Result::Result<RawTrace>
nested_capture_helper(CaptureOptions opt)
{
return capture(opt);
}
} // namespace
Void::Testing::Test stacktrace_capabilities_and_empty_formatting()
{
const auto caps = capabilities();
expect(caps.raw_capture);
expect(!caps.async_signal_safe);
expect(!caps.backend_name.empty());
expect_eq(format_stacktrace({}), std::string{" <no stacktrace available>\n"});
expect_eq(format_resolved_trace(ResolvedTrace{}),
std::string{" <no stacktrace available>\n"});
expect(!capture(CaptureOptions{.max_frames = 0}).has_value());
expect(!capture(CaptureOptions{.max_frames = kMaxCaptureFrames + 1}).has_value());
}
Void::Testing::Test stacktrace_capture_no_log_recursion_and_no_source_io()
{
std::atomic<int> log_calls{0};
struct LogReset {
~LogReset() { (void)Void::Log::detach_and_drain(0); }
} guard;
Void::Log::set_sink([&](Void::Log::Level,
std::string_view,
std::string_view,
const std::source_location&) {
log_calls.fetch_add(1, std::memory_order_relaxed);
});
auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 8});
require(raw.has_value());
expect(!raw->frames.empty());
expect_eq(log_calls.load(), 0);
// Asking for 1 frame on a deeper call stack sets truncated = true.
auto trunc = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 1});
require(trunc.has_value());
expect_eq(trunc->frames.size(), std::size_t{1});
expect(trunc->truncated);
// Default resolve() performs no snippet file reads and emits no Void::Log calls.
auto res = resolve(*raw, ResolveOptions{});
require(res.has_value());
expect_eq(res->frames.size(), raw->frames.size());
expect_eq(log_calls.load(), 0);
for (const auto& f : res->frames) {
expect(f.source_snippet.empty());
}
}
Void::Testing::Test stacktrace_resolver_cache_redaction_and_safe_snippets()
{
const auto base = std::filesystem::temp_directory_path() / "void_stacktrace_test";
std::filesystem::remove_all(base);
const auto allowed_root = base / "allowed";
const auto secret_root = base / "secret";
std::filesystem::create_directories(allowed_root);
std::filesystem::create_directories(secret_root);
const auto src_file = allowed_root / "sample.cpp";
{
std::ofstream os{src_file};
for (int i = 1; i <= 20; ++i) {
os << "int line_" << i << " = " << i << ";\n";
}
}
const auto outside_file = secret_root / "creds.txt";
{
std::ofstream os{outside_file};
os << "SECRET_KEY=12345\n";
}
ResolveOptions opt;
opt.allowed_source_roots = {allowed_root};
opt.redact_prefixes = {allowed_root.string()};
opt.context_lines = 1;
opt.max_snippet_bytes = 256;
// 1. Valid read under allowed root.
auto ok_snip = read_source_snippet_checked(src_file, 10, opt);
require(ok_snip.has_value());
expect(ok_snip->find(" >>> int line_10") != std::string::npos);
// 2. Rejects empty allowed_source_roots, traversal, outside file, and symlinks escaping root.
ResolveOptions no_roots = opt;
no_roots.allowed_source_roots.clear();
expect(!read_source_snippet_checked(src_file, 5, no_roots).has_value());
const auto traversal = allowed_root / ".." / "secret" / "creds.txt";
auto trav_res = read_source_snippet_checked(traversal, 1, opt);
expect(!trav_res.has_value());
expect_eq(trav_res.error().code().value,
static_cast<std::int32_t>(StacktraceErrorCode::unsafe_path));
#ifndef _WIN32
const auto sym_escape = allowed_root / "escape.txt";
std::error_code sym_ec;
std::filesystem::create_symlink(outside_file, sym_escape, sym_ec);
if (!sym_ec) {
auto sym_res = read_source_snippet_checked(sym_escape, 1, opt);
expect(!sym_res.has_value());
expect_eq(sym_res.error().code().value,
static_cast<std::int32_t>(StacktraceErrorCode::unsafe_path));
}
#endif
// 3. Overflow-safe INT_MAX line arithmetic and scan byte limit.
auto int_max_res = read_source_snippet_checked(
src_file, std::numeric_limits<int>::max(), opt);
expect(int_max_res.has_value());
ResolveOptions tiny_scan = opt;
tiny_scan.max_source_scan_bytes = 32;
auto scan_res = read_source_snippet_checked(src_file, 15, tiny_scan);
expect(!scan_res.has_value());
expect_eq(scan_res.error().code().value,
static_cast<std::int32_t>(StacktraceErrorCode::scan_limit_exceeded));
// 4. Resolver cache hit, module invalidation, and entry/byte cap eviction.
Resolver resolver{2, kDefaultResolverCacheBytes};
auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 4});
require(raw.has_value() && !raw->frames.empty());
ResolveOptions sym_opt = opt;
sym_opt.source_snippets = false;
auto r1 = resolver.resolve(*raw, sym_opt);
require(r1.has_value());
expect(resolver.cache_entries() <= 2);
std::string first_mod;
for (const auto& f : raw->frames) {
if (!f.module_id.empty()) {
first_mod = f.module_id;
break;
}
}
if (!first_mod.empty()) {
(void)resolver.invalidate_module(first_mod);
}
resolver.clear_cache();
expect_eq(resolver.cache_entries(), std::size_t{0});
expect_eq(resolver.cache_bytes(), std::size_t{0});
std::filesystem::remove_all(base);
}
Void::Testing::Test stacktrace_cancellation_deadline_and_subprocess_crash()
{
auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 4});
require(raw.has_value() && !raw->frames.empty());
// Pre-cancelled stop_token marks incomplete = true while retaining raw frames.
std::stop_source ss;
ss.request_stop();
ResolveOptions cancelled_opt;
cancelled_opt.stop = ss.get_token();
auto cres = resolve(*raw, cancelled_opt);
require(cres.has_value());
expect(cres->incomplete);
expect_eq(cres->frames.size(), raw->frames.size());
expect(cres->frames[0].status == FrameResolveStatus::cancelled);
expect_eq(cres->frames[0].raw.address, raw->frames[0].address);
// Expired ManualClock deadline also marks incomplete = true cleanly.
Void::Time::ManualClock clock;
const auto past = clock.now();
(void)clock.advance(std::chrono::seconds{1});
ResolveOptions timeout_opt;
timeout_opt.clock = &clock;
timeout_opt.deadline = past;
auto tres = resolve(*raw, timeout_opt);
require(tres.has_value());
expect(tres->incomplete);
expect(tres->frames[0].status == FrameResolveStatus::timed_out);
#ifndef _WIN32
// Async-signal-safe fatal marker writer writes clean ASCII record.
int pipefd[2]{-1, -1};
require(::pipe(pipefd) == 0);
expect(write_fatal_signal_marker(pipefd[1], SIGABRT));
::close(pipefd[1]);
char buf[128]{};
const auto n = ::read(pipefd[0], buf, sizeof(buf) - 1);
::close(pipefd[0]);
require(n > 0);
const std::string marker{buf, static_cast<std::size_t>(n)};
expect(marker.find("VOID_FATAL_SIGNAL sig=") != std::string::npos);
// Subprocess crash isolation for fatal child aborts (replaced in-process signal UB).
const std::string self_exe = Void::Testing::current_executable_path();
if (!self_exe.empty()) {
const std::vector<std::string> args{"--selftest-child", "abort"};
const auto run = Void::Testing::run_isolated_subprocess(
self_exe,
args,
Void::Testing::ProcessTestOptions{.timeout = std::chrono::seconds{5}});
expect(run.outcome == Void::Testing::ProcessOutcome::crashed);
expect_eq(run.term_signal, SIGABRT);
}
#endif
}