Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
385a441b0b | ||
|
|
5184d1cf8c | ||
|
|
691808eab6 | ||
|
|
658c21a2fa | ||
|
|
86d777eae6 | ||
|
|
700024a24d | ||
|
|
3e254055e0 | ||
|
|
bb0b2e1701 | ||
|
|
9920bfdaac | ||
|
|
66baae74a0 | ||
|
|
22c8538754 | ||
|
|
b50131f52e | ||
|
|
adfc8548dc | ||
|
|
53d42bda42 | ||
|
|
9be51134e8 | ||
|
|
cb988fa985 | ||
|
|
1a54f3857e | ||
|
|
40b579d683 | ||
|
|
ef5312c4b3 | ||
|
|
1dc51d5c43 | ||
|
|
a24e086e47 | ||
|
|
1474a69ab1 | ||
|
|
6b3dededac | ||
|
|
d83d0f4533 | ||
|
|
76ad7d1b39 | ||
|
|
84e6fe81ed | ||
|
|
fdf0da5ca8 | ||
|
|
427cc9a843 | ||
|
|
9925ea1764 | ||
|
|
43922d1ad4 | ||
|
|
9ef425c36c | ||
|
|
47736cb6ce | ||
|
|
00d7478335 | ||
|
|
713d2dc656 | ||
|
|
eb42228604 | ||
|
|
8a1c15f9c0 | ||
|
|
acd77ee67a | ||
|
|
9931c5ffc4 | ||
|
|
e43eee738c | ||
|
|
39a48d5c0a | ||
|
|
9a3c5d86ef | ||
|
|
fcdbc063b2 | ||
|
|
3f67b1ecb7 | ||
|
|
44799602c9 | ||
|
|
1e2fb8b5c6 | ||
|
|
7b57b355cd | ||
|
|
3d8dfb0ea2 | ||
|
|
a74a402938 | ||
|
|
18a623aa62 | ||
|
|
fe99051ded | ||
|
|
809b6f548d |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(Void VERSION 1.2.1 LANGUAGES CXX)
|
||||
project(Void VERSION 1.2.1 LANGUAGES C CXX)
|
||||
if(PROJECT_IS_TOP_LEVEL)
|
||||
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
|
||||
elseif(NOT DEFINED BUILD_SHARED_LIBS)
|
||||
|
||||
@@ -158,9 +158,89 @@ function(void_fetch_dependency DEP_NAME)
|
||||
endif()
|
||||
|
||||
if(DEP_NAME STREQUAL "SQLite3")
|
||||
if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
if(TARGET SQLite3::SQLite3)
|
||||
return()
|
||||
endif()
|
||||
if(TARGET SQLite::SQLite3)
|
||||
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
|
||||
return()
|
||||
endif()
|
||||
|
||||
set(_void_sqlite_dir "${VOID_SQLITE3_AMALGAMATION_DIR}")
|
||||
if(NOT _void_sqlite_dir)
|
||||
find_package(SQLite3 QUIET)
|
||||
if(TARGET SQLite3::SQLite3)
|
||||
return()
|
||||
endif()
|
||||
if(TARGET SQLite::SQLite3)
|
||||
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
|
||||
return()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
option(VOID_FETCH_SQLITE3
|
||||
"Allow FetchContent SQLite3 amalgamation fallback when system SQLite3 is unavailable"
|
||||
ON)
|
||||
set(VOID_SQLITE3_AMALGAMATION_DIR "" CACHE PATH
|
||||
"Path containing pre-downloaded sqlite3.c and sqlite3.h amalgamation sources")
|
||||
set(VOID_SQLITE3_FETCH_URL
|
||||
"https://www.sqlite.org/2025/sqlite-amalgamation-3490100.zip"
|
||||
CACHE STRING "SQLite3 amalgamation archive URL for FetchContent fallback")
|
||||
set(VOID_SQLITE3_FETCH_HASH "" CACHE STRING
|
||||
"Optional SHA256 hash (SHA256=...) for VOID_SQLITE3_FETCH_URL")
|
||||
|
||||
if(NOT _void_sqlite_dir AND VOID_FETCH_SQLITE3 AND
|
||||
NOT CMAKE_DISABLE_FIND_PACKAGE_SQLite3)
|
||||
message(STATUS "[Void] System SQLite3 not found — falling back to SQLite3 amalgamation")
|
||||
if(VOID_SQLITE3_FETCH_HASH)
|
||||
FetchContent_Declare(SQLite3
|
||||
URL "${VOID_SQLITE3_FETCH_URL}"
|
||||
URL_HASH "${VOID_SQLITE3_FETCH_HASH}"
|
||||
SYSTEM
|
||||
)
|
||||
else()
|
||||
FetchContent_Declare(SQLite3
|
||||
URL "${VOID_SQLITE3_FETCH_URL}"
|
||||
SYSTEM
|
||||
)
|
||||
endif()
|
||||
FetchContent_MakeAvailable(SQLite3)
|
||||
if(EXISTS "${sqlite3_SOURCE_DIR}/sqlite3.c")
|
||||
set(_void_sqlite_dir "${sqlite3_SOURCE_DIR}")
|
||||
else()
|
||||
file(GLOB _found_sqlite_c LIST_DIRECTORIES FALSE
|
||||
"${sqlite3_SOURCE_DIR}/*/sqlite3.c")
|
||||
if(_found_sqlite_c)
|
||||
list(GET _found_sqlite_c 0 _first_sqlite_c)
|
||||
get_filename_component(_void_sqlite_dir "${_first_sqlite_c}" DIRECTORY)
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(_void_sqlite_dir AND EXISTS "${_void_sqlite_dir}/sqlite3.c" AND
|
||||
EXISTS "${_void_sqlite_dir}/sqlite3.h")
|
||||
void_fetch_dependency(Threads)
|
||||
add_library(void_sqlite3_amalgamation STATIC
|
||||
"${_void_sqlite_dir}/sqlite3.c")
|
||||
set_target_properties(void_sqlite3_amalgamation PROPERTIES
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
C_STANDARD 11
|
||||
SYSTEM TRUE)
|
||||
target_include_directories(void_sqlite3_amalgamation SYSTEM PUBLIC
|
||||
"${_void_sqlite_dir}")
|
||||
target_compile_definitions(void_sqlite3_amalgamation PRIVATE
|
||||
SQLITE_THREADSAFE=1
|
||||
SQLITE_ENABLE_FTS5
|
||||
SQLITE_ENABLE_JSON1
|
||||
SQLITE_DQS=0)
|
||||
target_link_libraries(void_sqlite3_amalgamation PUBLIC
|
||||
Threads::Threads
|
||||
"$<$<NOT:$<PLATFORM_ID:Windows>>:${CMAKE_DL_LIBS};m>")
|
||||
add_library(SQLite3::SQLite3 ALIAS void_sqlite3_amalgamation)
|
||||
return()
|
||||
endif()
|
||||
|
||||
find_package(SQLite3 REQUIRED)
|
||||
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
|
||||
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
|
||||
endif()
|
||||
|
||||
+8
-1
@@ -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 "" ""
|
||||
@@ -11,7 +12,9 @@ function(void_add_module MODULE_NAME)
|
||||
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
|
||||
|
||||
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
|
||||
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp")
|
||||
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h")
|
||||
foreach(_excl IN LISTS ARG_EXCLUDE_HEADERS)
|
||||
list(REMOVE_ITEM HDR "${CMAKE_CURRENT_SOURCE_DIR}/include/${_excl}")
|
||||
endforeach()
|
||||
@@ -61,6 +64,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.
|
||||
|
||||
@@ -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") |
|
||||
@@ -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).
|
||||
Updated: 2026-11-27.
|
||||
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave9` (from `main`
|
||||
at `3e25405`, merged Waves 1–8 + `VL-001`..`VL-013` 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,179 @@ 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.
|
||||
|
||||
## Verification already observed (Wave 6A — P2 System, SystemAsync, IPC)
|
||||
|
||||
- Wave 6A prep & P2/P3 error domains (`3f67b1e`): reserved `kIpcErrorDomain = 16`..
|
||||
`kSqliteErrorDomain = 21` in `Error.hpp`, added thread-safe pipe `ENOTSOCK` fallback in
|
||||
`EpollDriver.cpp`, enabled `VoidProcessHelper` for `Void::System` OR `Void::IPC`, added
|
||||
`M-SYSTEM-01-05.md` and `S-IPC-01-03.md`.
|
||||
- `System` (`fcdbc06`): `System;Testing` (`/tmp/void-w6a-system`, `-Werror`) `System*`
|
||||
53/53 passed (226.6 ms); `ctest` 2/2 (`VoidTests` 0.57 s,
|
||||
`VoidInstalledComponentConsumers` including `SystemOnly` 3.95 s).
|
||||
- `SystemAsync` (`9a3c5d8`): `SystemAsync;Testing` (`/tmp/void-w6a-sysasync`, `-Werror`)
|
||||
`SystemAsync*` 2/2 passed (211.5 ms); `ctest` 2/2 (`VoidTests` 1.15 s,
|
||||
`VoidInstalledComponentConsumers` including `SystemAsyncOnly` 9.43 s).
|
||||
- `IPC` (`39a48d5`): `IPC;Testing` (`/tmp/void-w6a-ipc`, `-Werror`) `Ipc*` 3/3 passed
|
||||
(8.8 ms); `ctest` 2/2 (`VoidTests` 0.49 s, `VoidInstalledComponentConsumers` including
|
||||
`IPCOnly` 12.20 s, total 12.70 s).
|
||||
- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6a-full`, 39 modules,
|
||||
`39a48d5`): `VoidTests` 1,386 tests — 1,383 passed, 3 intentional skips
|
||||
(`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (4.68 s);
|
||||
`ctest` 2/2 passed (`VoidTests` 4.58 s, `VoidInstalledComponentConsumers` 19 consumer
|
||||
builds incl. `SystemOnly`, `SystemAsyncOnly`, `IPCOnly`, `RelocatedFoundation`,
|
||||
`RelocatedExternal`, 31.05 s, total 35.63 s).
|
||||
- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6a-asan`, 39
|
||||
modules, `39a48d5`): `VoidTests` 1,386 tests — 1,383 passed, 3 skipped, 0 failed
|
||||
(19.34 s), 0 ASan/LSan leaks, 0 UBSan errors.
|
||||
- Wave 6A Debug TSan subset (`/tmp/void-w6a-tsan`, 14 modules, `39a48d5`):
|
||||
`Process*|SystemHardening*|SystemAsync*|Ipc*|FileWatcher*|IoDriver*|OperationScope*`
|
||||
35/35 passed (609.4 ms), 0 TSan data races.
|
||||
- `VoidFoundationBench` post-W6A (`rev=39a48d5c0a72`, `/tmp/void-w6a-full/post-w6a.json`):
|
||||
`harness_empty_loop` 0.38 ns, `core_uuid_parse_hyphenated` 24.92 ns,
|
||||
`core_uuid_to_string` 17.45 ns, `core_hash_fnv1a64_256b` 181.41 ns,
|
||||
`core_hash_murmur3_256b` 67.93 ns, `functional_result_ok_chain` 1.13 ns,
|
||||
`functional_error_with_context` 58.77 ns, `math_checked_add_loop` 0.47 ns,
|
||||
`containers_spsc_ring_push_pop` 8.80 ns, `containers_lru_get_put` 20.61 ns,
|
||||
`binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 311.16 ns,
|
||||
`data_json_serialize_small_object` 162.52 ns.
|
||||
|
||||
## Verification already observed (StrictJson RFC 8259 decimals — `acd77ee`, on `main`)
|
||||
|
||||
- Added `ParseOptions{maximumDepth, allowDecimals = true}` and `double` variant
|
||||
alternative to `Void::Json::Strict` (`include/Void/Data/StrictJson.hpp`) for LSP
|
||||
messages while preserving exact `int64_t` integer semantics and `allowDecimals = false`
|
||||
opt-out (`tests/standalone/Data/StrictJson.cpp` 6/6 tests).
|
||||
- Verified in RelWithDebInfo `-Werror` (`49/49`, `ctest` 2/2) and Debug ASan+UBSan
|
||||
`-Werror` (`/tmp/void-strictjson-asan`, `49/49` in 7.0 ms, 0 leaks, 0 UB); pushed to
|
||||
`origin/main`.
|
||||
|
||||
## Verification already observed (Wave 6B — P2 Crypto, Security, Archive, Update)
|
||||
|
||||
- Wave 6B task specs (`8a1c15f`): added `M-CRYPTO-01-05.md`, `M-SECURITY-01-04.md`,
|
||||
`M-ARCHIVE-01-05.md`, and `M-UPDATE-01-06.md`.
|
||||
- `Crypto` & `CryptoAsync` (`eb42228`): `Crypto;CryptoAsync;Testing` (`/tmp/void-w6b-crypto`,
|
||||
`-Werror`, `-p openssl`, 10 modules) `Crypto*|crypto_*` 8/8 (`Crypto` 3,
|
||||
`CryptoHardening` 3, `CryptoAsync` 2); `ctest` 2/2 (`7.22 s`, including `CryptoOnly` &
|
||||
`CryptoAsyncOnly`).
|
||||
- `Security` & `SecurityAsync` (`713d2dc`): `Security;SecurityAsync;Testing`
|
||||
(`/tmp/void-w6b-security`, `-Werror`, `-p libsodium`, 10 modules) `Security*|security_*`
|
||||
14/14 (`720.7 ms`: `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2);
|
||||
`ctest` 2/2 (`8.46 s`, including `SecurityOnly` & `SecurityAsyncOnly`).
|
||||
- `Archive` (`00d7478`): `Archive;Testing` (`/tmp/void-w6b-archive`, `-Werror`,
|
||||
`-p libarchive`, 7 modules) `Archive*|archive_*` 9/9 (`259.0 ms`: `Archive` 6,
|
||||
`ArchiveHardening` 3); `ctest` 2/2 (`5.76 s`, including `ArchiveOnly`).
|
||||
- `Update` (`47736cb`): `Update;Testing` (`/tmp/void-w6b-update`, `-Werror`,
|
||||
`-p libarchive -p openssl`, 12 modules) `Update*|update_*|component_feed_*|readable_component_*|version_store_*`
|
||||
25/25 (`1.91 s`: `Update` 22, `UpdateHardening` 3); `ctest` 2/2 (`10.64 s`, including
|
||||
`UpdateOnly`).
|
||||
- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6b-full`, 41 modules,
|
||||
`47736cb`): `VoidTests` 1,406 tests — 1,403 passed, 3 intentional skips
|
||||
(`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed
|
||||
(`6.26 s`); `ctest` 2/2 passed (`VoidTests` 7.34 s, `VoidInstalledComponentConsumers`
|
||||
all 25 consumers incl. `CryptoOnly`, `CryptoAsyncOnly`, `SecurityOnly`,
|
||||
`SecurityAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `RelocatedFoundation`,
|
||||
`RelocatedExternal`, 40.73 s, total 48.07 s).
|
||||
- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6b-asan`, 41
|
||||
modules, `47736cb`): `VoidTests` 1,406 tests — 1,403 passed, 3 skipped, 0 failed
|
||||
(`21.78 s`), 0 ASan/LSan leaks, 0 UBSan errors.
|
||||
- Wave 6B Debug TSan subset (`CryptoAsync;SecurityAsync;Update;Testing`,
|
||||
`/tmp/void-w6b-tsan`, 20 modules, `47736cb`): 56/56 passed (`4.86 s`), 0 TSan data races.
|
||||
- `VoidFoundationBench` post-W6B (`rev=47736cb6ce2f`, `/tmp/void-w6b-full/post-w6b.json`):
|
||||
`harness_empty_loop` 0.38 ns, `core_uuid_parse_hyphenated` 24.52 ns,
|
||||
`core_uuid_to_string` 16.53 ns, `core_hash_fnv1a64_256b` 179.95 ns,
|
||||
`core_hash_murmur3_256b` 67.37 ns, `functional_result_ok_chain` 1.12 ns,
|
||||
`functional_error_with_context` 58.37 ns, `math_checked_add_loop` 0.47 ns,
|
||||
`containers_spsc_ring_push_pop` 8.76 ns, `containers_lru_get_put` 21.02 ns,
|
||||
`binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 333.32 ns,
|
||||
`data_json_serialize_small_object` 165.99 ns.
|
||||
|
||||
### Wave 7 (P2 Persistence & Storage: `Sqlite`, `SqliteAsync`, and NEW Original `Storage` — `G-STORE` Gate)
|
||||
|
||||
- Task specs committed on `feat/roadmap-p2-wave7` (`9925ea1`): `tasks/M-SQLITE-01-05.md`, `tasks/S-STORAGE-01-06.md`.
|
||||
- **`Void::Sqlite` & `Void::SqliteAsync`** (`427cc9a`, TSan lock-order fix `84e6fe8`): hardened `ConnectionState`, `open_database`/`OpenOptions` with checked WAL/FULL/`foreign_keys` pragmas and disabled extension loading, checked positional/named binds, borrowed lifetime owners, strict typed `RowView`/getters, `Transaction` (`sqlite3_get_autocommit`), `Savepoint`, `close()` busy guard, `migrate_checked` with `_void_schema_migrations`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, plus optional `Void::SqliteAsync` (`AsyncPool`, bounded workers, leased interrupt cleanup) and `SqliteOnly`/`SqliteAsyncOnly` installed consumers.
|
||||
- **`Void::Storage` (`G-STORE` Gate)** (`fdf0da5`): built NEW original durable single-writer key-value storage engine with zero SQLite or external dependencies (`Crc32c`, `Types`, `FilePort`/`PosixFilePort`/`FaultInjectingFilePort`, V1 binary codecs `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1`, `Batch` with preconditions, `Engine` with bootstrap/recovery/tail-truncation/checkpoint/incremental compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance) and `StorageOnly` installed consumer.
|
||||
- Integrated verification (`84e6fe8`): `VoidTests` 1,417 tests (1,414 passed, 3 intentionally skipped hardware/root checks, 0 failed across 43 modules in 21.06s), `ctest` 2/2 (all 28 installed consumers in 65.05s), Debug ASan+UBSan 1,417 tests (0 leaks, 0 UB in 36.47s), TSan (`SqliteAsync;Storage;Testing`) 19/19 in 15.38s with 0 warnings, and post-Wave-7 `VoidFoundationBench`.
|
||||
|
||||
### Wave 8 (P2 Lifecycle: `Service`, `ServicePlugin`, `Plugin`, `Configuration`, `ConfigurationAsync`, and `Fsm`)
|
||||
|
||||
- Task specs committed on `feat/roadmap-p2-wave8` (`6b3dede`): `tasks/M-SERVICE-01-05.md`, `tasks/M-PLUGIN-01-06.md`, `tasks/M-CONFIGURATION-01-05.md`, `tasks/M-FSM-01-05.md`; error domains `22..25` reserved in `Functional/Error.hpp` (`kServiceErrorDomain`, `kPluginErrorDomain`, `kConfigurationErrorDomain`, `kFsmErrorDomain`); `cmake/Module.cmake` updated to install `*.h` headers.
|
||||
- **`Void::Service` & `Void::ServicePlugin`** (`1474a69`): immutable `ServiceSnapshot`, owning `ServiceHandle<I>`, transactional DAG `ProviderSet`/`prepare_batch`/`start_staged`/`publish`/`start_and_publish`/`close_and_join`, split `Void::ServicePlugin` helper target, and `ServiceOnly`/`ServicePluginOnly` installed consumers.
|
||||
- **`Void::Plugin`** (`a24e086`, TSan pthread fixture fix `1a54f38`): pure-C11 `include/Void/Plugin/CAbi.h` v1 (`VOID_PLUGIN_ABI_VERSION`), `CModuleHost` (pins/quiesce/checkpoint/replace/degraded state/retention/byte budgets/dep topological batching), `CAbiAdapter`, unlocked `PluginManager` staging, 9 pure-C11 `-Werror` test fixtures, and `PluginOnly` installed consumer.
|
||||
- **`Void::Configuration` & `Void::ConfigurationAsync`** (`1dc51d5`): `Bind.hpp` attributes (`Secret`, `RestartRequired`, `Deprecated`, `IntRange`, `RealRange`), bounded `Schema<T>` reflection/provenance/redaction/deprecation validation, async transactional `ReloadController<T>` + `Snapshot<T>` + `prepare_external` + coalescing `WatcherService`, and `ConfigurationOnly`/`ConfigurationAsyncOnly` installed consumers.
|
||||
- **`Void::Fsm`** (`ef5312c`, TSan fixes `40b579d`, `cb988fa`): `terminal(Status)`/`TerminationReason`, `FsmErrorCode`/`kFsmErrorDomain = 25`, `FsmLimits`, `ExecutionBinding`, `Checkpoint`/`StateId`, hardened `Detail/Engine` (`MonotonicClock`, bounded `try_post`, `m_control_queue`, `ScopeId` waiter/timer tracking, 64-event/1ms turn budget), `Detail/Awaiter` (scope+user `stop_token` cancellation), `Machine::run`/`acquire_service`/`run_parallel_structured`/`run_parallel_any_structured`/`request_checkpoint`/`restore_checkpoint`, `Orchestrator` (`StopOnFault`/`BoundedRestart`, unlocked observers), `tests/standalone/Fsm/FsmHardening.cpp`, and `FsmOnly` installed consumer.
|
||||
- Integrated verification (`cb988fa`, `-DVOID_WARNINGS_AS_ERRORS=ON`):
|
||||
- Full RelWithDebInfo (`/tmp/void-w8-full`, 45 modules): `VoidTests` 1,437 tests (1,434 passed, 3 skipped, 0 failed, `20.99s`); `ctest` 2/2 (`77.11s`, all 34 installed consumers); `VoidFoundationBench` post-W8 (`rev=cb988fa98509`, `/tmp/void-w8-full/post-w8.json`): `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w8-asan`, 45 modules): `VoidTests` 1,437 tests (`37.13s`), 0 leaks, 0 UB.
|
||||
- Debug TSan (`/tmp/void-w8-tsan`, `ServicePlugin;ConfigurationAsync;Fsm;Testing`, 20 modules): `VoidTests` 1,110 tests (1,107 passed, 3 skipped, 0 failed, `11.49s`), 0 data races.
|
||||
|
||||
### VoidBuildSystem Upstream Feature Wave (`VL-001`..`VL-013`, `feat/upstream-vbs-requests`)
|
||||
|
||||
- **Batch A (`adfc854`, `VL-002`, `VL-008`, `VL-009`, `VL-012`, `VL-013`)**:
|
||||
- Reserved `kNetErrorDomain = 26`; enforced `PascalCase` types / `snake_case` methods naming (`VL-012`); added strict RFC 3629/8259 UTF-8 validation in `StrictJson`, `Semver` shorthand comparators (`^1`, `^1.0`, `~1.2`, `>=1.2 <2`), header-only `Data/Toml.hpp` TOML 1.0 parser/serializer with `Origin`, and zero-CMake self-registering `VOID_TEST*` macros.
|
||||
- Verified (`Data;Text;Testing`, `-Werror`): `690 tests (687 ✔, 3 ⊘)` in `351.9ms`; pure `g++` multi-file stem-collision binary `4/4` (`0.1ms`).
|
||||
- **Batch B (`b50131f`, `VL-001`, `VL-003`, `VL-010`, `VL-011`)**:
|
||||
- Full process-group supervision (`PR_SET_CHILD_SUBREAPER`, `waitpid(-pgid)`, `SIGKILL` escalation), `FileLock` / `atomic_symlink_swap` / `reflink_copy_file` / `set_timestamps_nofollow`, Linux `inotify` recursive `DirectoryWatcher`, `Argparse` subcommands/`option_many`/`positional_many`/`ParseOutcome`, top-level `LANGUAGES C CXX`, and FetchContent SQLite3 amalgamation fallback.
|
||||
- Verified (`/tmp/void-vbs-b`, `-Werror`): `791 tests (788 ✔, 3 ⊘)` in `1.72s`, `ctest` `2/2` (`14.44s` incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`).
|
||||
- **Batch C (`22c8538`, `VL-006`, `VL-007`)**:
|
||||
- Optional `OpenSSL::Crypto` (`VOID_CRYPTO_HAS_OPENSSL`) + pure-C++ FIPS 180-4 SHA-1/256/512 & RFC 7693 BLAKE2b-256/512 + HMAC/HKDF + `snake_case` aliases; optional `LibArchive` (`VOID_ARCHIVE_HAS_LIBARCHIVE`) + pure-C++ USTAR/PAX tar & deterministic `ArchiveCompression::Gzip` + `create()`.
|
||||
- Verified zero-OpenSSL (`534 ✔ / 3 ⊘`, `ctest` `2/2` `5.59s`), zero-LibArchive (`405 ✔ / 3 ⊘`, `ctest` `2/2` `6.22s`), and full backends (`888 ✔ / 3 ⊘`, `ctest` `2/2` `15.53s`).
|
||||
- **Batch D (`66baae7`, `VL-004`, `VL-005`) + TSan/race fix (`9920bfd`)**:
|
||||
- POSIX TCP HTTP/1.1 `HttpServer`, streaming `HttpClient` + `HttpClient::secure()` TLS >= 1.2 + CA/SAN verification + cross-origin/downgrade/redaction + `std::stop_token` cancellation + `NetOnly` consumer (`66baae7`); scoped GCC `-Wno-tsan` to `src/Net/Http.cpp` and fixed `StallServer` join order (`9920bfd`).
|
||||
- Verified `Net;System;Crypto;Testing` (`563 ✔ / 3 ⊘`, `ctest` `2/2` `8.48s` incl. `NetOnly`).
|
||||
- **Full-suite & sanitizer checks**:
|
||||
- Full RelWithDebInfo (`/tmp/void-vbs-full`, 45 modules, `-Werror`): `VoidTests` `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `21.94s` (`22.09s` post-`9920bfd`), `ctest` `2/2` in `82.82s` (`VoidTests` `22.03s`, `VoidInstalledComponentConsumers` `60.79s` across all `35` consumers incl. `NetOnly`), `VoidFoundationBench` (`rev=66baae74a0b7`) recorded.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-vbs-asan`, 45 modules, `-Werror`): `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB (+ post-`9920bfd` `Http|Net|Server` `9/9 ✔` in `1.58s`).
|
||||
- Debug TSan (`/tmp/void-vbs-tsan`, `Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`, 17 modules, `-Werror`): `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings.
|
||||
|
||||
### Wave 9 — P2 Completion: `Net`, `TestingMock`, `ShortUrl`, `RPC` (`feat/roadmap-p2-wave9`)
|
||||
|
||||
- **Specs & Error Domains (`700024a`)**: authored `M-NET-01-05.md`, `M-TESTINGMOCK-01-04.md`, `M-SHORTURL-01-04.md`, `S-RPC-01-03.md`; reserved `kTestingMockErrorDomain = 27`, `kShortUrlErrorDomain = 28`, `kRpcErrorDomain = 29`, `kDiscoveryErrorDomain = 30`.
|
||||
- **`Net` P2 Hardening (`86d777e`, `M-NET-01..05`)**: native incremental RFC 9110/9112 `HttpRequestParser` / `HttpResponseParser`, bounded `ConnectionPool` (`PoolKey` origin+proxy+TLS generation, `MonotonicClock` idle eviction, RAII `ConnectionLease`), descriptor-pinned `StaticFileResolver::open_safe()` (`openat`+`O_NOFOLLOW`), `HttpClient` `303`/`307` redirect & single-deadline hardening, RFC 6455 `WebSocket` codec/decoder/`WebSocketClient` & `HttpServer::add_websocket_route()`.
|
||||
- **`TestingMock` P2 Hardening (`658c21a`, `M-TESTINGMOCK-01..04`)**: explicit `MockSession` (`freeze`, `verify_and_close`, `MockLimits`, `RegistrationToken`), `Sequence` order groups, action-outside-lock reservation (same-thread reentry + `ConcurrentActions`), perfect forwarding + `returns_once`/`invokes_once` move-only support, `never()`/`at_least`/`at_most`/`between`, matcher combinators (`Ne`, `EndsWith`, `IsNull`, `NotNull`, `NotOf`, `AllOf`, `AnyOf`, depth bound 32), `TestingMockOnly` consumer.
|
||||
- **`ShortUrl` P2 Completion (`691808e`, `M-SHORTURL-01..04`)**: preserved frozen `V1` ABI; added `Void::ShortUrl::V2` (`LocalProvider`, URL/key validation, base62 keys, civil expiry, tombstone non-reuse, 24h idempotency, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (pre-mutation capability checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer.
|
||||
- **`RPC` Subsystem (`5184d1c`, `S-RPC-01..03`)**: NEW `Void::RPC` module with Wire v1 deterministic binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` (`AuthHook`, schema check, timeout clamp, sanitized exceptions, `Registration::unregister_and_drain()`), `RpcOnly` consumer.
|
||||
- **Full-suite & sanitizer checks**:
|
||||
- Full integrated RelWithDebInfo (`/tmp/void-w9-full`, 48 modules, `-Werror`): `VoidTests` `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `23.56s`; `ctest` `2/2` in `91.13s` (`VoidTests` `23.27s`, `VoidInstalledComponentConsumers` `67.86s` across all `38` consumers); `VoidFoundationBench` (`rev=5184d1cf8cdd`) recorded.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w9-asan`, 48 modules, `-Werror`): `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB.
|
||||
- Debug TSan (`/tmp/void-w9-tsan`, `Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`, 22 modules, `-Werror`): `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings.
|
||||
|
||||
## 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–9 (`P0`, `P1`, all `P2` functional modules and `VL-001`..`VL-013`) are
|
||||
complete, verified, and merged to `main` via `--no-ff`. Next roadmap phase:
|
||||
**P3** (new single-node subsystems `Discovery`, `Scheduler`, `Messaging` +
|
||||
`NetworkedApplications` / `ReloadableApplications` platform integrations).
|
||||
@@ -59,6 +59,75 @@ 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) |
|
||||
|
||||
## Wave 6A — P2 System, SystemAsync, IPC (`feat/roadmap-p2-wave6a`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Wave 6A prep, error domains & helper modes | Reserved P2/P3 domain IDs (`kIpcErrorDomain = 16`..`kSqliteErrorDomain = 21`) in `Error.hpp`, thread-safe pipe `ENOTSOCK` fallback in `EpollDriver.cpp`, enabled `VoidProcessHelper` for `Void::System` OR `Void::IPC` with `ignore-sigterm`, `simultaneous-io`, `flood`, `long-line`, `check-fds`, `env-dump`, `cwd`, `ipc-pipe-echo`, task specs (`3f67b1e`) | — | VERIFIED | Compiled cleanly with `-Werror`; verified via Wave 6A `System`, `SystemAsync`, `IPC`, ASan+UBSan, and TSan suites |
|
||||
| M-SYSTEM-01..05 | Hardened `System` (`Types.hpp`, `Process.{hpp,cpp}`, `Path.hpp`, `Query.hpp`, `TempFile.hpp`, `TempDir.hpp`, `Metrics.hpp`), strict non-shell spawning + fd hygiene, pipe/arg limits, duplex `communicate()` & bounded escalation, `query_process` /proc validation, symlink-safe atomic `TempFile`/`TempDir`, `/bin/sh`-free `ProcessStream.cpp`, `SystemHardening.cpp`, `SystemOnly` consumer (`fcdbc06`) | [M-SYSTEM-01-05](tasks/M-SYSTEM-01-05.md) | VERIFIED | `System*` 53/53 (`226.6ms`), `ctest` 2/2 (`SystemOnly` `3.95s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `16/16` (0 races) |
|
||||
| M-SYSTEM-06 | Split async `SystemAsync` (`INTERNAL_DEPS System Async IO Time Functional LogState`, `EXTRA_HEADERS` `AsyncProcess.hpp`/`AsyncWatcher.hpp`), `ProcessManager`, `ManagedChild`, async `communicate`/`wait`/`close_and_join`, `WatcherService`/`WatchSubscription`, `SystemAsync.cpp`, `SystemAsyncOnly` consumer (`9a3c5d8`) | [M-SYSTEM-01-05](tasks/M-SYSTEM-01-05.md) | VERIFIED | `SystemAsync*` 2/2 (`211.5ms`), `ctest` 2/2 (`SystemAsyncOnly` `9.43s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `2/2` (0 races) |
|
||||
| S-IPC-01..03 | New `IPC` module (`src/IPC/module.cmake`, `Types.hpp`, `Codec.hpp`, `Transport.hpp`, `Session.hpp`, `IPC.hpp`), V1 `VDIP` 24B big-endian framing & pre-alloc `BufferQuota`/`QuotaPermit`, `LocalListener`/`connect_local` (`O_NOFOLLOW`, `0700`/`0600`, `flock`, `SO_PEERCRED` fail-closed), `adopt_pipe_pair`/`create_socket_pair_transports`, full-duplex `Session` with control lane/tombstones/token-bucket/graceful drain, `Ipc.cpp`, `IPCOnly` consumer (`39a48d5`) | [S-IPC-01-03](tasks/S-IPC-01-03.md) | VERIFIED | `Ipc*` 3/3 (`8.8ms`), `ctest` 2/2 (`IPCOnly` `12.20s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `3/3` (0 races) |
|
||||
|
||||
## Out-of-band Priority Fix (`main`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| StrictJson decimals | RFC 8259 decimal numbers (`double` variant alternative + `ParseOptions::allowDecimals = true`) in `Void::Json::Strict` (`include/Void/Data/StrictJson.hpp`, `tests/standalone/Data/StrictJson.cpp`) (`acd77ee`) | — | VERIFIED | `StrictJson` 6/6 (`49/49` Data suite, `ctest` 2/2), Debug ASan+UBSan `49/49` (0 leaks/UB); pushed to `origin/main` |
|
||||
|
||||
## Wave 6B — P2 Crypto, Security, Archive, Update (`feat/roadmap-p2-wave6b`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| M-CRYPTO-01..05 | Hardened `Crypto` (OpenSSL 3.5.9 non-deprecated `EVP_MD`/`EVP_MAC`/`EVP_KDF`/`EVP_PKEY`, poisoned `Hasher`, 16 MiB Ed25519 cap, 4 KiB HKDF cap & overlap/wipe guards, `constant_time_equal`, `secure_wipe`, `kCryptoErrorDomain = 18`) + optional `CryptoAsync` (`hash_stream`, `AsyncFileHasher` 8/32/8 MiB budget, `close_and_join`), `CryptoOnly` & `CryptoAsyncOnly` consumers (`8a1c15f`, `eb42228`) | [M-CRYPTO-01-05](tasks/M-CRYPTO-01-05.md) | VERIFIED | `Crypto` 3 + `CryptoHardening` 3 + `CryptoAsync` 2 = 8/8, `ctest` 2/2 (`7.22s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 8/8 (0 races) |
|
||||
| M-SECURITY-01..04 | Hardened `Security` (`kSecurityErrorDomain = 19`, `SecureBuffer` with lock policies & wipe counter, input caps, `parse_argon2id_cost`, `verify_password_budgeted`, `VSEC` v1 `xchacha20poly1305_ietf` `Envelope`/`SecretKeyRing` without legacy fallback, bounded default-deny `Authorization`) + `SecurityAsync` (`Authenticator`, `AccountSessionPort`, fail-closed `AuditSink`, `PasswordJobBudget`, `SessionPolicy`, dummy-hash parity, version CAS, `close_and_join`), `SecurityOnly` & `SecurityAsyncOnly` consumers (`713d2dc`) | [M-SECURITY-01-04](tasks/M-SECURITY-01-04.md) | VERIFIED | `SecurityTests` 8 + `SecurityHardening` 4 + `SecurityAsync` 2 = 14/14 (`720.7ms`), `ctest` 2/2 (`8.46s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 14/14 (0 races) |
|
||||
| M-ARCHIVE-01..05 | Hardened `Archive` (`kArchiveErrorDomain = 17`, streaming `Reader` + forensic listing, file-as-parent conflict rejection, exclusive `0700` `StagedTree` + bottom-up `fsync` + Linux `SYS_renameat2(RENAME_NOREPLACE)` atomic `publish()` with `PublicationOutcome::Unknown`, `cleanup_stale_staging`, reproducible `O_NOFOLLOW` `create_archive`, isolated `VoidArchiveWorker` extraction with rlimits + RSS check + parent inventory verification), `ArchiveOnly` consumer (`00d7478`) | [M-ARCHIVE-01-05](tasks/M-ARCHIVE-01-05.md) | VERIFIED | `Archive` 6 + `ArchiveHardening` 3 = 9/9 (`259.0ms`), `ctest` 2/2 (`5.76s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 9/9 (0 races) |
|
||||
| M-UPDATE-01..06 | Hardened `Update` (`kUpdateErrorDomain = 20`, schema-3 verify-before-payload-parse fix, `StrictJsonProfile` integer-only option, non-forgeable `VerifiedSelection`, `VersionStore::pruneWithPins`, atomic checksummed `ReplayFloorStore`, Ed25519 `TrustStore` rotation/revocation, `ArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` halting with `RecoveryRequired`, `InstallCoordinator` with staged archive + `CleanupPending` + idempotent `reconcile`/`retry_cleanup`), `UpdateOnly` consumer (`47736cb`) | [M-UPDATE-01-06](tasks/M-UPDATE-01-06.md) | VERIFIED | `Update` 22 + `UpdateHardening` 3 = 25/25 (`1.91s`), `ctest` 2/2 (`10.64s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 25/25 (0 races) |
|
||||
|
||||
## Wave 7 — P2 Sqlite, SqliteAsync, and Storage (`feat/roadmap-p2-wave7`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| M-SQLITE-01..05 | Hardened `Sqlite` (`kSqliteErrorDomain = 21`, `ConnectionState`, `OpenOptions` checked WAL/FULL/FK pragmas & disabled extension loading, checked binds & borrowed lifetime owners, typed `RowView`, `Transaction` autocommit/busy guards, `Savepoint`, `migrate_checked`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, TSan lock-order fix outside `interrupt_mu`) + optional `SqliteAsync` (`AsyncPool`), `SqliteOnly` & `SqliteAsyncOnly` consumers (`427cc9a`, `84e6fe8`) | [M-SQLITE-01-05](tasks/M-SQLITE-01-05.md) | VERIFIED | Standalone `Sqlite` 14/14 (`426.5ms`), `ctest` 2/2 (`5.11s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) |
|
||||
| S-STORAGE-01..06 | NEW original `Void::Storage` (`kStorageErrorDomain = 9`, zero SQLite/external deps, `Crc32c`, `PosixFilePort`/`FaultInjectingFilePort`, V1 `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1` codecs, `Batch` preconditions, single-writer `Engine` with recovery/tail-truncation/checkpoint/compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance), `G-STORE` gate, `StorageOnly` consumer (`fdf0da5`) | [S-STORAGE-01-06](tasks/S-STORAGE-01-06.md) | VERIFIED | Standalone zero-ext-deps `Storage` 5/5 (`14.53s`), `ctest` 2/2 (`24.07s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) |
|
||||
|
||||
## Wave 8 — P2 Service, Plugin, Configuration, and Fsm (`feat/roadmap-p2-wave8`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| M-SERVICE-01..05 | Hardened `Service` (`kServiceErrorDomain = 22`, immutable `ServiceSnapshot`, owning `ServiceHandle<I>`, transactional DAG `ProviderSet`/`prepare_batch`/`start_staged`/`publish`/`start_and_publish`/`close_and_join`, retained generation cap) + split `ServicePlugin` (`acquire_plugin_service<I>`, `PluginServiceBinding`), `ServiceOnly` & `ServicePluginOnly` consumers (`6b3dede`, `1474a69`) | [M-SERVICE-01-05](tasks/M-SERVICE-01-05.md) | VERIFIED | Standalone `Service;ServicePlugin;Testing` 18/18, `ctest` 2/2 (`7.47s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
|
||||
| M-PLUGIN-01..06 | Hardened `Plugin` (`kPluginErrorDomain = 23`, pure-C11 `CAbi.h` v1, `CModuleHost` activity pins/quiesce/checkpoint/replace/degraded state/retention/byte budgets/dep topological batching, `CAbiAdapter`, unlocked `PluginManager` staging), `PluginOnly` consumer (`a24e086`, `1a54f38`) | [M-PLUGIN-01-06](tasks/M-PLUGIN-01-06.md) | VERIFIED | Standalone `Plugin;ServicePlugin;Testing` 32 ✔ / 1 skip (`194.5ms`), `ctest` 2/2 (`9.45s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
|
||||
| M-CONFIGURATION-01..05 | Hardened `Configuration` (`kConfigurationErrorDomain = 24`, `Bind.hpp` attributes, bounded `Schema<T>` reflection/provenance/redaction/deprecation checks) + split `ConfigurationAsync` (transactional `ReloadController<T>`, `Snapshot<T>`, `prepare_external`, coalescing `WatcherService` integration), `ConfigurationOnly` & `ConfigurationAsyncOnly` consumers (`1dc51d5`) | [M-CONFIGURATION-01-05](tasks/M-CONFIGURATION-01-05.md) | VERIFIED | Standalone `ConfigurationAsync;Testing` `Configuration*` 6/6 (`0.7ms`), `ctest` 2/2 (`13.75s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
|
||||
| M-FSM-01..05 | Hardened `Fsm` (`kFsmErrorDomain = 25`, shared `terminal(Status)` incl. `Faulted`, `TerminationReason`, `FsmLimits` bounds & reserved control lane, `MonotonicClock` & borrowed `ExecutionBinding`, per-state stop scopes & waiter/timer purge before `on_exit()`, `run_parallel_structured` / `run_parallel_any_structured` loser stop+join & tie-break, boundary `request_checkpoint` / `safe_point` / `restore_checkpoint` / `restore_legacy_checkpoint`, `acquire_service<I>()`, hardened `Orchestrator` `StopOnFault`/`BoundedRestart` & `FsmModel::~FsmModel()` worker join), `FsmOnly` consumer (`ef5312c`, `40b579d`, `cb988fa`) | [M-FSM-01-05](tasks/M-FSM-01-05.md) | VERIFIED | Standalone `Fsm;Testing` 814 ✔ / 2 skips (`789.1ms`), `ctest` 2/2 (`9.59s`), Debug TSan 1,107 ✔ (0 races, `internal_FsmServiceHotReload` 4/4), full RelWithDebInfo (`1,434 ✔`, `ctest` 2/2 `77.11s`), ASan+UBSan (`1,434 ✔`, 0 leaks/UB) |
|
||||
|
||||
## VoidBuildSystem Upstream Requests (`VL-001`..`VL-013`, `feat/upstream-vbs-requests`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| VL-002, VL-008, VL-009, VL-012, VL-013 | `Data/Toml.hpp` (TOML 1.0 parser/serializer + `Origin`), strict RFC 3629/8259 UTF-8 in `StrictJson`, zero-CMake self-registering `VOID_TEST*` macros, `Semver` shorthand comparators (`^1`, `^1.0`, `~1.2`, `>=1.2 <2`), `PascalCase`/`snake_case` naming (`VL-012`), `kNetErrorDomain = 26` (`adfc854`) | — | VERIFIED | Standalone `Data;Text;Testing` `-Werror` `687 ✔ / 3 ⊘` (`351.9ms`); pure `g++` zero-CMake multi-file stem collision binary `4/4` (`0.1ms`), `--list`, `--filter from_dir_b` `1/1`; full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
|
||||
| VL-001, VL-003, VL-010, VL-011 | Process-group supervision (`PR_SET_CHILD_SUBREAPER`, `waitpid(-pgid)`, leader-exit `SIGKILL` escalation), `FileLock` / `atomic_symlink_swap` / `reflink_copy_file` / `set_timestamps_nofollow`, Linux `inotify` recursive `DirectoryWatcher`, `Argparse` subcommands/`option_many`/`positional_many`/`ParseOutcome`, top-level `LANGUAGES C CXX` & FetchContent SQLite3 amalgamation (`b50131f`) | — | VERIFIED | Standalone `/tmp/void-vbs-b` `-Werror` `788 ✔ / 3 ⊘` (`1.72s`), `ctest` `2/2` (`14.44s`, incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`); full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
|
||||
| VL-006, VL-007 | Optional `OpenSSL::Crypto` (`VOID_CRYPTO_HAS_OPENSSL`) + pure-C++ FIPS 180-4 SHA-1/256/512 & RFC 7693 BLAKE2b-256/512 + HMAC/HKDF + `snake_case` hash aliases (`22c8538`); optional `LibArchive` (`VOID_ARCHIVE_HAS_LIBARCHIVE`) + pure-C++ USTAR/PAX tar & deterministic `ArchiveCompression::Gzip` + `create()` (`22c8538`) | — | VERIFIED | Zero-OpenSSL `534 ✔ / 3 ⊘` (`1.09s`, `ctest` `2/2` `5.59s`); zero-LibArchive `405 ✔ / 3 ⊘` (`1.45s`, `ctest` `2/2` `6.22s`); full-backend `888 ✔ / 3 ⊘` (`3.70s`, `ctest` `2/2` `15.53s`); full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
|
||||
| VL-004, VL-005 | POSIX TCP HTTP/1.1 `HttpServer` (`query`, `file_body`/`from_file`, `Router::allowed_methods`, `bound_port`, `431`/`413`, TE+CL smuggling `400`, streaming `BodyReader`, `HEAD`->`GET`, `shutdown`), streaming `HttpClient` + `HttpClient::secure()` TLS >= 1.2 + CA/SAN + cross-origin/downgrade/redaction + `NetErrorCode` (`kNetErrorDomain = 26`) + `std::stop_token` + `NetOnly` consumer (`66baae7`) + TSan `-Wno-tsan` scope & `StallServer` fix (`9920bfd`) | — | VERIFIED | Standalone `Net;System;Crypto;Testing` `563 ✔ / 3 ⊘` (`2.36s`), `ctest` `2/2` (`8.48s` incl. `NetOnly`); Debug TSan `954 ✔ / 3 ⊘` (`10.65s`, `0` races); full RelWithDebInfo `1,452 ✔ / 4 ⊘` (`22.09s`), `ctest` `2/2` (`82.82s`, `35` consumers); ASan+UBSan `1,452 ✔` (`39.11s`) + `Http\|Net\|Server` `9/9` (`1.58s`, `0` leaks/UB) |
|
||||
|
||||
## Wave 9 — P2 Completion: Net, TestingMock, ShortUrl, RPC (`feat/roadmap-p2-wave9`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| M-NET-01..05 | Native incremental RFC 9110/9112 `HttpRequestParser` / `HttpResponseParser` (smuggling rejection, 1xx/HEAD/chunked/trailers/EOF), bounded `ConnectionPool` (`PoolKey` origin+proxy+TLS generation, `MonotonicClock` idle eviction, RAII `ConnectionLease`), descriptor-pinned `StaticFileResolver::open_safe()` (`openat`+`O_NOFOLLOW`), `HttpClient` `303`/`307` redirect & single-deadline hardening, RFC 6455 `WebSocket` codec/decoder/`WebSocketClient` & `HttpServer::add_websocket_route()` (`86d777e`) | [M-NET-01-05](tasks/M-NET-01-05.md) | VERIFIED | Standalone `Net;System;Crypto;TestingMock;Testing` `44/44 ✔` (`1.31s`), `ctest` `2/2` (`10.96s` incl. `NetOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔ / 4 ⊘` (`23.56s`, `ctest` `2/2` `91.13s`, `38` consumers); ASan+UBSan `1,466 ✔` (`41.95s`, `0` leaks/UB) |
|
||||
| M-TESTINGMOCK-01..04 | Explicit `MockSession` (`kTestingMockErrorDomain = 27`, `freeze(SingleThread\|ConcurrentActions)`, `verify_and_close()`, `MockLimits`, `RegistrationToken`), `Sequence` order groups, action-outside-lock reservation (same-thread reentry + concurrent actions), perfect forwarding + `returns_once`/`invokes_once` move-only support, `never()`/`at_least`/`at_most`/`between`, matcher combinators (`Ne`, `EndsWith`, `IsNull`, `NotNull`, `NotOf`, `AllOf`, `AnyOf`, depth bound 32), `TestingMockOnly` consumer (`658c21a`) | [M-TESTINGMOCK-01-04](tasks/M-TESTINGMOCK-01-04.md) | VERIFIED | Standalone `TestingMock*` 18/18 ✔ + `ctest` `TestingMockOnly`; Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
|
||||
| M-SHORTURL-01..04 | Frozen `V1` ABI preserved + additive `Void::ShortUrl::V2` (`kShortUrlErrorDomain = 28`, URL/key validation, base62 rejection-sampled keys, civil expiry, tombstone non-reuse, 24h idempotency, `LocalProvider`, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (capability pre-checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer (`691808e`) | [M-SHORTURL-01-04](tasks/M-SHORTURL-01-04.md) | VERIFIED | Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing` `ShortUrl*` 5/5 ✔, `ctest` `2/2` (`36.84s` incl. `ShortUrlOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
|
||||
| S-RPC-01..03 | NEW `Void::RPC` subsystem (`kRpcErrorDomain = 29`), Wire v1 big-endian binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` with `AuthHook`, schema negotiation, timeout clamping, sanitized handler exceptions, `Registration::unregister_and_drain()`, `RpcOnly` consumer (`5184d1c`) | [S-RPC-01-03](tasks/S-RPC-01-03.md) | VERIFIED | Standalone `Rpc` 2/2 ✔, `ctest` `2/2` (`36.84s` incl. `RpcOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`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
|
||||
|
||||
@@ -215,3 +215,85 @@ 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 |
|
||||
|
||||
## Wave 6A / P2 System, SystemAsync, IPC Verification (2026-11-24)
|
||||
|
||||
Branch: `feat/roadmap-p2-wave6a` (branched from `main` at `4479960`, 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 |
|
||||
| --- | --- | --- |
|
||||
| M-SYSTEM-01..05 (`3f67b1e`, `fcdbc06`) | `System;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-system` (`VoidTests --filter "System*"`, `ctest`) | `System*` 53/53 passed (226.6ms); `ctest` 2/2 passed (`VoidTests` 0.57s, `VoidInstalledComponentConsumers` including `SystemOnly` 3.95s) |
|
||||
| M-SYSTEM-06 (`9a3c5d8`) | `SystemAsync;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-sysasync` (`VoidTests --filter "SystemAsync*"`, `ctest`) | `SystemAsync*` 2/2 passed (211.5ms); `ctest` 2/2 passed (`VoidTests` 1.15s, `VoidInstalledComponentConsumers` including `SystemAsyncOnly` 9.43s) |
|
||||
| S-IPC-01..03 (`39a48d5`) | `IPC;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-ipc` (`VoidTests --filter "Ipc*"`, `ctest`) | `Ipc*` 3/3 passed (8.8ms); `ctest` 2/2 passed (`VoidTests` 0.49s, `VoidInstalledComponentConsumers` including `IPCOnly` 12.20s, total 12.70s) |
|
||||
| Full Integrated RelWithDebInfo (`39a48d5`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w6a-full`, 39 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w6a-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w6a-full --output-on-failure --timeout 300` | `VoidTests`: 1,386 tests — 1,383 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (4.68s); `ctest`: 2/2 passed (`VoidTests` 4.58s + `VoidInstalledComponentConsumers` 31.05s across 19 consumer runs incl. `SystemOnly`, `SystemAsyncOnly`, `IPCOnly`, `RelocatedFoundation`, `RelocatedExternal`, total 35.63s) |
|
||||
| Full Integrated ASan+UBSan (`39a48d5`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6a-asan`, 39 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-asan/tests/VoidTests` | 1,386 tests — 1,383 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (19.34s), 0 ASan/LSan leaks, 0 UBSan errors |
|
||||
| Wave 6A TSan Subset (`39a48d5`) | `dev cpp-gcc -c` Debug (`SystemAsync;IPC;IO;Async;Resilience;Testing`, `/tmp/void-w6a-tsan`, 14 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-tsan/tests/VoidTests --filter "Process*\|SystemHardening*\|SystemAsync*\|Ipc*\|FileWatcher*\|IoDriver*\|OperationScope*"` | 35/35 passed (609.4ms: `OperationScope` 5, `IoDriver` 4, `Ipc` 3, `FileWatcher` 5, `Process` 10, `ProcessStream` 3, `SystemHardening` 3, `SystemAsync` 2), 0 TSan data races |
|
||||
| Post-W6A Benchmark (`39a48d5`, `rev=39a48d5c0a72`) | `/tmp/void-w6a-full/benchmarks/VoidFoundationBench --json /tmp/void-w6a-full/post-w6a.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.92ns, `core_uuid_to_string` 17.45ns, `core_hash_fnv1a64_256b` 181.41ns, `core_hash_murmur3_256b` 67.93ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.77ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.61ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 311.16ns, `data_json_serialize_small_object` 162.52ns |
|
||||
|
||||
## StrictJson RFC 8259 Decimal Verification (2026-11-25)
|
||||
|
||||
Branch: `main` (`acd77ee`, 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 |
|
||||
| --- | --- | --- |
|
||||
| StrictJson decimals (`acd77ee`) | RelWithDebInfo `-Werror` Data suite & `ctest`, plus Debug ASan+UBSan `-Werror` (`/tmp/void-strictjson-asan`) | RelWithDebInfo: `49/49` (`StrictJson` 6/6), `ctest` 2/2 passed; Debug ASan+UBSan: `49/49` (7.0ms), 0 leaks, 0 UB |
|
||||
|
||||
## Wave 6B / P2 Crypto, Security, Archive, Update Verification (2026-11-25)
|
||||
|
||||
Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2, OpenSSL 3.5.9, libsodium 1.0.22, libarchive 3.8.10, SQLite 3.54.0.
|
||||
|
||||
| Scope | Command & configuration | Observed outcome |
|
||||
| --- | --- | --- |
|
||||
| M-CRYPTO-01..05 (`8a1c15f`, `eb42228`) | `Crypto;CryptoAsync;Testing` RelWithDebInfo `-Werror` `-p openssl` `/tmp/void-w6b-crypto` (10 modules, `VoidTests`, `ctest`) | `CryptoHardening` 3 + `CryptoAsync` 2 (+ `Crypto` 3) passed; `ctest` 2/2 passed (`7.22s`, incl. `CryptoOnly` & `CryptoAsyncOnly`) |
|
||||
| M-SECURITY-01..04 (`713d2dc`) | `Security;SecurityAsync;Testing` RelWithDebInfo `-Werror` `-p libsodium` `/tmp/void-w6b-security` (10 modules, `VoidTests`, `ctest`) | `Security*\|security_*` 14/14 passed (`720.7ms`: `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2); `ctest` 2/2 passed (`8.46s`, incl. `SecurityOnly` & `SecurityAsyncOnly`) |
|
||||
| M-ARCHIVE-01..05 (`00d7478`) | `Archive;Testing` RelWithDebInfo `-Werror` `-p libarchive` `/tmp/void-w6b-archive` (7 modules, `VoidTests`, `ctest`) | `Archive*\|archive_*` 9/9 passed (`259.0ms`: `Archive` 6, `ArchiveHardening` 3); `ctest` 2/2 passed (`5.76s`, incl. `ArchiveOnly`) |
|
||||
| M-UPDATE-01..06 (`47736cb`) | `Update;Testing` RelWithDebInfo `-Werror` `-p libarchive -p openssl` `/tmp/void-w6b-update` (12 modules, `VoidTests`, `ctest`) | `Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*` 25/25 passed (`1.91s`: `Update` 22, `UpdateHardening` 3); `ctest` 2/2 passed (`10.64s`, incl. `UpdateOnly`) |
|
||||
| Full Integrated RelWithDebInfo (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w6b-full`, 41 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w6b-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w6b-full --output-on-failure --timeout 300` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`6.26s`); `ctest`: 2/2 passed (`VoidTests` 7.34s + `VoidInstalledComponentConsumers` 40.73s across 25 consumer runs incl. `CryptoOnly`, `CryptoAsyncOnly`, `SecurityOnly`, `SecurityAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `RelocatedFoundation`, `RelocatedExternal`, total `48.07s`) |
|
||||
| Full Integrated ASan+UBSan (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6b-asan`, 41 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-w6b-asan/tests/VoidTests` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`21.78s`), 0 ASan/LSan leaks, 0 UBSan errors |
|
||||
| Wave 6B TSan Subset (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p libsodium` Debug (`CryptoAsync;SecurityAsync;Update;Testing`, `/tmp/void-w6b-tsan`, 20 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6b-tsan/tests/VoidTests --filter "Crypto*\|crypto_*\|Security*\|security_*\|Archive*\|archive_*\|Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*"` | 56/56 passed (`4.86s`: `Archive` 6, `ArchiveHardening` 3, `Crypto` 3, `CryptoHardening` 3, `CryptoAsync` 2, `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2, `Update` 22, `UpdateHardening` 3), 0 TSan data races |
|
||||
| Post-W6B Benchmark (`47736cb`, `rev=47736cb6ce2f`) | `/tmp/void-w6b-full/benchmarks/VoidFoundationBench --json /tmp/void-w6b-full/post-w6b.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.52ns, `core_uuid_to_string` 16.53ns, `core_hash_fnv1a64_256b` 179.95ns, `core_hash_murmur3_256b` 67.37ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 58.37ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.76ns, `containers_lru_get_put` 21.02ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 333.32ns, `data_json_serialize_small_object` 165.99ns |
|
||||
| Wave 7 `Sqlite` & `SqliteAsync` standalone (`84e6fe8`) | `dev cpp-gcc -p sqlite` RelWithDebInfo (`-Werror`, `/tmp/void-w7-sqlite`), 8 modules, `VoidTests --filter 'Sqlite*\|...'` + `ctest` | **PASSED**: `SqliteTests` 8 + `SqliteHardening` 4 + `SqliteAsync` 2 = 14/14 in `426.5ms`; `ctest` 2/2 in `5.11s` (`VoidTests` 0.87s, `VoidInstalledComponentConsumers` including `SqliteOnly` & `SqliteAsyncOnly` 4.23s) |
|
||||
| Wave 7 `Storage` standalone (`fdf0da5`, `G-STORE`) | `dev cpp-gcc` zero `-p` external deps RelWithDebInfo (`-Werror`, `/tmp/void-w7-storage`), 10 modules, `VoidTests --filter '^storage_'` + `ctest` | **PASSED**: `Storage` 5/5 in `14.53s`; `ctest` 2/2 in `24.07s` (`StorageOnly` verified with Boost/LibArchive/OpenSSL/PkgConfig/SQLite3/Threads disabled) |
|
||||
| Wave 7 TSan (`84e6fe8`) | `dev cpp-gcc -p sqlite` Debug TSan (`-Werror`, `/tmp/void-w7-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 12 modules (`SqliteAsync;Storage;Testing`) | **PASSED**: 19/19 in `15.38s` (`SqliteTests` 8, `SqliteHardening` 4, `SqliteAsync` 2, `Storage` 5), exit 0, 0 TSan data races / lock-order warnings |
|
||||
| Wave 7 integrated RelWithDebInfo + consumers (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w7-full`), 43 modules, `VoidTests` + `ctest` | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `21.06s`; `ctest` 2/2 in `65.05s` (`VoidTests` 20.95s, all 28 installed consumers 44.10s) |
|
||||
| Wave 7 full Debug ASan+UBSan (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w7-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 43 modules | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `36.47s`, 0 leaks, 0 UB |
|
||||
| Post-W7 Benchmark (`84e6fe8`, `VOID_GIT_REV=fdf0da5ca883`) | `/tmp/void-w7-full/benchmarks/VoidFoundationBench --json /tmp/void-w7-full/post-w7.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 25.06ns, `core_uuid_to_string` 16.69ns, `core_hash_fnv1a64_256b` 181.03ns, `core_hash_murmur3_256b` 67.90ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.24ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.62ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 310.70ns, `data_json_serialize_small_object` 160.98ns |
|
||||
| Wave 8 `Service` & `ServicePlugin` standalone (`1474a69`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-service`, `Service;ServicePlugin;Testing`), `VoidTests` + `ctest` | **PASSED**: `18/18` in `0.4ms`; `ctest` `2/2` in `7.47s` (`ServiceOnly` & `ServicePluginOnly` consumers) |
|
||||
| Wave 8 `Plugin` standalone (`a24e086`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-plugin`, `Plugin;ServicePlugin;Testing`), 9 pure-C11 `-Werror` fixtures + `VoidTests` + `ctest` | **PASSED**: `33 tests` (`32 ✔`, `1 ⊘` `plugin_load_and_query_skipped`, `0 ✘`) in `194.5ms`; `ctest` `2/2` in `9.45s` (`PluginOnly` consumer) |
|
||||
| Wave 8 `Configuration` & `ConfigurationAsync` standalone (`1dc51d5`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-config`, `ConfigurationAsync;Testing`), `VoidTests --filter 'Configuration'` + `ctest` | **PASSED**: `ConfigurationHardening` 3/3 + `ConfigurationAsync` 3/3 = `6/6` in `0.7ms`; `ctest` `2/2` in `13.75s` (`ConfigurationOnly` & `ConfigurationAsyncOnly` consumers) |
|
||||
| Wave 8 `Fsm` standalone (`ef5312c`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-fsm`, `Fsm;Testing`), `VoidTests` + `ctest` | **PASSED**: `816 tests` (`814 ✔`, `2 ⊘`, `0 ✘`) in `789.1ms`; `ctest` `2/2` in `9.59s` (`FsmOnly` consumer) |
|
||||
| Wave 8 TSan (`cb988fa`) | `dev cpp-gcc` Debug TSan (`-Werror`, `/tmp/void-w8-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 20 modules (`ServicePlugin;ConfigurationAsync;Fsm;Testing`), `VoidTests` | **PASSED**: `1,110 tests` (`1,107 ✔`, `3 ⊘` skipped, `0 ✘`) in `11.49s` (incl. `ServiceHardening` 5/5, `PluginHardening` 5/5, `Configuration*` 6/6, `FsmHardening` 4/4, `internal_FsmServiceHotReload` 4/4), exit `0`, `0` TSan warnings |
|
||||
| Wave 8 integrated RelWithDebInfo + consumers (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w8-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `20.99s`; `ctest` `2/2` in `77.11s` (`VoidTests` `20.97s`, all `34` installed consumers `56.13s`) |
|
||||
| Wave 8 full Debug ASan+UBSan (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w8-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `37.13s`, `0` leaks, `0` UB |
|
||||
| Post-W8 Benchmark (`cb988fa`, `rev=cb988fa98509`) | `/tmp/void-w8-full/benchmarks/VoidFoundationBench --json /tmp/void-w8-full/post-w8.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns |
|
||||
| Batch A `VL-002`/`008`/`009`/`012`/`013` (`adfc854`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-a`, `Data;Text;Testing`) + pure `g++` zero-CMake multi-file stem collision binary (`tests/package/TestingNativeGxx/{dir_a,dir_b}/dup.cpp`) | **PASSED**: `VoidTests` `690 tests` (`687 ✔`, `3 ⊘`, `0 ✘`) in `351.9ms`; pure `g++` `4/4` (`0.1ms`), `--list`, `--filter from_dir_b` `1/1` |
|
||||
| Batch B `VL-001`/`003`/`010`/`011` (`b50131f`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-b`, FetchContent SQLite3 amalgamation), `VoidTests` + `ctest` | **PASSED**: `VoidTests` `791 tests` (`788 ✔`, `3 ⊘`, `0 ✘`) in `1.72s`; `ctest` `2/2` in `14.44s` (`VoidTests` `1.76s`, `VoidInstalledComponentConsumers` `12.68s` incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`) |
|
||||
| Batch C zero-OpenSSL `VL-007` (`22c8538`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-no-openssl`, `-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE`, `Crypto;System;Text;Testing`) | **PASSED**: `VoidTests` `537 tests` (`534 ✔`, `3 ⊘`, `0 ✘`) in `1.09s`; `ctest` `2/2` in `5.59s` incl. `CryptoOnly` |
|
||||
| Batch C zero-LibArchive `VL-006` (`22c8538`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-no-libarchive`, `-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE`, `Archive;Testing`) | **PASSED**: `VoidTests` `408 tests` (`405 ✔`, `3 ⊘`, `0 ✘`) in `1.45s`; `ctest` `2/2` in `6.22s` incl. `ArchiveOnly` |
|
||||
| Batch C full backends `VL-006`/`007` (`22c8538`) | `dev cpp-gcc -p libarchive -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-c`, `Crypto;CryptoAsync;Archive;Update;Testing`) | **PASSED**: `VoidTests` `891 tests` (`888 ✔`, `3 ⊘`, `0 ✘`) in `3.70s`; `ctest` `2/2` in `15.53s` incl. `CryptoOnly`, `CryptoAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `Audited` |
|
||||
| Batch D `VL-004`/`005` (`66baae7`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-d`, `Net;System;Crypto;Testing`) | **PASSED**: `VoidTests` `566 tests` (`563 ✔`, `3 ⊘`, `0 ✘`) in `2.36s`; `ctest` `2/2` in `8.48s` (`VoidTests` `2.39s`, `VoidInstalledComponentConsumers` `6.09s` incl. `NetOnly`) |
|
||||
| Integrated RelWithDebInfo + consumers (`66baae7`, `9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `21.94s`; `ctest` `2/2` in `82.82s` (`VoidTests` `22.03s`, `VoidInstalledComponentConsumers` `60.79s` across all `35` consumers incl. `NetOnly`); post-`9920bfd` rebuild `VoidTests` `1,456` (`1,452 ✔`, `4 ⊘`) in `22.09s` |
|
||||
| Full Debug ASan+UBSan (`66baae7`, `9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-vbs-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB; post-`9920bfd` incremental `--filter 'Http\|Net\|Server'` `9/9 ✔` in `1.58s` |
|
||||
| Debug TSan (`9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug TSan (`-Werror`, `/tmp/void-vbs-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 17 modules (`Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`) | **PASSED**: `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings |
|
||||
| Post-VBS Benchmark (`66baae7`, `rev=66baae74a0b7`) | `/tmp/void-vbs-full/benchmarks/VoidFoundationBench --json /tmp/void-vbs-full/post-vbs.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 26.35ns, `core_uuid_to_string` 18.33ns, `core_hash_fnv1a64_256b` 185.86ns, `core_hash_murmur3_256b` 69.58ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 59.59ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.97ns, `containers_lru_get_put` 21.17ns, `binary_reader_u64_be` 1.34ns, `data_json_parse_small_object` 316.05ns, `data_json_serialize_small_object` 174.83ns |
|
||||
| Wave 9 `Net` & `TestingMock` standalone (`86d777e`, `658c21a`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w9-net`, `Net;System;Crypto;TestingMock;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `44/44 ✔` in `1.31s` (`NetHardening` 5/5, `SessionHardening` 4/4, all legacy Net/TestingMock suites); `ctest` `2/2` in `10.96s` (`VoidTests` `2.46s`, `VoidInstalledComponentConsumers` `8.50s` incl. `NetOnly` & `TestingMockOnly`) |
|
||||
| Wave 9 `ShortUrl` & `RPC` standalone (`691808e`, `5184d1c`) | `dev cpp-gcc -p openssl -p libsodium -c` RelWithDebInfo (`-Werror`, `/tmp/void-w9-shorturl-rpc`, `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `7/7 ✔` in `1.20s` (`Rpc` 2/2, `ShortUrl` 2/2, `ShortUrlV2` 1/1, `StorageRepository` 1/1, `RemoteProvider` 1/1); `ctest` `2/2` in `36.84s` (`VoidTests` `17.31s`, `VoidInstalledComponentConsumers` `19.54s` incl. `ShortUrlOnly` & `RpcOnly`) |
|
||||
| Wave 9 integrated RelWithDebInfo + consumers (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w9-full`), 48 modules, `VoidTests` + `ctest` | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `23.56s`; `ctest` `2/2` in `91.13s` (`VoidTests` `23.27s`, `VoidInstalledComponentConsumers` `67.86s` across all `38` consumers incl. `NetOnly`, `TestingMockOnly`, `ShortUrlOnly`, `RpcOnly`) |
|
||||
| Wave 9 full Debug ASan+UBSan (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w9-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 48 modules | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB |
|
||||
| Wave 9 Debug TSan (`5184d1c`) | `dev cpp-gcc -p openssl -p libsodium` Debug TSan (`-Werror`, `/tmp/void-w9-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 22 modules (`Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`) | **PASSED**: `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings |
|
||||
| Post-W9 Benchmark (`5184d1c`, `rev=5184d1cf8cdd`) | `/tmp/void-w9-full/benchmarks/VoidFoundationBench --json /tmp/void-w9-full/post-w9.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.49ns, `core_uuid_parse_hyphenated` 25.02ns, `core_uuid_to_string` 16.55ns, `core_hash_fnv1a64_256b` 183.63ns, `core_hash_murmur3_256b` 69.12ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.06ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.93ns, `containers_lru_get_put` 21.47ns, `binary_reader_u64_be` 1.15ns, `data_json_parse_small_object` 297.72ns, `data_json_serialize_small_object` 172.85ns |
|
||||
@@ -0,0 +1,26 @@
|
||||
# Archive Streaming Reader, Atomic Staged Publication, Reproducible Creation & Child Isolation
|
||||
Task ID: M-ARCHIVE-01..05
|
||||
Phase: P2 (Wave 6B)
|
||||
Status: APPROVED
|
||||
Contracts: C-02, C-03, C-04, C-05, C-06, C-07
|
||||
|
||||
## 1. Context and baseline
|
||||
`Void::Archive` preserves the existing incremental `extract(path, destination, ExtractionOptions)` API and anti-traversal/symlink-swap/size-limit tests while adding typed error reporting (`kArchiveErrorDomain = 17`), bounded streaming `Reader` (`open_reader`, `next_entry`, `read_chunk`, `skip_entry`, normal/forensic `list_entries`), atomic staged extraction and no-replace directory publication (`StagedTree`, `extract_staged`, `publish`, `cleanup_stale_staging`), reproducible tar/tar.zstd creation (`create_archive`), and hardened child-process isolated extraction (`extract_staged_isolated`, `run_isolated_worker_main`).
|
||||
|
||||
## 2. Deliverables
|
||||
- `src/Archive/module.cmake` (`INTERNAL_DEPS Functional Time System`, `EXTERNAL_DEPS LibArchive::LibArchive`).
|
||||
- `include/Void/Archive/Types.hpp`: `kArchiveErrorDomain = 17`, `ArchiveErrorCode`, `make_archive_error`, `ReadLimits` (10,000 entries, 512 MiB file, 2 GiB total, 1 GiB compressed, 8 MiB metadata, 64 KiB transfer chunk, 4 KiB path, 255B component, 64 components), `EntryInfo`, `ProgressEvent`, `PublicationOutcome`, `PublicationReceipt`, `CreationOptions`, `IsolationOptions` (128 MiB RSS, 60s timeout), `ByteSource`/`ByteSink` + span/vector/file adapters.
|
||||
- `include/Void/Archive/Archive.hpp`, `src/Archive/Archive.cpp`, `src/Archive/StagedArchive.cpp`: preserve `extract()`; add `Reader`, `list_entries` (normal + opt-in forensic), `StagedTree`, `extract_staged` (exclusive `0700` dir, `O_NOFOLLOW`, `0644`/`0755`, bottom-up dir `fsync`, completion inventory, no-follow cleanup), `publish` via Linux `renameat2(..., RENAME_NOREPLACE)` (`unsupported_capability` on `ENOSYS`/`EINVAL`, `PublicationOutcome::Unknown` on post-rename parent `fsync` failure), `cleanup_stale_staging`, reproducible `create_archive`, and `extract_staged_isolated` / `run_isolated_worker_main` via `Void::Process::spawn` (ASan-safe rlimits + parent verification of staged inventory).
|
||||
- `tests/helpers/ArchiveWorker.cpp` wired as `VoidArchiveWorker` in `tests/CMakeLists.txt`, `tests/standalone/Archive/ArchiveHardening.cpp`, `tests/package/ArchiveOnly/*`, registered in `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## 3. Edge cases
|
||||
- `skip_entry` still decodes and accounts for actual decompressed bytes against per-entry and total limits.
|
||||
- File-as-parent path conflicts (e.g. file `a` followed by `a/b`, or `a/b` followed by file `a`) and non-zero/zero invalid limits are rejected cleanly.
|
||||
- Diagnostics cap path rendering at 4 KiB and escape control characters / attacker newlines.
|
||||
- Post-rename parent `fsync` failure reports `PublicationOutcome::Unknown` without falsely claiming rollback; pre-publish failure cleans only the owned staging descriptor and preserves primary error + staging id if cleanup fails.
|
||||
- Under `__SANITIZE_ADDRESS__`, child worker avoids fatal `RLIMIT_AS` and enforces `RLIMIT_CPU`/`RLIMIT_FSIZE`/`RLIMIT_NOFILE` + `/proc/self/statm` RSS enforcement.
|
||||
|
||||
## 4. Verification commands
|
||||
```sh
|
||||
dev cpp-gcc -p libarchive -c bash -lc 'cmake -S . -B /tmp/void-w6b-archive -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Archive;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-archive && /tmp/void-w6b-archive/tests/VoidTests --filter "Archive*|archive_*" && ctest --test-dir /tmp/void-w6b-archive --output-on-failure --timeout 120'
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
# M-CONFIGURATION-01..05 — Bounded Schemas, Provenance Redaction & Transactional Async Reload
|
||||
|
||||
- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`)
|
||||
- **Roadmap reference**: `docs/roadmap/modules/Configuration.md`, `docs/roadmap/DEPENDENCIES.md`
|
||||
|
||||
## Scope & Ownership
|
||||
- `src/Configuration/module.cmake`: `INTERNAL_DEPS Core Functional System Data Time LogState`, `EXCLUDE_HEADERS Void/Configuration/ReloadController.hpp`.
|
||||
- `src/ConfigurationAsync/module.cmake`: `INTERNAL_DEPS Configuration SystemAsync Async Time Functional LogState`, `EXTRA_HEADERS Void/Configuration/ReloadController.hpp`.
|
||||
- `include/Void/Configuration/Bind.hpp`: non-breaking field annotations `Secret{}`, `RestartRequired{}`, `Deprecated{}`, `IntRange{}`, `RealRange{}` while keeping `bind<T>` intact.
|
||||
- `include/Void/Configuration/Schema.hpp` + `src/Configuration/Schema.cpp`:
|
||||
- `kConfigurationErrorDomain = 24`, `ConfigErrorCode`, `ConfigLimits` (1 MiB/source, 8 sources, 4 MiB merged, 10,000 keys, 4 KiB key, 64 KiB scalar, depth 32, 1,024 vector items, 100 diagnostics, 64 participants, 4 retained generations, 128 notifications, 5s prepare timeout).
|
||||
- `SourceKind`, `SourceId`, `SourceLocation`, `ValueState` (`Missing`, `Empty`, `Null`, `Present`, `Removed`), `KeyProvenance`, `Provenance`, `SourceSpec`, `SourceSet`, `MergedConfig`.
|
||||
- `load_sources(...)`: deterministic precedence (defaults < files in order < allowlisted/prefixed env < explicit CLI), rejects literal-dot vs nested JSON collisions, enforces byte/key/depth/vector caps, redacts secrets in diagnostics.
|
||||
- `Schema<T>`, `validate<T>(...)` (rejects unknown keys by default, rejects vector gaps, no malformed-to-default fallback, cross-field constraints, up to 100 diagnostics with redacted secrets), `detect_restart_required_changes(...)`.
|
||||
- `include/Void/Configuration/ReloadController.hpp` + `src/ConfigurationAsync/ReloadController.cpp`:
|
||||
- Immutable `Snapshot<T>`, `PreparedChange`, `ReloadParticipant<T>`, `ReloadReport`, serialized `ReloadController<T>` with fallible `create(...)`, participant prepare/reverse-rollback/join on unregister, 4-generation retention cap, single atomic pointer swap, post-commit stop observation (`committed = true, stop_observed_after_commit = true`), bounded notification queue + exception isolation, external coordinator prepare port, `WatcherService` coalescing adapter.
|
||||
- Tests & consumers: `tests/standalone/Configuration/ConfigurationHardening.cpp`, `tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp`, `tests/package/ConfigurationOnly/*`, `tests/package/ConfigurationAsyncOnly/*`, `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## Verification Criteria
|
||||
- Standalone `ConfigurationAsync;Testing` RelWithDebInfo `-Werror`: `Configuration*` tests + `ctest` 2/2 (`ConfigurationOnly`, `ConfigurationAsyncOnly`).
|
||||
- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Crypto Hardening, Signing, MAC/KDF & Optional Async Hash Adapter
|
||||
Task ID: M-CRYPTO-01..05
|
||||
Phase: P2 (Wave 6B)
|
||||
Status: APPROVED
|
||||
Contracts: C-02, C-03, C-07, C-13
|
||||
|
||||
## 1. Context and baseline
|
||||
`Void::Crypto` preserves all 1.x APIs (`Hasher`, `Digest`, `HashAlgorithm`, `hash`, `hashFile`, `sha1`/`sha256`/`sha512`, `sha*File`, `verifyEd25519` exact-byte false-vs-error semantics) while hardening `Hasher` state poisoning (`Ready -> Updating -> Finalized | Failed`), adding per-context OpenSSL 3 `ProviderOptions` (no process-wide provider mutation), typed Ed25519 wrappers (`Ed25519PublicKey`, `Ed25519Signature`, `Ed25519Seed`, move-only `Ed25519PrivateKey`), `sign_ed25519`, `hmac_sha256`/`hmac_sha256_into`, `hkdf_sha256`, `constant_time_equal`, backend fault injection, and a separate optional `CryptoAsync` module (`hash_stream`, `AsyncFileHasher`) so `Crypto` remains runtime-free.
|
||||
|
||||
## 2. Deliverables
|
||||
- `src/Crypto/module.cmake` (`INTERNAL_DEPS Functional`, `EXTERNAL_DEPS OpenSSL::Crypto`, `EXCLUDE_HEADERS Void/Crypto/AsyncHash.hpp`) & `src/CryptoAsync/module.cmake` (`INTERNAL_DEPS Crypto IO Async Time Functional`, `EXTRA_HEADERS Void/Crypto/AsyncHash.hpp`).
|
||||
- `include/Void/Crypto/Types.hpp`: `kCryptoErrorDomain = 18`, `CryptoErrorCode`, `make_crypto_error`, `HasherState`, `ProviderOptions`, `CryptoLimits` (`kMaxOneShotMessageBytes = 16 MiB`, `kMaxHkdfOutputBytes = 4 KiB`, `kStreamChunkBytes = 64 KiB`, `kDefaultMaxConcurrentFileHashes = 8`, `kDefaultMaxWaitingFileHashes = 32`, `kDefaultAsyncBufferBudgetBytes = 8 MiB`), `Ed25519PublicKey`, `Ed25519Signature`, `Ed25519Seed` (with explicit wipe).
|
||||
- `include/Void/Crypto/Crypto.hpp` & `src/Crypto/Crypto.cpp`: OpenSSL 3 non-deprecated EVP APIs (`EVP_MD_fetch`, `EVP_MAC_fetch`, `EVP_KDF_fetch`, `EVP_PKEY_new_raw_*_ex`, `EVP_DigestSignInit_ex`, `EVP_DigestVerifyInit_ex`, `CRYPTO_memcmp`, `OPENSSL_cleanse`), poisoned `Hasher` + `state()`, `Ed25519PrivateKey` (`generate`, `from_raw_seed`, `public_key`, `export_raw_seed`), `sign_ed25519`, typed `verify_ed25519`, `hmac_sha256`, `hmac_sha256_into`, `hkdf_sha256` (4 KiB cap, overlap rejection, wipe-on-error), `constant_time_equal`, and thread-local/scoped backend fault hook.
|
||||
- `include/Void/Crypto/AsyncHash.hpp` & `src/CryptoAsync/AsyncHash.cpp`: `hash_stream` (64 KiB `BufferLease` chunks, stop/deadline checks between chunks, clean-EOF-only finalize) and `AsyncFileHasher` (8 concurrent / 32 waiters / 8 MiB buffer budget, `close_and_join`).
|
||||
- `tests/standalone/Crypto/CryptoHardening.cpp`, `tests/standalone/CryptoAsync/CryptoAsync.cpp`, `tests/package/{CryptoOnly,CryptoAsyncOnly}/*`, registered in `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## 3. Edge cases
|
||||
- Invalid key/signature sizes return `invalid_argument` before touching OpenSSL; well-formed invalid Ed25519 signatures return `true`/`false` (not error).
|
||||
- One-shot `sign_ed25519`/`verify_ed25519` enforce `16 MiB` limit; `hkdf_sha256` rejects zero/oversized (`> 4 KiB`) output and overlapping input/salt/context/output spans, wiping output on failure.
|
||||
- Backend error during `Hasher::update`/`finalize` transitions state to `Failed`, rejecting further `update`/`finalize` calls.
|
||||
- `hash_stream` never returns a digest on partial read + error or stop/EOF cancellation race; `AsyncFileHasher::close_and_join` stops admission and drains in-flight work before returning.
|
||||
|
||||
## 4. Verification commands
|
||||
```sh
|
||||
dev cpp-gcc -p openssl -c bash -lc 'cmake -S . -B /tmp/void-w6b-crypto -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Crypto;CryptoAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-crypto && /tmp/void-w6b-crypto/tests/VoidTests --filter "Crypto*|crypto_*" && ctest --test-dir /tmp/void-w6b-crypto --output-on-failure --timeout 120'
|
||||
```
|
||||
@@ -0,0 +1,24 @@
|
||||
# M-FSM-01..05 — Structured Scopes, Race-Loser Joins, Boundary Checkpoints & Bounded Supervision
|
||||
|
||||
- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`)
|
||||
- **Roadmap reference**: `docs/roadmap/modules/Fsm.md`, `docs/roadmap/DEPENDENCIES.md`
|
||||
|
||||
## Scope & Ownership
|
||||
- `src/Fsm/module.cmake`: `INTERNAL_DEPS Async Core Data Functional Time Log Service`.
|
||||
- `include/Void/Fsm/StateKey.hpp`: `kFsmErrorDomain = 25`, `FsmErrorCode`, `make_fsm_error`, shared `constexpr bool terminal(Status)` including `Faulted`, `TerminationReason`, `FsmLimits` (1,024 mailbox events / 4 MiB, 256 deferred, 1,024 timers, 128 child regions, depth 32, 256 retained transitions, 4 MiB checkpoint, 64 events / 1ms per turn), `Checkpoint`, `ExecutionBinding`, `StateId`.
|
||||
- `include/Void/Fsm/Detail/Engine.hpp` + `src/Fsm/Engine.cpp`:
|
||||
- Injected `Time::MonotonicClock` and `FsmLimits` for timers and turn budgeting.
|
||||
- Bounded `try_post` enforcing mailbox event & byte limits (`overloaded`) alongside a bounded control lane so stop/checkpoint/jump always progress.
|
||||
- Scope-tracked waiters & timers (`cancel_scope_waiters`) cancelled prior to state destruction.
|
||||
- `include/Void/Fsm/Machine.hpp`:
|
||||
- Preserve 100% of existing API (`start`, `wait`, `run_blocking`, `run_parallel`, `run_parallel_any`, `serialize`, `restore`).
|
||||
- Add `acquire_service<I>()` returning owning `Service::ServiceHandle<I>`, `try_post`, `termination_reason`, bounded `transition_history`, `observer_errors`, `state_stop_token()`, `await_event_cancellable`, `safe_point`.
|
||||
- Add `run(ExecutionBinding, Async::OperationOptions)` with root + per-state stop scopes, waiter/timer cleanup before `on_exit`, `on_exit` exception faulting, observer error isolation.
|
||||
- Add `run_parallel_structured` (sibling fault stop/join) and `run_parallel_any_structured` (deterministic tie-break + stop/join all losers).
|
||||
- Add boundary `request_checkpoint` / `restore_checkpoint` / `restore_legacy_checkpoint`.
|
||||
- `include/Void/Fsm/Orchestrator.hpp`: fix `FsmHandle::finished()` via `terminal(status())`, clarify `shared_ptr` ownership docs, add `SupervisionPolicy` (`StopOnFault`, `BoundedRestart` 3/60s on injected clock, 1,024 max supervised), unlocked observers, `try_launch`.
|
||||
- Tests & consumers: `tests/standalone/Fsm/FsmHardening.cpp`, `tests/package/FsmOnly/*`, `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## Verification Criteria
|
||||
- Standalone `Fsm;Testing` RelWithDebInfo `-Werror`: `Fsm*` tests + `ctest` 2/2 (`FsmOnly`).
|
||||
- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan.
|
||||
@@ -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,29 @@
|
||||
# Task Spec: `M-NET-01..05` — P2 Network Hardening, Native HTTP/1.1 Codec, Connection Pool, Safe Static Open & RFC 6455 WebSockets
|
||||
|
||||
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`, building on `VL-004`/`VL-005` in `66baae7` + `9920bfd`).
|
||||
- **Roadmap authority**: `docs/roadmap/modules/Net.md` (`M-NET-01`..`M-NET-05`), `ARCHITECTURE.md` C-02..C-06, C-11, C-13.
|
||||
- **Error domain**: `Void::Result::kNetErrorDomain = 26` (`NetErrorCode` in `include/Void/Net/Http.hpp`).
|
||||
|
||||
## Scope & Deliverables
|
||||
|
||||
1. **Native Incremental HTTP/1.1 Codec (`include/Void/Net/HttpCodec.hpp`, `src/Net/HttpCodec.cpp`)**:
|
||||
- `HttpCodecLimits` (defaults: `max_start_line_bytes = 8 KiB`, `max_header_bytes = 32 KiB`, `max_headers = 100`, `max_body_bytes = 8 MiB`, `max_chunk_ext_bytes = 1 KiB`, `max_trailer_bytes = 8 KiB`).
|
||||
- `HttpRequestParser` and `HttpResponseParser`: byte-by-byte / arbitrary-split incremental RFC 9110/9112 state machines.
|
||||
- Strict CRLF framing, header field-name token validation, rejection of duplicate/conflicting `Content-Length`, rejection of `Transfer-Encoding` + `Content-Length` smuggling ambiguity, handling of `1xx` informational responses, `HEAD`/`204`/`304` no-body responses, chunked transfer encoding with chunk extensions and trailers, close-delimited response bodies (`finish_eof()`), and explicit `connection_reusable()` check.
|
||||
2. **Bounded HTTP/1.1 Connection Pool (`include/Void/Net/Pool.hpp`, `src/Net/Pool.cpp`)**:
|
||||
- `PoolLimits` (defaults: `max_total_connections = 256`, `max_per_origin = 8`, `max_idle_connections = 128`, `idle_timeout = 30s`).
|
||||
- `PoolKey` keyed by `{scheme, host, port, proxy_identity, tls_policy_generation}` (so changing proxy or trust generation never reuses stale connections).
|
||||
- `ConnectionPool` using injectable `Void::Time::MonotonicClock` for deterministic idle eviction, returning RAII `ConnectionLease` handles that only return clean, reusable connections to the pool (`mark_reusable(true)`); abandoned/unmarked/dirty/expired leases close cleanly.
|
||||
3. **Descriptor-Pinned Static File Opening (`include/Void/Net/Server.hpp`, `src/Net/Server.cpp`)**:
|
||||
- `OpenedStaticFile` (move-only RAII descriptor + `content_type` + `size`, `read_all()`, `native_handle()`).
|
||||
- `StaticFileResolver::open_safe(std::string_view request_path)` walking components beneath a retained root directory fd (`O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC`), rejecting symlinks/traversal/non-regular files without pathname TOCTOU.
|
||||
4. **Redirect Compliance in `HttpClient` (`src/Net/Http.cpp`)**:
|
||||
- Follow only `301`, `302`, `303`, `307`, `308`; `303` converts non-HEAD to `GET` and strips body + `Content-Length`/`Content-Type`; `307`/`308` preserve method/body; resolve relative `Location` references against current URL; reject HTTPS->HTTP downgrade unless `allow_insecure_redirects`; strip `Authorization`, `Cookie`, `Proxy-Authorization`, `X-Api-Key` on cross-origin hops; enforce single absolute steady deadline across redirect hops.
|
||||
5. **Native RFC 6455 WebSocket Wire Framing & Loopback Transport (`include/Void/Net/WebSocket.hpp`, `src/Net/WebSocket.cpp`, `include/Void/Net/HttpServer.hpp`, `src/Net/HttpServer.cpp`)**:
|
||||
- `compute_websocket_accept(key)` (RFC 6455 SHA-1 + Base64), `validate_websocket_upgrade_request()` (version 13, `Upgrade: websocket`, `Connection: Upgrade`, 16-byte base64 key, optional origin/subprotocol policy).
|
||||
- `WebSocketOpcode`, `WebSocketLimits` (`max_message_bytes = 1 MiB`, `max_output_messages = 64`, `max_output_bytes = 4 MiB`), `WebSocketFrame`, `encode_websocket_frame()`, `WebSocketFrameDecoder` enforcing client masking / server non-masking, fragmentation, control-frame rules (<= 125 bytes, FIN=1), strict RFC 3629 UTF-8 validation for text frames & close reasons, ping/pong, and single close handshake.
|
||||
- `HttpServer::add_websocket_route(pattern, WebSocketSessions&, WebSocketUpgradeOptions)` upgrading incoming HTTP/1.1 requests into live RFC 6455 connections integrated with `WebSocketSessions`, plus loopback `WebSocketClient` for full client/server wire verification.
|
||||
|
||||
## Verification
|
||||
- Standalone `Net;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`): split-byte smuggling & chunked/trailer/1xx/HEAD codec corpus, pool eviction & key isolation, `open_safe` symlink-swap rejection, redirect `303`/`307`/relative/cross-origin tests, RFC 6455 wire & loopback `WebSocketClient`/`HttpServer` ping/pong/fragmented/UTF-8/close/shutdown tests.
|
||||
- `ctest` `NetOnly` installed consumer, full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
|
||||
@@ -0,0 +1,19 @@
|
||||
# M-PLUGIN-01..06 — Pure C11 ABI (`CAbi.h`), Generation Pins, Quiesce/Reload & Unlocked Staging
|
||||
|
||||
- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`)
|
||||
- **Roadmap reference**: `docs/roadmap/modules/Plugin.md`, `docs/roadmap/DEPENDENCIES.md` (`G-HOST`)
|
||||
|
||||
## Scope & Ownership
|
||||
- `src/Plugin/module.cmake`: `INTERNAL_DEPS Core Functional System Data Time Async LogState Text Service`, `DEPS_UNIX dl`.
|
||||
- `include/Void/Plugin/CAbi.h`: strict ISO C11 public ABI (`VOID_STATUS_*`, `VOID_CABI_MAJOR_V1 = 1`, `VOID_CAP_*`, `void_module_query_v1`, `void_bytes_v1`, `void_owned_bytes_v1`, `void_interface_id_v1`, `void_module_info_v1`, `void_op_options_v1`, `void_error_detail_v1`, `void_host_api_v1`, `void_module_api_v1`, `VOID_MODULE_API_V1_MIN_SIZE`) with zero C++/STL types or exceptions.
|
||||
- `include/Void/Plugin/Host.hpp` + `src/Plugin/Host.cpp` + `include/Void/Plugin/CAbiAdapter.hpp`:
|
||||
- `kPluginErrorDomain = 23`, `PluginErrorCode`, `PluginHostLimits` (64 modules, 256 interfaces/module, 4 retained generations/module, 64 MiB mapped image file accounting/module, 4 MiB checkpoint, 1 MiB config, 1,024 async ops/gen, 256 pending callbacks, 5s prepare / 5s quiesce / 10s readiness / 30s total reload timeout, `allow_safe_dlclose = false` default).
|
||||
- Independent `external_refs` and `activity_pins`; host-owned retirement queue executing `deactivate -> destroy -> optional dlclose` only when both reach 0 and never on a plugin callback's stack; uncooperative generations stay mapped and remain visible via `retained_generations()`.
|
||||
- `CModuleHost`: validates `void_module_query_v1` against truncation/unknown major/non-zero reserved/oversized lengths; per-module unlocked staged reload coordinator (`quiesce -> checkpoint -> restore -> activate -> readiness` sharing one absolute deadline on injected `Time::MonotonicClock`, rollback + `resume` on pre-publication failure or `Degraded` on resume failure, atomic epoch-checked publication + coherent `ServiceRegistry` swap); topological dependency `load_batch` rejecting cycles and `RestartRequired` conflicts.
|
||||
- `CAbiAdapter.hpp`: exception-safe C++ `IModule` to `void_module_api_v1` shim.
|
||||
- `src/Plugin/Manager.cpp`: per-entry `reload_mutex` so candidate staging/validators/config/activation run outside `m_mutex` without deadlocking reentrant lookups.
|
||||
- Tests & consumers: `tests/plugins/CAbiPluginV{1,2}.c`, `tests/standalone/Plugin/PluginHardening.cpp`, `tests/package/PluginOnly/*`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## Verification Criteria
|
||||
- Standalone `Plugin;ServicePlugin;Testing` RelWithDebInfo `-Werror`: `Plugin*` tests + `ctest` 2/2 (`PluginOnly`, `ServicePluginOnly`).
|
||||
- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan.
|
||||
@@ -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,29 @@
|
||||
# Security Hardening, SecureBuffer, Versioned Envelopes, Authorization & Authenticator
|
||||
Task ID: M-SECURITY-01..04
|
||||
Phase: P2 (Wave 6B)
|
||||
Status: APPROVED
|
||||
Contracts: C-02, C-03, C-04, C-05, C-07, C-09, C-13
|
||||
|
||||
## 1. Context and baseline
|
||||
`Void::Security` preserves all 1.x APIs (`generateToken`, `hashToken`, `verifyToken`, `hashPassword`, `verifyPassword`, `generateSecretKey`, `sealSecret`, `openSecret`) and the exact legacy secret envelope format (`24B nonce || secretbox_easy(16B MAC + ciphertext)`), while adding `SecureBuffer`, input/cost validation (`parse_argon2id_cost`, `verify_password_budgeted`), versioned `VSEC` v1 AEAD envelopes + `SecretKeyRing` rotation, typed default-deny `Authorization`, and a separate `SecurityAsync` module (`Authenticator`, `AccountSessionPort`, `InMemoryAccountSessionStore`, `PasswordJobBudget`, `AuditSink`) so primitive `Security` remains free of Async/Resilience/Storage dependencies.
|
||||
|
||||
## 2. Deliverables
|
||||
- `src/Security/module.cmake` (`INTERNAL_DEPS Functional Time`, `EXTERNAL_DEPS Sodium::Sodium`, `EXCLUDE_HEADERS Void/Security/Authenticator.hpp`) & `src/SecurityAsync/module.cmake` (`INTERNAL_DEPS Security Async Time Resilience Functional`, `EXTRA_HEADERS Void/Security/Authenticator.hpp`).
|
||||
- `include/Void/Security/Types.hpp`: `kSecurityErrorDomain = 19`, `SecurityErrorCode`, `make_security_error`, `SecurityLimits` (1 KiB password/hash, 512 B token, 16 MiB plaintext, 64 roles, 4096 rules, 16 predicate depth), `PasswordVerifyBudget`, `Argon2idCost`.
|
||||
- `include/Void/Security/SecureBuffer.hpp` & `src/Security/SecureBuffer.cpp`: move-only `SecureBuffer` with `LockPolicy::{StandardWiped, LockedOptional, LockedRequired}` (fail-closed if locked allocation fails), `sodium_memzero` wipe on release/move, optional fault hook.
|
||||
- `include/Void/Security/Security.hpp` & `src/Security/Security.cpp`: preserve 1.x surface + enforce input caps, `parse_argon2id_cost`, `verify_password_budgeted` rejecting excessive `m`/`t` before Argon2id allocation, backend init/randomness fault seam.
|
||||
- `include/Void/Security/Envelope.hpp` & `src/Security/Envelope.cpp`: versioned `VSEC` v1 `crypto_aead_xchacha20poly1305_ietf` envelope authenticating header + `key_id` + `aad`, `SecretKeyRing` (active-key writes, multi-key reads, checked retirement), zero silent legacy fallback.
|
||||
- `include/Void/Security/Authorization.hpp` & `src/Security/Authorization.cpp`: `Principal` (<=64 roles), typed `Predicate` (depth <=16), `PolicySnapshot` (<=4096 rules, default-deny, deny-overrides-allow, `authorize`).
|
||||
- `include/Void/Security/Authenticator.hpp` & `src/SecurityAsync/Authenticator.cpp`: `AccountSessionPort`, `InMemoryAccountSessionStore`, `PasswordJobBudget` (512 MiB / 2 active / 32 waiters), `SessionPolicy` (10,000 total / 16 per subject / 1h TTL / 60s civil-clock rollback check / 256 cleanup batch), mandatory `AuditSink`, `Authenticator` (dummy-hash timing-work parity, credential-version CAS, non-interruptible drain-on-stop, zero positive session cache, `close_and_join`).
|
||||
- `tests/standalone/Security/SecurityHardening.cpp`, `tests/standalone/SecurityAsync/SecurityAsync.cpp`, `tests/package/{SecurityOnly,SecurityAsyncOnly}/*`, registered in `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## 3. Edge cases
|
||||
- Legacy `sealSecret`/`openSecret` bytes remain bit-for-bit compatible; `Envelope` never guesses legacy decoding after AEAD failure.
|
||||
- Unknown account and wrong password execute comparable Argon2id work via a precomputed dummy hash and return identical public denial while recording distinct internal audit reasons.
|
||||
- Cancelling during password verification returns cancelled, retains budget/buffers until the Argon2id job completes, discards output, and never writes a session.
|
||||
- Civil-clock rollback exceeding configured tolerance (default 60s) fails session admission until reconciled.
|
||||
|
||||
## 4. Verification commands
|
||||
```sh
|
||||
dev cpp-gcc -p libsodium -c bash -lc 'cmake -S . -B /tmp/void-w6b-security -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Security;SecurityAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-security && /tmp/void-w6b-security/tests/VoidTests --filter "Security*|security_*" && ctest --test-dir /tmp/void-w6b-security --output-on-failure --timeout 120'
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
# M-SERVICE-01..05 — Owning ServiceHandles, Immutable Snapshots, DAG Lifecycle & ServicePlugin Split
|
||||
|
||||
- **Wave**: Wave 8 (`feat/roadmap-p2-wave8`, branched from `main` at `d83d0f4`)
|
||||
- **Roadmap reference**: `docs/roadmap/modules/Service.md`, `docs/roadmap/DEPENDENCIES.md` (Rule #3, `G-HOST`)
|
||||
|
||||
## Scope & Ownership
|
||||
- `src/Service/module.cmake`: `INTERNAL_DEPS Core Functional Time Async LogState`, `EXCLUDE_HEADERS Void/Service/PluginService.hpp` (zero external deps, zero `Plugin` dependency).
|
||||
- `src/ServicePlugin/module.cmake`: `INTERNAL_DEPS Service Plugin LogState`, `EXTRA_HEADERS Void/Service/PluginService.hpp`.
|
||||
- `include/Void/Service/Types.hpp`: `kServiceErrorDomain = 22`, `ServiceErrorCode`, `make_service_error`, `ServiceLimits` (256 providers, 16 parent levels, 1,024 edges, 64 staged changes, 128 lifecycle requests, 4 retained generations), `PublicationEpoch`, `ExpectedEpoch`, `ServicePin`, `ServiceHealth`, `ServiceObservation`, `ShutdownReport`, `IManagedService`, `ServiceHandle<I>`.
|
||||
- `include/Void/Service/Registry.hpp` + `src/Service/Registry.cpp`:
|
||||
- Preserve 100% of existing `ServiceRegistry` API (`provide<I>`, `remove<I>`, `get<I>`, `require<I>`, `has<I>`, `start_all`, `stop_all`, `size`).
|
||||
- Immutable `SnapshotData` swapped atomically under a short guard; old snapshots, destructors, and observers released/invoked outside locks.
|
||||
- `start_all()`/`stop_all()` copy retained lifecycle list under short lock and invoke callbacks outside locks.
|
||||
- `ServiceSnapshot` retaining `parent_snapshot` `shared_ptr` so child snapshots outlive parent registries; `snapshot()`, `from_parent_snapshot()`, `refresh_parent()`.
|
||||
- `acquire<I>() -> Result<ServiceHandle<I>>` returning `service_stopping` when closed or `missing_service` when absent, pinning generation lifetime until handle drop.
|
||||
- `ProviderSet` (`add`, `add_alias` sharing one lifecycle node per object pointer), `PreparedPublication`, `prepare_batch` (topological sort + cycle/duplicate/missing-dep/limit validation), `start_staged` (topological start + `abort_start()` + reverse rollback preserving active snapshot), `publish` (epoch check + retention cap + atomic swap), `start`, `close_and_join` (dependent-first stop + `incomplete_owners` reporting without freeing live providers), `retained_generation_count()`.
|
||||
- `include/Void/Service/PluginService.hpp`: preserved `PluginServiceBinding<I>` + `acquire_plugin_service<I>` pinning exact `PluginHandle` via `ServicePin`.
|
||||
- Tests & consumers: `tests/standalone/Service/ServiceHardening.cpp`, `tests/package/ServiceOnly/*`, `tests/package/ServicePluginOnly/*`, updated `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## Verification Criteria
|
||||
- Standalone `Service;ServicePlugin;Testing` RelWithDebInfo `-Werror`: `Service*` tests + `ctest` 2/2 (`ServiceOnly`, `ServicePluginOnly`).
|
||||
- Full Wave 8 RelWithDebInfo `-Werror`, ASan+UBSan `-Werror`, and Wave 8 TSan.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Task Spec: `M-SHORTURL-01..04` — Frozen V1, Additive V2 Local/Durable/Remote Providers & V1 Adapter
|
||||
|
||||
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
|
||||
- **Roadmap authority**: `docs/roadmap/modules/ShortUrl.md` (`M-SHORTURL-01`..`M-SHORTURL-04`), `ARCHITECTURE.md` C-02..C-05, C-09, C-13.
|
||||
- **Error domain**: `Void::Result::kShortUrlErrorDomain = 28`.
|
||||
|
||||
## Scope & Deliverables
|
||||
|
||||
1. **Frozen `V1` Contract (`include/Void/ShortUrl/ShortUrl.hpp`, `docs/short-url.md`)**:
|
||||
- Zero changes to `Void::ShortUrl::V1` layout, enum ordinals, virtual table order, or `docs/short-url.md`.
|
||||
- Keep `ShortUrl` module's internal dependencies lightweight (`Service Time`), with zero `Storage`, `Net`, or `Security` dependencies.
|
||||
2. **Additive `Void::ShortUrl::V2` Core & Local Provider (`include/Void/ShortUrl/V2.hpp`)**:
|
||||
- `V2ErrorCode` mapped via `kShortUrlErrorDomain = 28` (`InvalidUrl`, `InvalidKey`, `InvalidExpiry`, `Conflict`, `NotFound`, `Expired`, `Revoked`, `Unsupported`, `RateLimited`, `QuotaExceeded`, `IdentityExpired`, `StorageError`, `UnknownOutcome`, `ProviderError`, `Timeout`, `Unavailable`).
|
||||
- `CreateLink`, `ShortenOptions` (`operation_id`, `idempotency_ttl = 24h`), `Link`, `LinkRecord`, `LinkState::{Active, Revoked}`, `LocalProviderLimits` (`max_url_bytes = 8192`, `max_key_bytes = 64`, `generated_key_length = 16`, `max_collision_retries = 8`, `max_retained_identities = 10000`, `max_entries = 100000`, `max_concurrent_ops = 128`).
|
||||
- Strict target URL validation (absolute `http`/`https`, no userinfo, no control chars, <= 8 KiB, optional host deny predicate) and custom key validation (1..64 `[A-Za-z0-9_-]`, case-sensitive, reserved route rejection).
|
||||
- Abstract `LinkRepositoryPort` + `RandomBytesPort`, explicitly nondurable `InMemoryLinkRepository` (for unit/semantics tests), rejection-sampled base62 key generation, atomic conditional insert + idempotency record, civil expiry via injected `Void::Time::CivilClock`, tombstone `revoke()` (never reusing revoked keys), `V1Adapter` implementing `V1::IShortener` without modifying `V1`.
|
||||
3. **Durable Storage Provider (`src/ShortUrlStorage/module.cmake`, `include/Void/ShortUrlStorage/StorageRepository.hpp`, `src/ShortUrlStorage/StorageRepository.cpp`)**:
|
||||
- Separate module (`INTERNAL_DEPS ShortUrl Storage Security`) keeping `ShortUrl` free of `Storage`/`libsodium`.
|
||||
- `StorageLinkRepository` backed by `Void::Storage::Engine` conditional `WriteBatch` (versioned records, atomic link + idempotency commit, tombstone persistence, byte quota enforcement, full recovery across engine reopen) + `SecurityRandomBytesPort` backed by `Void::Security::random_bytes`.
|
||||
4. **Remote Provider SPI (`src/ShortUrlRemote/module.cmake`, `include/Void/ShortUrlRemote/RemoteProvider.hpp`, `src/ShortUrlRemote/RemoteProvider.cpp`)**:
|
||||
- Separate module (`INTERNAL_DEPS ShortUrl Net Data`) keeping `ShortUrl` free of `Net`/Boost/OpenSSL.
|
||||
- `RemoteCapabilities`, `RemoteProviderOptions` (explicit origin, secure `HttpClient`, max 1 MiB response, 10s deadline), `RemoteProvider` checking capability flags before network mutation, preserving `Retry-After` and classifying transport failures after send as `UnknownOutcome` without blind replay, plus loopback fixture tests.
|
||||
5. **Installed Consumers**:
|
||||
- `tests/package/ShortUrlOnly/` (`ShortUrl` with zero external packages) + `ShortUrlProviders` in `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## Verification
|
||||
- Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`), `ctest` (`ShortUrlOnly`, `ShortUrlProviders`), full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
|
||||
@@ -0,0 +1,26 @@
|
||||
# M-SQLITE-01..05 — Hardened Sqlite C API Integration & Optional SqliteAsync Pool
|
||||
|
||||
- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`)
|
||||
- **Roadmap reference**: `docs/roadmap/modules/Sqlite.md`, `docs/roadmap/DEPENDENCIES.md`
|
||||
- **Supported runtime observed**: SQLite 3.54.0 via Nix `sqlite` package
|
||||
|
||||
## Scope & Ownership
|
||||
- `src/Sqlite/module.cmake`: `INTERNAL_DEPS Functional Time`, `EXTERNAL_DEPS SQLite3::SQLite3`, `EXCLUDE_HEADERS Void/Sqlite/AsyncPool.hpp`.
|
||||
- `include/Void/Sqlite/Types.hpp`: `kSqliteErrorDomain = 21`, `SqliteErrorCode`, `JournalMode`, `SyncMode`, `BeginMode`, `CheckpointMode`, `TransactionState`, `SqliteLimits`, `OpenOptions`, `EffectiveCapabilities`, `ColumnType`, `ValueView`, `OwnedValue`, `OwnedRow`, `CheckpointReport`, `BackupOptions`, `BackupReport`, `CheckedMigration`, `ConnectionHealth`, `ScopedFaultGuard`.
|
||||
- `include/Void/Sqlite/Sqlite.hpp` + `src/Sqlite/Sqlite.cpp`:
|
||||
- Shared `ConnectionState` held by `Database`, `Statement`, `Transaction`, and `Savepoint` so moving/destroying `Database` never leaves dangling pointers.
|
||||
- Preserve 1.x APIs (`Database::open`, `exec`, `prepare`, `begin`, `last_insert_rowid`, `changes`, `user_version`, `migrate`, `Statement::bind`/`step`/`reset`/`clear_bindings`/column getters, `Transaction::commit`/`rollback`, `Migration`, `OpenMode`).
|
||||
- Add `open_database(path, OpenOptions)` validating limits/pragmas (`WAL`, `FULL`, `foreign_keys`, disabling extension loading by default, querying effective pragma results).
|
||||
- Add checked `bind_checked` (positional & named, `ValueView`, `max_value_bytes` cap), borrowed lifetime-owned bindings, `reset_checked`, `clear_bindings_checked`, `finalize_checked`, strict single-statement `prepare` (rejecting non-whitespace trailing SQL), `RowView` with expiration generation, strict typed column reads rejecting coercion, `query_all` with row/byte caps.
|
||||
- Transaction state machine (`Active`, `Committed`, `RolledBack`, `RecoveryRequired`): never mark `Committed` before `COMMIT` succeeds; inspect `sqlite3_get_autocommit` on error; reject nested `begin`; add RAII `Savepoint`.
|
||||
- Checked `Database::close()` rejecting with `busy` while statements/transactions/savepoints remain open; deferred close in destructor reports errors to optional diagnostic hook.
|
||||
- Validate migration lists before any SQL; add `migrate_checked` recording `id`+`checksum` in `_void_schema_migrations` in the same transaction as `PRAGMA user_version` and rejecting newer schemas and checksum drift.
|
||||
- Operational methods: `checkpoint()`, `backup_to()`, `restore_from()`, `health()`, WAL write-admission threshold gating, and exception-safe `create_scalar_function` / `set_authorizer` adapters.
|
||||
- `src/SqliteAsync/module.cmake` + `include/Void/Sqlite/AsyncPool.hpp` + `src/SqliteAsync/AsyncPool.cpp`:
|
||||
- Optional async leased connection pool (default 4 readers + 1 writer, bounded blocking workers, `max_queued_jobs = 1024`, `max_pending_input_bytes = 64 MiB`).
|
||||
- Leases one connection for the complete read/write/transaction with serialized progress/interrupt cleanup so cancellation never leaks to the next borrower.
|
||||
- Tests & consumers: `tests/standalone/Sqlite/SqliteHardening.cpp`, `tests/standalone/SqliteAsync/SqliteAsync.cpp`, `tests/package/SqliteOnly/*`, `tests/package/SqliteAsyncOnly/*`, updated `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## Verification Criteria
|
||||
- Standalone `Sqlite;SqliteAsync;Testing` RelWithDebInfo `-Werror` (`-p sqlite`): all `Sqlite*` tests + `ctest` 2/2 (`SqliteOnly`, `SqliteAsyncOnly`).
|
||||
- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset.
|
||||
@@ -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,27 @@
|
||||
# System Process, Shared Watcher, Durable Filesystem & Temp Factories
|
||||
Task ID: M-SYSTEM-01..05
|
||||
Phase: P2 (Wave 6A)
|
||||
Status: APPROVED
|
||||
Contracts: C-01, C-02, C-03, C-04, C-05
|
||||
|
||||
## 1. Context and baseline
|
||||
`Void::System` preserves 1.x APIs (`Void::Process::{run,run_streaming,shell,reexec}`, `Void::FileSystem::{FileWatcher,Path,Query,TempFile,TempDir}`, `Void::SystemInfo::CpuSampler`) while fixing legacy bugs (zero-timeout 30s cutoff, full-duplex pipe deadlock, unescalated `SIGTERM` wait hangs, `SIGPIPE` on pipes, TOCTOU temp creation, unsafe `atomic_write`) and adding `System` (`Types`, `OwnedFd`, `Child`, `spawn`, `communicate_blocking`, `replace_file`, bounded `read_file`/`list_directory`, valid `CpuSampler::sample`) plus `Void::SystemAsync` (`ProcessManager`, async `communicate`/`wait`, shared `WatcherService`, `WatchSubscription`).
|
||||
|
||||
## 2. Deliverables
|
||||
- `src/System/module.cmake` (`INTERNAL_DEPS Functional Time LogState`, `EXCLUDE_HEADERS Void/System/AsyncProcess.hpp Void/System/AsyncWatcher.hpp`) & `src/SystemAsync/module.cmake` (`INTERNAL_DEPS System Async IO Time Functional LogState`).
|
||||
- `include/Void/System/Types.hpp`: `kSystemErrorDomain = 10`, `SystemErrorCode`, `make_system_error`, move-only `OwnedFd`.
|
||||
- `include/Void/System/Process.hpp` & `src/System/Process.cpp`: legacy compatibility fixes + `SpawnOptions`, `EnvironmentPolicy`, `CaptureLimits`, `OverflowPolicy`, `kMaxSpawnInputBytes = 256 KiB`, move-only `Child`, `spawn`, `communicate_blocking`, `reexec(..., close_extra_fds)`.
|
||||
- `include/Void/System/{Path,Query,TempFile,TempDir,Metrics}.hpp`: `read_file_bounded`, `list_directory_bounded`, `replace_file` with `ReplaceDurability`/`ReplacePhase`/`ReplaceFaultHook`, atomic `0600`/`0700` `TempFile`/`TempDir` verified by `(dev, ino)` before removal, `CpuSample`.
|
||||
- `include/Void/System/{AsyncProcess,AsyncWatcher}.hpp` & `src/SystemAsync/{AsyncProcess,AsyncWatcher}.cpp`: `ProcessManager`, async `communicate`/`wait`/`close_and_join`, shared `WatcherService`, `WatchSubscription`.
|
||||
- `tests/helpers/ProcessHelper.cpp`, `tests/standalone/System/{ProcessStream,SystemHardening}.cpp`, `tests/standalone/SystemAsync/SystemAsync.cpp`, `tests/package/{SystemOnly,SystemAsyncOnly}/*`.
|
||||
|
||||
## 3. Edge cases
|
||||
- Between `fork()` and `exec*()`, strictly async-signal-safe operations only; `exec_failed` preserves `errno` via `CLOEXEC` error pipe and never collides with child exit `127`.
|
||||
- `replace_file` cleans only owned temp files before rename and reports `visible_on_disk = true, durability_unknown = true` if post-rename directory `fsync` fails.
|
||||
- `WatcherService::close_and_join()` drains admitted callbacks and rejects self-join.
|
||||
|
||||
## 4. Verification commands
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-system -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-system && /tmp/void-w6a-system/tests/VoidTests --filter "Process*|SystemHardening*|Path*|Query*|TempDir*|TempFile*|Metrics*|FileWatcher*|SignalWatcher*" && ctest --test-dir /tmp/void-w6a-system --output-on-failure --timeout 120'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-sysasync -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="SystemAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-sysasync && /tmp/void-w6a-sysasync/tests/VoidTests --filter "SystemAsync*" && ctest --test-dir /tmp/void-w6a-sysasync --output-on-failure --timeout 120'
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
# Task Spec: `M-TESTINGMOCK-01..04` — Deterministic Sessions, Action-Outside-Lock, Move-Only Forwarding & Matcher Combinators
|
||||
|
||||
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
|
||||
- **Roadmap authority**: `docs/roadmap/modules/TestingMock.md` (`M-TESTINGMOCK-01`..`M-TESTINGMOCK-04`), `ARCHITECTURE.md` C-02..C-05.
|
||||
- **Error domain**: `Void::Result::kTestingMockErrorDomain = 27`.
|
||||
|
||||
## Scope & Deliverables
|
||||
|
||||
1. **Preserve 1.x API & Existing Tests**:
|
||||
- Existing `Mock<Derived>`, `MockBase`, `MockFunction<R(Args...)>`, `Matcher<T>`, `Eq`, `_`, `Lt`, `Le`, `Gt`, `Ge`, `Range`, `Pred`, `StartsWith`, `Contains`, and all existing tests under `tests/standalone/TestingMock/` continue compiling and passing unchanged.
|
||||
2. **Matcher Combinators (`include/Void/TestingMock/Matcher.hpp`)**:
|
||||
- Add `Ne`, `EndsWith`, `Not`, `AllOf`, `AnyOf`, `IsNull`, `NotNull`, with bounded description/nesting depth (`kMaxMatcherDepth = 32`).
|
||||
3. **Explicit Session, Sequences, Limits & Tokens (`include/Void/TestingMock/Session.hpp`)**:
|
||||
- `Concurrency::{SingleThread, ConcurrentActions}`.
|
||||
- `MockLimits{max_expectations = 1024, max_matchers = 64, max_events = 4096, max_diagnostic_bytes = 4 MiB, max_arg_render_bytes = 4 KiB}` (zero means zero capacity, never unlimited).
|
||||
- `Sequence`: explicit per-group call ordering independent of global registration order.
|
||||
- `Verification`: structured report (`ok()`, `unmet`, `excess`, `unmatched`, `prohibited`, `matcher_errors`, `threading_errors`, `events_truncated`, `total_events`, `format()`), idempotent across repeated calls.
|
||||
- `MockSession`: `freeze(Concurrency)` (mutating a frozen session returns `ErrorKind::invalid_argument` / `InvalidState`), `verify_and_close()` (drains/joins active calls; returns `WouldDeadlock` if called from inside an active action), bounded event log with truncation tracking, RAII `RegistrationToken` stopping admission and waiting for admitted calls on unregister.
|
||||
4. **Hardened `Expectation` & `SessionMockFunction` (`include/Void/TestingMock/Expectation.hpp`, `include/Void/TestingMock/MockFunction.hpp`)**:
|
||||
- Action-outside-lock reservation protocol: snapshot immutable candidates under short lock -> evaluate matchers outside lock (catching matcher exceptions as `MatcherFailure`) -> reacquire lock to reserve matching unsaturated expectation & sequence slot -> release lock -> execute action -> decrement in-flight counter & record completion.
|
||||
- Same-thread reentrant calls succeed in `SingleThread`; cross-thread concurrent entry in `SingleThread` reports deterministic threading violation; `ConcurrentActions` permits concurrent action execution safely.
|
||||
- Perfect argument forwarding (`Args&&...`) to actions; `returns_once(U&&)` for move-only return types (`std::unique_ptr`), `invokes_once(F&&)` for one-shot move-only callables, `at_least(n)`, `at_most(n)`, `between(min, max)`, `never()` (checked before ordinary candidates), `in_sequence(Sequence&)`.
|
||||
- Non-default-constructible return type on unmatched call records failure and throws TestingMock's invocation-abort exception (never `R{}` fallback).
|
||||
5. **Installed Consumer (`tests/package/TestingMockOnly/`)**:
|
||||
- Register `TestingMockOnly` in `tests/package/InstalledComponents.cmake` with `_no_external_deps`.
|
||||
|
||||
## Verification
|
||||
- Standalone `TestingMock;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`), `ctest` `TestingMockOnly`, Debug `ASan+UBSan`, Debug `TSan` (concurrent action reservation & dynamic unregister races).
|
||||
@@ -0,0 +1,28 @@
|
||||
# Update Verify-Before-Parse, Replay Floor, Trust Store, Pinned Pruning & Recoverable Install Coordinator
|
||||
Task ID: M-UPDATE-01..06
|
||||
Phase: P2 (Wave 6B)
|
||||
Status: APPROVED
|
||||
Contracts: C-02, C-03, C-04, C-05, C-06, C-07, C-09, C-10
|
||||
|
||||
## 1. Context and baseline
|
||||
`Void::Update` preserves existing feed/component verification, readable envelopes, greatest-compatible-version selection, and `VersionStore` durable activation/commit/rollback/reconcile/external-health semantics while fixing the schema-3 verify-before-payload-parse bug in `src/Update/Feed.cpp`, introducing explicit `SchemaParsePolicy` (`LegacyGeneralJson` vs `StrictJsonProfile`), non-forgeable `VerifiedSelection`, durable monotonic `ReplayFloorStore`, explicit `TrustStore` rotation/revocation, pin-aware bounded `VersionStore::pruneWithPins`, checksummed `OperationJournal`, and `InstallCoordinator` integrating `Archive`'s staged atomic publication and `VersionStore`'s single commit boundary.
|
||||
|
||||
## 2. Deliverables
|
||||
- `src/Update/module.cmake` (`INTERNAL_DEPS Archive Crypto Data Functional System Text Time`).
|
||||
- `include/Void/Update/Types.hpp`: `kUpdateErrorDomain = 20`, `UpdateErrorCode`, `make_update_error`, `SchemaParsePolicy`, `InstallState`, `ActivationMode`, `ReleaseIdentity`, `InstallReceipt`, `InstallOptions` (1 active, 8 queued, 2 concurrent downloads, 512 MiB artifact, 2 GiB staging quota, 32 components, 256 edges, 10m deadline, 30s readiness, 1s probe interval, 3 consecutive healthy, 2 retained previous, 16 prune batch).
|
||||
- `include/Void/Update/Feed.hpp` & `src/Update/Feed.cpp`: move `Crypto::verifyEd25519` strictly BEFORE payload JSON parsing/comparison in schema-3 `verifyEnvelope`, support `SchemaParsePolicy::StrictJsonProfile` (integer-only strict JSON via `Void::Json::Strict::ParseOptions{.allowDecimals = false}`), add non-forgeable `VerifiedSelection` + `verify_and_select_release` / `verify_and_select_component_set`.
|
||||
- `include/Void/Update/VersionStore.hpp` & `src/Update/VersionStore.cpp`: add `PruneReport` and `pruneWithPins(retainedPreviousVersions, pinnedVersions, batchLimit = 16)`.
|
||||
- `include/Void/Update/Install.hpp` & `src/Update/Install.cpp` (included from `Update.hpp`): `ReplayFloorStore` (atomic via `Void::FileSystem::replace_file`, monotonic across restarts/key rotations/clock rollback), `TrustStore` (bootstrap, authenticated rotation, revocation), `ArtifactTransport` + `LocalFileArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` (`RecoveryRequired` on unknown/corrupt), and `InstallCoordinator` (`install`, idempotent `reconcile`, `retry_cleanup`, `shutdown`).
|
||||
- `tests/standalone/Update/UpdateHardening.cpp`, `tests/package/UpdateOnly/*`, registered in `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## 3. Edge cases
|
||||
- Invalid signature over malformed JSON payload in schema-3 envelopes fails at signature verification without ever invoking payload JSON parsing.
|
||||
- Replay floor never decreases on restart, key rotation, or civil-clock rollback.
|
||||
- Post-commit cleanup/prune failures transition receipt to `CleanupPending` with retryable diagnostics and NEVER trigger rollback; calling `rollback` after durable healthy marker preserves the committed candidate.
|
||||
- Unknown/corrupt operation journal entries halt automation with `RecoveryRequired` without discarding evidence.
|
||||
- Pinned versions cannot be pruned; prune reports skipped-pin pressure rather than breaking live pins.
|
||||
|
||||
## 4. Verification commands
|
||||
```sh
|
||||
dev cpp-gcc -p libarchive -p openssl -c bash -lc 'cmake -S . -B /tmp/void-w6b-update -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Update;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-update && /tmp/void-w6b-update/tests/VoidTests --filter "Update*|update_*|component_feed_*|readable_component_*|version_store_*" && ctest --test-dir /tmp/void-w6b-update --output-on-failure --timeout 120'
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
# IPC Wire Codec, Quota Reservations, Local UDS/Pipe Transport, and Session
|
||||
Task ID: S-IPC-01..03
|
||||
Phase: P2 (Wave 6A)
|
||||
Status: APPROVED
|
||||
Contracts: C-01, C-02, C-03, C-04, C-05
|
||||
|
||||
## 1. Context and baseline
|
||||
New subsystem `Void::IPC` (`src/IPC/module.cmake`, `INTERNAL_DEPS Core Functional Memory Time Binary Async IO Resilience`) providing V1 `VDIP` 24-byte big-endian framed RPC/messaging over pathname `AF_UNIX` `SOCK_STREAM` and supervised child pipe pairs (`adopt_pipe_pair`).
|
||||
|
||||
## 2. Deliverables
|
||||
- `include/Void/Functional/Error.hpp`: reserve `kIpcErrorDomain = 16` (plus remaining P2 domains `17..21`).
|
||||
- `include/Void/IPC/{Types,Codec,Transport,Session,IPC}.hpp` & `src/IPC/{Codec,Transport,Session}.cpp`:
|
||||
- `IpcErrorCode`, `IpcLimits`, `EffectStatus`, `CallFailure`, `PeerCredentials`, `PeerPolicy`, `HelloInfo`.
|
||||
- V1 24B `VDIP` codec + `BufferQuota`/`QuotaPermit` + incremental `FrameDecoder` validating magic/version/flags/stream/request ID/limits and reserving global (`64 MiB`) + per-session quotas before payload allocation.
|
||||
- `LocalListener` (0700 owned parent dir, `sun_path < 108`, startup `flock` + failed `connect` stale cleanup, `SOCK_NONBLOCK|SOCK_CLOEXEC`, `fchmod(0600)` before `bind()`, `SO_PEERCRED`), `connect_local`, `adopt_pipe_pair` (`PeerCredentials::available == false`).
|
||||
- Full-duplex `Session` (`handshake`, `start`, `request`, `send_one_way`, `send_goaway`, `close_and_join` rejecting `self_join`), monotonic request IDs, `TokenBucket` per-peer rate limit, reserved control lane (`8 KiB`/`16` frames), `256` late-response tombstones, advisory `cancel`, single terminal completion, zero auto-replay.
|
||||
- `tests/standalone/IPC/Ipc.cpp` & `tests/package/IPCOnly/*`.
|
||||
|
||||
## 3. Edge cases
|
||||
- Oversize/corrupt headers fail before any payload allocation or quota charge.
|
||||
- Saturated data lane still delivers reserved control-lane `cancel`/`overloaded`/`rate_limited` replies without deadlock.
|
||||
- Peer disconnect faults active requests once with `transport_lost` and `EffectStatus::unknown`.
|
||||
|
||||
## 4. Verification commands
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-ipc -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="IPC;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-ipc && /tmp/void-w6a-ipc/tests/VoidTests --filter "Ipc*" && ctest --test-dir /tmp/void-w6a-ipc --output-on-failure --timeout 120'
|
||||
```
|
||||
@@ -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'
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
# Task Spec: `S-RPC-01..03` — NEW `Void::RPC` Subsystem (Wire v1 Binary Codec & Unary HTTP/1.1 Transport)
|
||||
|
||||
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
|
||||
- **Roadmap authority**: `docs/roadmap/subsystems/RPC.md` (`S-RPC-01`..`S-RPC-03`), `ARCHITECTURE.md` C-02..C-07, C-11..C-13.
|
||||
- **Error domain**: `Void::Result::kRpcErrorDomain = 29`.
|
||||
|
||||
## Scope & Deliverables
|
||||
|
||||
1. **Module Boundary (`src/RPC/module.cmake`)**:
|
||||
- `void_add_module(RPC INTERNAL_DEPS Core Functional Binary Data Time Async Net)`.
|
||||
- Zero dependency on `Coordination`, `Discovery`, `Replication`, `Security`, or platform hosts.
|
||||
2. **Types & Limits (`include/Void/RPC/Types.hpp`)**:
|
||||
- `RpcStatusCode` (`Ok`, `Cancelled`, `InvalidArgument`, `DeadlineExceeded`, `NotFound`, `PermissionDenied`, `Unauthenticated`, `ResourceExhausted`, `FailedPrecondition`, `Unimplemented`, `Unavailable`, `Internal`, `DataLoss`, `UnknownOutcome`, `ProtocolError`, `IncompatibleVersion`).
|
||||
- `MethodId{service, method}`, `PrincipalView` (immutable authenticated principal attributes), `MetadataEntry`, `MethodDescriptor{id, service_name, method_name, schema_version, replay_safe}`.
|
||||
- `RpcLimits`: `max_header_bytes = 16 KiB`, `max_metadata_entries = 64`, `max_payload_bytes = 4 MiB`, `max_client_calls = 1024`, `max_server_executing = 256`, `max_server_queued_bytes = 64 MiB`, `max_server_timeout = 30s`.
|
||||
3. **Wire v1 Binary Envelope Codec (`include/Void/RPC/Codec.hpp`, `src/RPC/Codec.cpp`)**:
|
||||
- Explicit network byte order via `Void::Binary::Writer`/`Reader`:
|
||||
- 4-byte magic `VRPC`, `u16 major (1)`, `u16 minor (0)`, `u32 header_length`, `u32 total_length`, `u8 frame_kind`, `u8 flags`, `u16 reserved (0)`, 128-bit `call_id` (`Uuid`), `u64 service_id`, `u32 method_id`, `u32 schema_version`, `u32 remaining_timeout_ms`, `u16 status_code`, `u16 metadata_count`, length-delimited metadata pairs, payload bytes.
|
||||
- Strict bounds/overflow checks BEFORE allocating metadata/payload; rejects bad magic, unsupported major, non-zero reserved field, unknown required flags, truncated/extra bytes, oversized header/metadata/payload; skips unknown optional minor trailing header extensions cleanly.
|
||||
4. **Unary HTTP/1.1 Server & Client (`include/Void/RPC/Rpc.hpp`, `src/RPC/Rpc.cpp`)**:
|
||||
- `CallContext` (`call_id`, `principal`, local steady `deadline`, `remaining_timeout()`, `metadata`, `stop`).
|
||||
- `AuthHook` (`authenticate(headers, metadata) -> Result<PrincipalView>` and `authorize(MethodDescriptor, PrincipalView) -> Result<void>`) executed outside dispatch locks before handler admission.
|
||||
- `Server`: binds methods returning move-only RAII `Registration` (destructor/explicit `unregister_and_drain()` stops admission and waits for in-flight calls), mounts `/void-rpc/v1/call` on `Void::Net::HttpServer`, validates wire v1 envelope, schema version, auth/authz, concurrency/payload budgets, clamps relative timeout to `limits.max_server_timeout`, executes handlers outside locks, and translates handler errors/exceptions into sanitized `RpcStatus`.
|
||||
- `Client`: encodes wire v1 unary request envelope, sends HTTP/1.1 POST to `/void-rpc/v1/call` via `Void::Net::HttpClient`, propagates remaining relative timeout and `std::stop_token`, separates HTTP transport failures from RPC domain status, enforces client concurrency & payload limits, never implicitly retries non-`replay_safe` methods.
|
||||
5. **Installed Consumer (`tests/package/RpcOnly/`)**:
|
||||
- Register `RpcOnly` in `tests/package/InstalledComponents.cmake` proving `Void::RPC` links cleanly without `LibArchive`, `PkgConfig`, or `SQLite3`.
|
||||
|
||||
## Verification
|
||||
- Standalone `RPC;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`): wire v1 round-trip, overflow/truncation/unknown-major/reserved-flag rejection, loopback unary calls, schema mismatch, auth/authz denial, deadline clamping, handler exception sanitization, unregister drain under concurrent load.
|
||||
- `ctest` (`RpcOnly`), full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
|
||||
@@ -0,0 +1,27 @@
|
||||
# S-STORAGE-01..06 — Original Durable Key-Value Storage Engine (`G-STORE`)
|
||||
|
||||
- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`)
|
||||
- **Roadmap reference**: `docs/roadmap/subsystems/Storage.md`, `docs/roadmap/DEPENDENCIES.md`
|
||||
|
||||
## Scope & Ownership
|
||||
- Zero SQLite dependency (`src/Storage/module.cmake`: `INTERNAL_DEPS Core Functional Time Memory Binary IO Async`, zero external deps).
|
||||
- `include/Void/Storage/Crc32c.hpp`: native Castagnoli CRC32C (`0x1EDC6F41` / reflected `0x82F63B78`, golden `"123456789"` == `0xE3069283`).
|
||||
- `include/Void/Storage/Types.hpp`: `kStorageErrorDomain = 9`, `StorageErrorCode`, `Sequence`, `ByteView`, `OwnedBytes`, `OwnedValue`, `Durability::{Sync,Buffered}`, `Outcome::{NotCommitted,Committed,Unknown}`, `Limits` (all roadmap defaults + non-zero validation), `CommitReceipt`, `WriteFailure`, `ScanBounds` (with `prefix`), `ScanEntry`, `ScanPage`, `EngineState`, `EngineStats`, unsigned-byte lexicographic comparator.
|
||||
- `include/Void/Storage/FilePort.hpp` + `src/Storage/FilePort.cpp`: `FilePort`, `FileHandle`, `PosixFilePort` (exclusive `flock`, `EINTR`/short-write loops, file & dir `fsync`, atomic same-dir rename capability check), and `FaultInjectingFilePort` for deterministic power-loss / short-write / sync-failure / rename-failure / unsynced-discard simulation.
|
||||
- `include/Void/Storage/Format.hpp` + `src/Storage/Format.cpp`:
|
||||
- V1 WAL (`VOIDWAL1` 64B segment header with CRC32C, 36B `VWR1` record header with header CRC32C checked before allocating payload, 8B trailer with record CRC32C + repeated length, `BEGIN`/`PUT`/`ERASE`/`COMMIT` payloads with aggregate CRC32C).
|
||||
- V1 Immutable Sorted Table (`VOIDTBL1` header, 32 KiB target sorted blocks with per-block CRC32C, sparse block index, checksummed `VOIDTBF1` footer).
|
||||
- V1 Immutable Manifest (`VOIDMNF1`) and atomic `CURRENT` (`VOIDCUR1`).
|
||||
- `include/Void/Storage/Batch.hpp`, `include/Void/Storage/Engine.hpp`, `src/Storage/Engine.cpp`:
|
||||
- Conditional atomic `Batch` (`put`, `erase`, `require_absent`, `require_version`, `require_value`; rejects duplicate keys/conditions; sequence-based versioning prevents ABA).
|
||||
- Exclusive directory lock, minimal `CURRENT`/manifest bootstrap & WAL segment rotation publication before write admission, deterministic recovery with tail-only truncation of final active segment and fail-closed `corrupt` on damaged complete records or earlier closed segments.
|
||||
- Single serialized writer, pre-append reservation/encoding, infallible visibility publication, `RecoveryRequired` + `Outcome::Unknown` on post-append failure, pinned `Snapshot`/`Cursor` with continuation scans and `page_too_small` enforcement.
|
||||
- `checkpoint()` freezing memtable -> immutable table -> manifest -> `CURRENT` -> deferred retirement after snapshot pins release; bounded incremental `compact()` merging <= 4 overlapping runs while preserving versions needed by live snapshots.
|
||||
- `include/Void/Storage/Tools.hpp` + `src/Storage/Tools.cpp`: `verify_directory` (full block-level read-only verification), pinned `export_backup` / `restore_backup`, offline `salvage_directory` into a separate destination.
|
||||
- `include/Void/Storage/AsyncAdapter.hpp` + `src/Storage/AsyncAdapter.cpp`: bounded blocking async adapter following C-03 domain-result classification (`stop before append -> NotCommitted`, `stop during sync -> retain until settled`, `sync succeeds after stop -> CommitReceipt`, `sync fails after append -> Unknown + RecoveryRequired`, single delivery).
|
||||
- `include/Void/Storage/Storage.hpp`: umbrella header.
|
||||
- Tests & consumer: `tests/standalone/Storage/Storage.cpp` (CRC32C golden, format/overflow, model checker vs reference map, byte-offset truncation, corruption, fault-injected creation/rotation/sync/checkpoint/compaction crashes, retention under slow snapshots, async stop-race conformance, verify/backup/salvage), `tests/package/StorageOnly/*`, updated `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## Verification Criteria
|
||||
- Standalone `Storage;Testing` RelWithDebInfo `-Werror` (zero external deps!): `storage_*` tests + `ctest` 2/2 (`StorageOnly`).
|
||||
- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset.
|
||||
@@ -1,11 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Archive/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Archive
|
||||
{
|
||||
@@ -21,12 +29,191 @@ namespace Void::Archive
|
||||
std::uint64_t bytes{0};
|
||||
};
|
||||
|
||||
/// Extract a tar/tar.zst archive without invoking an external process.
|
||||
/// Only regular files and directories are accepted. Absolute/traversal
|
||||
/// paths, links, special files, duplicates and configured size/count
|
||||
/// overages fail the whole operation.
|
||||
/// Returns true if Void::Archive was built with LibArchive support (required
|
||||
/// for .tar.zst and .tar.gz compression/decompression; uncompressed USTAR/PAX
|
||||
/// .tar reading and writing work with zero external dependencies).
|
||||
[[nodiscard]] bool has_libarchive_backend() noexcept;
|
||||
|
||||
/// Extract a tar/tar.gz/tar.zst archive incrementally into `destination`
|
||||
/// without invoking an external process. Preserved 1.x incremental API;
|
||||
/// callers requiring all-or-nothing directory visibility should use
|
||||
/// `extract_staged` + `StagedTree::publish`.
|
||||
[[nodiscard]] Void::Result::Result<ExtractionResult>
|
||||
extract(const std::filesystem::path& archivePath,
|
||||
const std::filesystem::path& destination,
|
||||
const ExtractionOptions& options = {});
|
||||
|
||||
/// Caller-driven bounded tar/tar.zst reader. Maintains one active entry at
|
||||
/// a time; callers must drain (`read_chunk` returning 0) or call
|
||||
/// `skip_entry()` before advancing with `next_entry()`.
|
||||
class Reader
|
||||
{
|
||||
public:
|
||||
|
||||
~Reader();
|
||||
Reader(Reader&&) noexcept;
|
||||
Reader& operator=(Reader&&) noexcept;
|
||||
Reader(const Reader&) = delete;
|
||||
Reader& operator=(const Reader&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Reader> open(
|
||||
ByteSource& source, ReadLimits limits = {},
|
||||
std::stop_token stop = {},
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline =
|
||||
std::nullopt,
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Reader> open_file(
|
||||
const std::filesystem::path& archive_path,
|
||||
ReadLimits limits = {}, std::stop_token stop = {},
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline =
|
||||
std::nullopt,
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
|
||||
/// Advance to the next archive entry. Returns std::nullopt on clean
|
||||
/// EOF.
|
||||
[[nodiscard]] Void::Result::Result<std::optional<EntryInfo>>
|
||||
next_entry();
|
||||
|
||||
/// Read up to dst.size() decompressed bytes of the active regular
|
||||
/// file entry. Returns 0 on entry EOF.
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
read_chunk(std::span<std::byte> dst);
|
||||
|
||||
/// Drain and discard remaining bytes of the active entry while
|
||||
/// still accounting decompressed bytes against policy limits.
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry();
|
||||
|
||||
[[nodiscard]] std::size_t entries_seen() const noexcept;
|
||||
[[nodiscard]] std::uint64_t total_decompressed_bytes() const noexcept;
|
||||
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> m_impl;
|
||||
explicit Reader(std::unique_ptr<Impl> impl) noexcept;
|
||||
};
|
||||
|
||||
/// Bounded metadata listing of archive entries. Normal mode (`forensic =
|
||||
/// false`) rejects unsafe/duplicate/conflicting entries. Opt-in forensic
|
||||
/// mode reports rejected entries without writing to disk.
|
||||
[[nodiscard]] Void::Result::Result<std::vector<EntryInfo>>
|
||||
list_entries(ByteSource& source, ReadLimits limits = {},
|
||||
bool forensic = false);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<EntryInfo>>
|
||||
list_entries(const std::filesystem::path& archive_path,
|
||||
ReadLimits limits = {}, bool forensic = false);
|
||||
|
||||
/// Move-only handle owning an unpublished private staging directory beneath
|
||||
/// a pinned parent directory. Unlinks only names under its staging
|
||||
/// descriptor without following links if destroyed before publication.
|
||||
class StagedTree
|
||||
{
|
||||
public:
|
||||
|
||||
StagedTree() noexcept = default;
|
||||
~StagedTree() noexcept;
|
||||
StagedTree(StagedTree&&) noexcept;
|
||||
StagedTree& operator=(StagedTree&&) noexcept;
|
||||
StagedTree(const StagedTree&) = delete;
|
||||
StagedTree& operator=(const StagedTree&) = delete;
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept;
|
||||
[[nodiscard]] bool published() const noexcept;
|
||||
[[nodiscard]] std::string_view staging_id() const noexcept;
|
||||
[[nodiscard]] const std::filesystem::path&
|
||||
staging_root() const noexcept;
|
||||
[[nodiscard]] const std::filesystem::path&
|
||||
tree_path() const noexcept;
|
||||
[[nodiscard]] std::size_t entries() const noexcept;
|
||||
[[nodiscard]] std::uint64_t bytes() const noexcept;
|
||||
[[nodiscard]] const std::vector<EntryInfo>&
|
||||
inventory() const noexcept;
|
||||
|
||||
/// Publish the staged tree into a previously absent immediate child
|
||||
/// of the pinned parent directory using atomic no-replace rename
|
||||
/// (`renameat2(..., RENAME_NOREPLACE)`). Never overwrites existing
|
||||
/// directories or falls back to a racy existence check.
|
||||
[[nodiscard]] Void::Result::Result<PublicationReceipt>
|
||||
publish(std::string_view new_child_name);
|
||||
|
||||
/// Explicitly discard an unpublished staging tree.
|
||||
[[nodiscard]] Void::Result::Result<void> discard();
|
||||
|
||||
private:
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> m_impl;
|
||||
explicit StagedTree(std::unique_ptr<Impl> impl) noexcept;
|
||||
|
||||
friend Void::Result::Result<StagedTree>
|
||||
extract_staged(ByteSource& source,
|
||||
const std::filesystem::path& parent_directory,
|
||||
const StagedExtractionOptions& options);
|
||||
friend Void::Result::Result<StagedTree>
|
||||
extract_staged_isolated(
|
||||
const std::filesystem::path& archive_path,
|
||||
const std::filesystem::path& parent_directory,
|
||||
const IsolationOptions& options);
|
||||
};
|
||||
|
||||
/// Extract a tar/tar.zst stream into an exclusive 0700 staging directory
|
||||
/// beneath `parent_directory`, fsync files and directories bottom-up, write
|
||||
/// a bounded completion inventory, and return an unpublished StagedTree.
|
||||
[[nodiscard]] Void::Result::Result<StagedTree>
|
||||
extract_staged(ByteSource& source,
|
||||
const std::filesystem::path& parent_directory,
|
||||
const StagedExtractionOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<StagedTree>
|
||||
extract_staged(const std::filesystem::path& archive_path,
|
||||
const std::filesystem::path& parent_directory,
|
||||
const StagedExtractionOptions& options = {});
|
||||
|
||||
/// Remove abandoned staging directories under `parent_directory` that carry
|
||||
/// a valid exclusive operation marker owned by the current user and are at
|
||||
/// least `min_age` old. Never touches directories without a valid marker.
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
cleanup_stale_staging(const std::filesystem::path& parent_directory,
|
||||
std::chrono::seconds min_age =
|
||||
std::chrono::seconds{300});
|
||||
|
||||
/// Create a bounded, optionally reproducible tar, tar.gz, or tar.zst
|
||||
/// archive from regular file and directory entries. Sorts normalized
|
||||
/// paths, rejects duplicates/conflicts, and opens source files with O_NOFOLLOW.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create_archive(ByteSink& sink, std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create_archive(const std::filesystem::path& output_path,
|
||||
std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
|
||||
/// Canonical snake_case alias for `create_archive`.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create(ByteSink& sink, std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create(const std::filesystem::path& output_path,
|
||||
std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
|
||||
/// Hardened untrusted-input profile: extracts the archive in an isolated
|
||||
/// System child process with bounded execution time and RSS checks, then
|
||||
/// independently verifies the staged tree and inventory in the parent
|
||||
/// before returning StagedTree.
|
||||
[[nodiscard]] Void::Result::Result<StagedTree>
|
||||
extract_staged_isolated(const std::filesystem::path& archive_path,
|
||||
const std::filesystem::path& parent_directory,
|
||||
const IsolationOptions& options);
|
||||
|
||||
/// Entry point invoked by the isolated archive decoder worker binary.
|
||||
[[nodiscard]] int run_isolated_worker_main(int argc, char** argv);
|
||||
|
||||
} // namespace Void::Archive
|
||||
@@ -0,0 +1,347 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Archive
|
||||
{
|
||||
enum class ArchiveErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
unsafe_entry = 2,
|
||||
unsupported_format = 3,
|
||||
corrupt_archive = 4,
|
||||
limit_exceeded = 5,
|
||||
permission_denied = 6,
|
||||
no_space = 7,
|
||||
io_error = 8,
|
||||
cancelled = 9,
|
||||
timeout = 10,
|
||||
unknown_publication = 11,
|
||||
unsupported_capability = 12,
|
||||
already_exists = 13,
|
||||
conflict = 14,
|
||||
isolation_failed = 15
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_archive_error(ArchiveErrorCode code, std::string message = {},
|
||||
std::error_code sys_err = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case ArchiveErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case ArchiveErrorCode::invalid_argument:
|
||||
case ArchiveErrorCode::unsafe_entry:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case ArchiveErrorCode::unsupported_format:
|
||||
case ArchiveErrorCode::unsupported_capability:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case ArchiveErrorCode::corrupt_archive:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case ArchiveErrorCode::limit_exceeded:
|
||||
case ArchiveErrorCode::no_space:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case ArchiveErrorCode::permission_denied:
|
||||
case ArchiveErrorCode::io_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case ArchiveErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case ArchiveErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case ArchiveErrorCode::already_exists:
|
||||
case ArchiveErrorCode::conflict:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case ArchiveErrorCode::unknown_publication:
|
||||
case ArchiveErrorCode::isolation_failed:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
}
|
||||
|
||||
const ErrorCode domain_code{Void::Result::kArchiveErrorDomain,
|
||||
static_cast<std::int32_t>(code)};
|
||||
return Error{kind, std::move(message), domain_code, sys_err};
|
||||
}
|
||||
|
||||
/// Render an untrusted archive entry path safely for diagnostics: capped at
|
||||
/// 4 KiB with control characters and newlines escaped.
|
||||
[[nodiscard]] std::string
|
||||
sanitize_diagnostic_path(std::string_view raw) noexcept;
|
||||
|
||||
struct ReadLimits {
|
||||
std::size_t max_entries{10'000};
|
||||
bool allow_zero_entries{false};
|
||||
std::uint64_t max_file_bytes{512ULL * 1024 * 1024};
|
||||
std::uint64_t max_total_bytes{2ULL * 1024 * 1024 * 1024};
|
||||
std::uint64_t max_compressed_bytes{1ULL * 1024 * 1024 * 1024};
|
||||
std::size_t max_metadata_bytes{8ULL * 1024 * 1024};
|
||||
std::size_t transfer_buffer_bytes{64ULL * 1024};
|
||||
std::size_t max_path_bytes{4096};
|
||||
std::size_t max_component_bytes{255};
|
||||
std::size_t max_path_components{64};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate() const
|
||||
{
|
||||
if ((max_entries == 0 && !allow_zero_entries) ||
|
||||
max_file_bytes == 0 || max_total_bytes == 0 ||
|
||||
max_compressed_bytes == 0 || max_metadata_bytes == 0 ||
|
||||
transfer_buffer_bytes == 0 || max_path_bytes == 0 ||
|
||||
max_component_bytes == 0 || max_path_components == 0) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::invalid_argument,
|
||||
"Archive::ReadLimits: limits must be non-zero unless "
|
||||
"allow_zero_entries is explicitly enabled")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
enum class EntryType : std::uint8_t {
|
||||
RegularFile = 0,
|
||||
Directory,
|
||||
Symlink,
|
||||
Hardlink,
|
||||
Other
|
||||
};
|
||||
|
||||
struct EntryInfo {
|
||||
std::string path{};
|
||||
EntryType type{EntryType::RegularFile};
|
||||
std::uint64_t declared_size{0};
|
||||
std::uint32_t safe_mode{0644};
|
||||
bool executable{false};
|
||||
bool accepted{true};
|
||||
std::string rejection_reason{};
|
||||
};
|
||||
|
||||
struct ProgressEvent {
|
||||
std::size_t entries_processed{0};
|
||||
std::uint64_t bytes_extracted{0};
|
||||
std::string current_path{};
|
||||
};
|
||||
|
||||
using ProgressCallback = std::function<void(const ProgressEvent&)>;
|
||||
|
||||
enum class PublicationOutcome : std::uint8_t {
|
||||
Published = 0,
|
||||
NotPublished,
|
||||
Unknown
|
||||
};
|
||||
|
||||
struct PublicationReceipt {
|
||||
PublicationOutcome outcome{PublicationOutcome::NotPublished};
|
||||
std::filesystem::path destination_path{};
|
||||
std::string staging_id{};
|
||||
std::size_t entries{0};
|
||||
std::uint64_t bytes{0};
|
||||
std::string diagnostic{};
|
||||
};
|
||||
|
||||
struct StagedExtractionOptions {
|
||||
ReadLimits limits{};
|
||||
bool preserve_executable_bit{true};
|
||||
std::stop_token stop{};
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
|
||||
const Void::Time::MonotonicClock* clock{nullptr};
|
||||
ProgressCallback on_progress{};
|
||||
};
|
||||
|
||||
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd, Gzip };
|
||||
|
||||
struct CreationOptions {
|
||||
ArchiveCompression compression{ArchiveCompression::Zstd};
|
||||
bool reproducible{true};
|
||||
ReadLimits limits{};
|
||||
std::stop_token stop{};
|
||||
std::int64_t canonical_mtime{0};
|
||||
std::uint32_t canonical_uid{0};
|
||||
std::uint32_t canonical_gid{0};
|
||||
bool prefer_builtin_tar{false};
|
||||
};
|
||||
|
||||
struct CreateEntry {
|
||||
std::string path{};
|
||||
EntryType type{EntryType::RegularFile};
|
||||
bool executable{false};
|
||||
std::vector<std::byte> content{};
|
||||
std::optional<std::filesystem::path> source_file{};
|
||||
std::optional<std::uint32_t> mode{};
|
||||
};
|
||||
|
||||
struct IsolationOptions {
|
||||
std::filesystem::path worker_executable{};
|
||||
std::uint64_t max_rss_bytes{128ULL * 1024 * 1024};
|
||||
std::chrono::milliseconds timeout{std::chrono::seconds{60}};
|
||||
StagedExtractionOptions extraction{};
|
||||
};
|
||||
|
||||
/// Synchronous byte source interface borrowed through completion.
|
||||
class ByteSource
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~ByteSource() = default;
|
||||
/// Read up to dst.size() bytes. Returns 0 on clean EOF.
|
||||
[[nodiscard]] virtual Void::Result::Result<std::size_t>
|
||||
read(std::span<std::byte> dst) = 0;
|
||||
};
|
||||
|
||||
/// Synchronous byte sink interface borrowed through completion.
|
||||
class ByteSink
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~ByteSink() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
write(std::span<const std::byte> src) = 0;
|
||||
};
|
||||
|
||||
class SpanByteSource final : public ByteSource
|
||||
{
|
||||
public:
|
||||
|
||||
explicit SpanByteSource(std::span<const std::byte> data) noexcept
|
||||
: m_data(data)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
read(std::span<std::byte> dst) override;
|
||||
|
||||
private:
|
||||
|
||||
std::span<const std::byte> m_data{};
|
||||
std::size_t m_offset{0};
|
||||
};
|
||||
|
||||
class FileByteSource final : public ByteSource
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<FileByteSource>
|
||||
open(const std::filesystem::path& path);
|
||||
|
||||
FileByteSource(FileByteSource&&) noexcept;
|
||||
FileByteSource& operator=(FileByteSource&&) noexcept;
|
||||
~FileByteSource() override;
|
||||
|
||||
FileByteSource(const FileByteSource&) = delete;
|
||||
FileByteSource& operator=(const FileByteSource&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
read(std::span<std::byte> dst) override;
|
||||
|
||||
private:
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> m_impl;
|
||||
explicit FileByteSource(std::unique_ptr<Impl> impl) noexcept;
|
||||
};
|
||||
|
||||
class VectorByteSink final : public ByteSink
|
||||
{
|
||||
public:
|
||||
|
||||
explicit VectorByteSink(
|
||||
std::size_t max_bytes = 256ULL * 1024 * 1024) noexcept
|
||||
: m_max_bytes(max_bytes)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
write(std::span<const std::byte> src) override;
|
||||
|
||||
[[nodiscard]] const std::vector<std::byte>& bytes() const noexcept
|
||||
{
|
||||
return m_bytes;
|
||||
}
|
||||
[[nodiscard]] std::vector<std::byte> take_bytes() noexcept
|
||||
{
|
||||
return std::move(m_bytes);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::size_t m_max_bytes{256ULL * 1024 * 1024};
|
||||
std::vector<std::byte> m_bytes{};
|
||||
};
|
||||
|
||||
class FileByteSink final : public ByteSink
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<FileByteSink>
|
||||
create(const std::filesystem::path& path);
|
||||
|
||||
FileByteSink(FileByteSink&&) noexcept;
|
||||
FileByteSink& operator=(FileByteSink&&) noexcept;
|
||||
~FileByteSink() override;
|
||||
|
||||
FileByteSink(const FileByteSink&) = delete;
|
||||
FileByteSink& operator=(const FileByteSink&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
write(std::span<const std::byte> src) override;
|
||||
[[nodiscard]] Void::Result::Result<void> sync_and_close();
|
||||
|
||||
private:
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> m_impl;
|
||||
explicit FileByteSink(std::unique_ptr<Impl> impl) noexcept;
|
||||
};
|
||||
|
||||
enum class FaultPoint : std::uint8_t {
|
||||
none = 0,
|
||||
rename_enosys,
|
||||
post_rename_parent_sync,
|
||||
staging_cleanup_fail
|
||||
};
|
||||
|
||||
class ScopedFaultGuard
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ScopedFaultGuard(FaultPoint point) noexcept;
|
||||
~ScopedFaultGuard() noexcept;
|
||||
|
||||
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
|
||||
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
FaultPoint m_previous{FaultPoint::none};
|
||||
};
|
||||
|
||||
} // namespace Void::Archive
|
||||
@@ -188,7 +188,7 @@ public:
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
std::array<std::byte, sizeof(T)> storage{};
|
||||
std::ranges::copy(*bytes, storage.begin());
|
||||
std::memcpy(storage.data(), bytes->data(), sizeof(T));
|
||||
T value = std::bit_cast<T>(storage);
|
||||
if (byteOrder != std::endian::native) {
|
||||
value = std::byteswap(value);
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
#include <Void/Core/Meta.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
@@ -11,23 +14,56 @@
|
||||
namespace Void::Argparse
|
||||
{
|
||||
|
||||
enum class ParseOutcome : std::uint8_t {
|
||||
Ok,
|
||||
Help,
|
||||
Error,
|
||||
};
|
||||
|
||||
struct ParseResult {
|
||||
ParseOutcome outcome{ParseOutcome::Ok};
|
||||
std::string message{};
|
||||
std::vector<std::string> matched_command_path{};
|
||||
|
||||
[[nodiscard]] bool ok() const noexcept
|
||||
{
|
||||
return outcome == ParseOutcome::Ok;
|
||||
}
|
||||
[[nodiscard]] bool is_help() const noexcept
|
||||
{
|
||||
return outcome == ParseOutcome::Help;
|
||||
}
|
||||
[[nodiscard]] bool is_error() const noexcept
|
||||
{
|
||||
return outcome == ParseOutcome::Error;
|
||||
}
|
||||
};
|
||||
|
||||
// ── Parser
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// Fluent command-line argument parser.
|
||||
//
|
||||
// Supports:
|
||||
// --flag, -f boolean flag (default false, set to true by
|
||||
// presence)
|
||||
// presence)
|
||||
// --key=value option with value (= or space separator)
|
||||
// --key value option with value
|
||||
// option_many(...) repeatable option collecting all occurrences
|
||||
// subcommand(...) nested subcommand parsers (e.g. "compdb use")
|
||||
// positional args collected in declaration order
|
||||
// --help / -h auto-generated help text
|
||||
// --help / -h auto-generated help text (ParseOutcome::Help)
|
||||
|
||||
class Parser
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Parser(std::string program, std::string description = {});
|
||||
~Parser();
|
||||
|
||||
Parser(const Parser&) = delete;
|
||||
Parser& operator=(const Parser&) = delete;
|
||||
Parser(Parser&&) noexcept;
|
||||
Parser& operator=(Parser&&) noexcept;
|
||||
|
||||
// Add a boolean flag.
|
||||
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name
|
||||
@@ -43,6 +79,12 @@ namespace Void::Argparse
|
||||
std::string_view description,
|
||||
std::optional<std::string>& out);
|
||||
|
||||
// Add a repeatable option collecting all occurrences into `out`.
|
||||
Parser& option_many(std::string_view long_name,
|
||||
std::string_view short_name,
|
||||
std::string_view description,
|
||||
std::vector<std::string>& out);
|
||||
|
||||
// Add an option with a default value. out is always set after
|
||||
// parse().
|
||||
Parser& option_default(std::string_view long_name,
|
||||
@@ -55,7 +97,28 @@ namespace Void::Argparse
|
||||
Parser& positional(std::string_view name,
|
||||
std::string_view description, std::string& out);
|
||||
|
||||
// Parse argc/argv. Returns error message on failure.
|
||||
// Add a variadic trailing positional argument list.
|
||||
Parser& positional_many(std::string_view name,
|
||||
std::string_view description,
|
||||
std::vector<std::string>& out,
|
||||
bool required = false);
|
||||
|
||||
// Register a nested subcommand and return a reference to its
|
||||
// Parser. The returned reference remains valid for the lifetime of
|
||||
// the parent Parser.
|
||||
Parser& subcommand(std::string name, std::string description = {},
|
||||
std::function<void()> on_selected = {});
|
||||
|
||||
// Control whether a parser with subcommands requires one to be
|
||||
// selected (default: true when any subcommand is registered).
|
||||
Parser& require_subcommand(bool required = true) noexcept;
|
||||
|
||||
// Parse argc/argv with explicit Ok / Help / Error classification.
|
||||
[[nodiscard]] ParseResult
|
||||
parse_detailed(int argc, const char* const* argv) const;
|
||||
|
||||
// Parse argc/argv. Returns error message (or help text) on
|
||||
// non-Ok outcome for 1.x compatibility.
|
||||
[[nodiscard]] std::expected<void, std::string>
|
||||
parse(int argc, const char* const* argv) const;
|
||||
|
||||
@@ -70,18 +133,33 @@ namespace Void::Argparse
|
||||
};
|
||||
struct OptionEntry {
|
||||
std::string lng, sht, desc, def;
|
||||
std::optional<std::string>* out_opt;
|
||||
std::string* out_str;
|
||||
std::optional<std::string>* out_opt{nullptr};
|
||||
std::string* out_str{nullptr};
|
||||
std::vector<std::string>* out_many{nullptr};
|
||||
};
|
||||
struct PosEntry {
|
||||
std::string name, desc;
|
||||
std::string* out;
|
||||
};
|
||||
struct MultiPosEntry {
|
||||
std::string name, desc;
|
||||
std::vector<std::string>* out{nullptr};
|
||||
bool required{false};
|
||||
};
|
||||
struct SubcommandEntry {
|
||||
std::string name;
|
||||
std::unique_ptr<Parser> parser;
|
||||
std::function<void()> on_selected;
|
||||
};
|
||||
|
||||
std::string program_, description_;
|
||||
std::vector<FlagEntry> flags_;
|
||||
std::vector<OptionEntry> options_;
|
||||
std::vector<PosEntry> positionals_;
|
||||
std::optional<MultiPosEntry> positional_many_;
|
||||
std::vector<SubcommandEntry> subcommands_;
|
||||
bool has_explicit_require_sub_{false};
|
||||
bool require_subcommand_{true};
|
||||
};
|
||||
|
||||
// ── reflective options struct
|
||||
@@ -147,6 +225,8 @@ namespace Void::Argparse
|
||||
parser.flag(lng, sht, desc, out.[:m:]);
|
||||
} else if constexpr (Void::Meta::is_optional_v<MT>) {
|
||||
parser.option(lng, sht, desc, out.[:m:]);
|
||||
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
|
||||
parser.option_many(lng, sht, desc, out.[:m:]);
|
||||
} else if constexpr (std::same_as<MT, std::string>) {
|
||||
const std::string def = out.[:m:];
|
||||
parser.option_default(lng, sht, desc, out.[:m:], def);
|
||||
|
||||
@@ -51,6 +51,21 @@ namespace Void::Configuration
|
||||
};
|
||||
struct Required {
|
||||
};
|
||||
struct Secret {
|
||||
};
|
||||
struct RestartRequired {
|
||||
};
|
||||
struct Deprecated {
|
||||
Void::Meta::Str message;
|
||||
};
|
||||
struct IntRange {
|
||||
std::int64_t min{0};
|
||||
std::int64_t max{0};
|
||||
};
|
||||
struct RealRange {
|
||||
double min{0.0};
|
||||
double max{0.0};
|
||||
};
|
||||
|
||||
#ifdef VOID_HAS_CONFIG_REFLECTION
|
||||
|
||||
|
||||
@@ -0,0 +1,784 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Configuration/Schema.hpp>
|
||||
#include <Void/System/AsyncWatcher.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <coroutine>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <exception>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Configuration
|
||||
{
|
||||
struct PreparedChange {
|
||||
std::shared_ptr<const void> view{};
|
||||
std::size_t declared_budget_bytes{0};
|
||||
std::function<Void::Coro::Task<Void::Result::Result<void>>()>
|
||||
dispose_async{};
|
||||
};
|
||||
|
||||
template <typename T> struct Snapshot {
|
||||
std::uint64_t generation{0};
|
||||
std::shared_ptr<const T> values{};
|
||||
std::shared_ptr<const Provenance> provenance{};
|
||||
std::shared_ptr<const MergedConfig> raw{};
|
||||
std::shared_ptr<
|
||||
const std::unordered_map<std::string, std::shared_ptr<const void>>>
|
||||
resources{};
|
||||
std::shared_ptr<const void> retention_token{};
|
||||
|
||||
template <typename R>
|
||||
[[nodiscard]] std::shared_ptr<const R>
|
||||
resource(std::string_view participant_id) const
|
||||
{
|
||||
if (!resources) {
|
||||
return nullptr;
|
||||
}
|
||||
const auto it = resources->find(std::string{participant_id});
|
||||
if (it == resources->end()) {
|
||||
return nullptr;
|
||||
}
|
||||
return std::static_pointer_cast<const R>(it->second);
|
||||
}
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return values != nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> struct PreparedAggregate {
|
||||
std::shared_ptr<const T> values{};
|
||||
std::shared_ptr<const Provenance> provenance{};
|
||||
std::shared_ptr<const MergedConfig> raw{};
|
||||
std::shared_ptr<
|
||||
const std::unordered_map<std::string, std::shared_ptr<const void>>>
|
||||
resources{};
|
||||
std::vector<PreparedChange> staged_changes{};
|
||||
std::vector<std::string> changed_keys{};
|
||||
std::vector<std::string> warnings{};
|
||||
|
||||
Void::Coro::Task<Void::Result::Result<void>> dispose_all()
|
||||
{
|
||||
for (auto it = staged_changes.rbegin();
|
||||
it != staged_changes.rend(); ++it) {
|
||||
if (it->dispose_async) {
|
||||
(void)co_await it->dispose_async();
|
||||
}
|
||||
}
|
||||
staged_changes.clear();
|
||||
co_return Void::Result::Result<void>{};
|
||||
}
|
||||
};
|
||||
|
||||
struct ReloadReport {
|
||||
std::uint64_t generation{0};
|
||||
bool committed{false};
|
||||
bool restart_required{false};
|
||||
std::vector<std::string> restart_required_keys{};
|
||||
bool stop_observed_after_commit{false};
|
||||
std::vector<std::string> changed_keys{};
|
||||
std::vector<Void::Result::Error> notification_errors{};
|
||||
std::vector<std::string> warnings{};
|
||||
std::size_t coalesced_events{0};
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
class AsyncReloadGate
|
||||
{
|
||||
public:
|
||||
|
||||
struct Waiter {
|
||||
Void::Async::Executor* exec{nullptr};
|
||||
std::coroutine_handle<> h{};
|
||||
};
|
||||
|
||||
struct Guard {
|
||||
AsyncReloadGate* gate{nullptr};
|
||||
Guard() noexcept = default;
|
||||
explicit Guard(AsyncReloadGate* g) noexcept : gate(g) {}
|
||||
Guard(Guard&& o) noexcept
|
||||
: gate(std::exchange(o.gate, nullptr))
|
||||
{
|
||||
}
|
||||
Guard& operator=(Guard&& o) noexcept
|
||||
{
|
||||
if (this != &o) {
|
||||
if (gate != nullptr) gate->release();
|
||||
gate = std::exchange(o.gate, nullptr);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
~Guard()
|
||||
{
|
||||
if (gate != nullptr) {
|
||||
gate->release();
|
||||
}
|
||||
}
|
||||
Guard(const Guard&) = delete;
|
||||
Guard& operator=(const Guard&) = delete;
|
||||
};
|
||||
|
||||
struct Awaiter {
|
||||
AsyncReloadGate* gate;
|
||||
Void::Async::Executor* exec;
|
||||
bool await_ready() noexcept { return gate->try_lock(); }
|
||||
bool await_suspend(std::coroutine_handle<> h) noexcept
|
||||
{
|
||||
return gate->enqueue_or_acquire(exec, h);
|
||||
}
|
||||
Guard await_resume() noexcept { return Guard{gate}; }
|
||||
};
|
||||
|
||||
Awaiter lock(Void::Async::Executor* exec) noexcept
|
||||
{
|
||||
return Awaiter{this, exec};
|
||||
}
|
||||
|
||||
bool try_lock() noexcept;
|
||||
bool enqueue_or_acquire(Void::Async::Executor* exec,
|
||||
std::coroutine_handle<> h) noexcept;
|
||||
void release() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
std::mutex mu_{};
|
||||
bool locked_{false};
|
||||
std::deque<Waiter> waiters_{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::vector<std::string>
|
||||
diff_merged_keys(const MergedConfig& old_cfg,
|
||||
const MergedConfig& new_cfg);
|
||||
} // namespace detail
|
||||
|
||||
struct ControllerOptions {
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
Void::Async::Executor* executor{nullptr};
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class ReloadController
|
||||
: public std::enable_shared_from_this<ReloadController<T>>
|
||||
{
|
||||
public:
|
||||
|
||||
using PrepareFn = std::function<
|
||||
Void::Coro::Task<Void::Result::Result<PreparedChange>>(
|
||||
const Snapshot<T>& old_snapshot,
|
||||
const std::shared_ptr<const T>& candidate,
|
||||
Void::Async::OperationOptions options)>;
|
||||
|
||||
using CommitListener =
|
||||
std::function<void(const Snapshot<T>& snapshot,
|
||||
const ReloadReport& report)>;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<
|
||||
std::shared_ptr<ReloadController<T>>>
|
||||
create(Schema<T> schema, SourceSet initial_sources,
|
||||
ControllerOptions options = {})
|
||||
{
|
||||
auto merged = load_sources(initial_sources, schema.limits(),
|
||||
schema.secret_keys());
|
||||
if (!merged) {
|
||||
return Void::Result::fail(std::move(merged).error());
|
||||
}
|
||||
auto validated = validate<T>(*merged, schema);
|
||||
if (!validated) {
|
||||
return Void::Result::fail(std::move(validated).error());
|
||||
}
|
||||
|
||||
auto ctrl = std::shared_ptr<ReloadController<T>>(
|
||||
new ReloadController<T>(std::move(schema), options));
|
||||
auto merged_ptr =
|
||||
std::make_shared<const MergedConfig>(std::move(*merged));
|
||||
auto val_ptr =
|
||||
std::make_shared<const T>(std::move(validated->value));
|
||||
auto res_ptr = std::make_shared<const std::unordered_map<
|
||||
std::string, std::shared_ptr<const void>>>();
|
||||
auto tok = std::make_shared<const int>(1);
|
||||
ctrl->m_retention_tokens.push_back(tok);
|
||||
ctrl->m_current = Snapshot<T>{
|
||||
.generation = 1,
|
||||
.values = std::move(val_ptr),
|
||||
.provenance = merged_ptr->provenance,
|
||||
.raw = std::move(merged_ptr),
|
||||
.resources = std::move(res_ptr),
|
||||
.retention_token = std::move(tok),
|
||||
};
|
||||
ctrl->m_generation = 1;
|
||||
return ctrl;
|
||||
}
|
||||
|
||||
~ReloadController() { close_and_join(); }
|
||||
|
||||
ReloadController(const ReloadController&) = delete;
|
||||
ReloadController& operator=(const ReloadController&) = delete;
|
||||
|
||||
[[nodiscard]] Snapshot<T> current() const
|
||||
{
|
||||
std::lock_guard lk{m_pub_mu};
|
||||
return m_current;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t retained_generation_count() const
|
||||
{
|
||||
std::lock_guard lk{m_pub_mu};
|
||||
std::size_t live = 0;
|
||||
for (const auto& w : m_retention_tokens) {
|
||||
if (!w.expired()) ++live;
|
||||
}
|
||||
return live;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
register_participant(std::string id,
|
||||
std::size_t declared_budget_bytes,
|
||||
PrepareFn prepare_fn)
|
||||
{
|
||||
if (id.empty() || !prepare_fn) {
|
||||
return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::invalid_argument,
|
||||
"ReloadController: participant id and callback required"));
|
||||
}
|
||||
std::lock_guard lk{m_part_mu};
|
||||
if (m_closing) {
|
||||
return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::prepare_failed,
|
||||
"ReloadController: controller closing"));
|
||||
}
|
||||
if (m_participants.size() >= m_schema.limits().max_participants) {
|
||||
return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::limit_exceeded,
|
||||
"ReloadController: max_participants exceeded"));
|
||||
}
|
||||
for (const auto& p : m_participants) {
|
||||
if (p.id == id && !p.removing) {
|
||||
return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::key_collision,
|
||||
"ReloadController: duplicate participant id '" +
|
||||
id + "'"));
|
||||
}
|
||||
}
|
||||
m_participants.push_back(ParticipantEntry{
|
||||
.id = std::move(id),
|
||||
.budget_bytes = declared_budget_bytes,
|
||||
.prepare = std::move(prepare_fn),
|
||||
.in_flight = 0,
|
||||
.removing = false,
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
void unregister_participant(std::string_view id)
|
||||
{
|
||||
std::unique_lock lk{m_part_mu};
|
||||
for (auto& p : m_participants) {
|
||||
if (p.id == id) {
|
||||
p.removing = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
m_part_cv.wait(lk, [&] {
|
||||
for (const auto& p : m_participants) {
|
||||
if (p.id == id && p.in_flight > 0) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
std::erase_if(m_participants, [&](const ParticipantEntry& p) {
|
||||
return p.id == id;
|
||||
});
|
||||
}
|
||||
|
||||
std::size_t on_committed(CommitListener listener)
|
||||
{
|
||||
std::lock_guard lk{m_listener_mu};
|
||||
const std::size_t id = m_next_listener_id++;
|
||||
m_listeners.emplace_back(id, std::move(listener));
|
||||
return id;
|
||||
}
|
||||
|
||||
void remove_listener(std::size_t id)
|
||||
{
|
||||
std::lock_guard lk{m_listener_mu};
|
||||
std::erase_if(m_listeners, [id](const auto& pair) {
|
||||
return pair.first == id;
|
||||
});
|
||||
}
|
||||
|
||||
/// Prepare-only port exporting a staged candidate aggregate for a
|
||||
/// higher-level platform coordinator without swapping m_current.
|
||||
[[nodiscard]] Void::Coro::Task<
|
||||
Void::Result::Result<PreparedAggregate<T>>>
|
||||
prepare_external(SourceSet sources,
|
||||
Void::Async::OperationOptions opts = {})
|
||||
{
|
||||
auto gate_guard = co_await m_gate.lock(m_executor);
|
||||
if (opts.stop.stop_requested()) {
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::cancelled,
|
||||
"ReloadController::prepare_external: cancelled"));
|
||||
}
|
||||
auto snap = current();
|
||||
co_return co_await prepare_candidate(
|
||||
std::move(sources), snap, opts, nullptr);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<ReloadReport>>
|
||||
reload(SourceSet sources, Void::Async::OperationOptions opts = {})
|
||||
{
|
||||
if (opts.stop.stop_requested()) {
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::cancelled,
|
||||
"ReloadController::reload: cancelled before admission"));
|
||||
}
|
||||
|
||||
auto gate_guard = co_await m_gate.lock(m_executor);
|
||||
if (opts.stop.stop_requested()) {
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::cancelled,
|
||||
"ReloadController::reload: cancelled while queued"));
|
||||
}
|
||||
|
||||
Snapshot<T> old_snap;
|
||||
std::uint64_t expected_gen = 0;
|
||||
{
|
||||
std::lock_guard lk{m_pub_mu};
|
||||
std::erase_if(m_retention_tokens, [](const auto& w) {
|
||||
return w.expired();
|
||||
});
|
||||
if (m_schema.limits().max_retained_generations > 0 &&
|
||||
m_retention_tokens.size() >=
|
||||
m_schema.limits().max_retained_generations) {
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::retention_limit,
|
||||
"ReloadController::reload: max_retained_generations reached"));
|
||||
}
|
||||
old_snap = m_current;
|
||||
expected_gen = m_generation;
|
||||
}
|
||||
|
||||
std::vector<std::string> restart_keys;
|
||||
auto cand_res = co_await prepare_candidate(
|
||||
std::move(sources), old_snap, opts, &restart_keys);
|
||||
if (!restart_keys.empty()) {
|
||||
ReloadReport rep;
|
||||
rep.generation = expected_gen;
|
||||
rep.committed = false;
|
||||
rep.restart_required = true;
|
||||
rep.restart_required_keys = std::move(restart_keys);
|
||||
co_return rep;
|
||||
}
|
||||
if (!cand_res) {
|
||||
co_return Void::Result::fail(std::move(cand_res).error());
|
||||
}
|
||||
auto agg = std::move(*cand_res);
|
||||
|
||||
// Check pre-commit stop/deadline before swapping m_current.
|
||||
if (opts.stop.stop_requested()) {
|
||||
(void)co_await agg.dispose_all();
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::cancelled,
|
||||
"ReloadController::reload: cancelled before commit"));
|
||||
}
|
||||
if (opts.deadline.has_value() &&
|
||||
m_clock->now() >= *opts.deadline) {
|
||||
(void)co_await agg.dispose_all();
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::timeout,
|
||||
"ReloadController::reload: deadline expired before commit"));
|
||||
}
|
||||
|
||||
// Short pointer swap — commit point (zero user callbacks or
|
||||
// allocations under m_pub_mu).
|
||||
auto tok = std::make_shared<const int>(1);
|
||||
Snapshot<T> new_snap{
|
||||
.generation = expected_gen + 1,
|
||||
.values = std::move(agg.values),
|
||||
.provenance = std::move(agg.provenance),
|
||||
.raw = std::move(agg.raw),
|
||||
.resources = std::move(agg.resources),
|
||||
.retention_token = tok,
|
||||
};
|
||||
Snapshot<T> retired_old;
|
||||
{
|
||||
std::lock_guard lk{m_pub_mu};
|
||||
if (m_generation != expected_gen || m_closing) {
|
||||
// Should be impossible under m_gate, fail-safe rollback.
|
||||
retired_old = Snapshot<T>{};
|
||||
} else {
|
||||
m_generation = new_snap.generation;
|
||||
m_retention_tokens.push_back(tok);
|
||||
retired_old = std::exchange(m_current, new_snap);
|
||||
}
|
||||
}
|
||||
if (!retired_old) {
|
||||
(void)co_await agg.dispose_all();
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::internal,
|
||||
"ReloadController::reload: generation swap conflict"));
|
||||
}
|
||||
|
||||
// Release old snapshot outside lock.
|
||||
retired_old = Snapshot<T>{};
|
||||
|
||||
ReloadReport rep;
|
||||
rep.generation = new_snap.generation;
|
||||
rep.committed = true;
|
||||
rep.changed_keys = std::move(agg.changed_keys);
|
||||
rep.warnings = std::move(agg.warnings);
|
||||
rep.stop_observed_after_commit = opts.stop.stop_requested();
|
||||
rep.coalesced_events =
|
||||
m_coalesced_events.exchange(0, std::memory_order_acq_rel);
|
||||
|
||||
// Notify observers strictly outside locks; capture exceptions
|
||||
// without claiming rollback.
|
||||
std::vector<CommitListener> copy;
|
||||
{
|
||||
std::lock_guard lk{m_listener_mu};
|
||||
copy.reserve(m_listeners.size());
|
||||
for (const auto& [_, fn] : m_listeners) {
|
||||
if (fn) copy.push_back(fn);
|
||||
}
|
||||
}
|
||||
const std::size_t notify_cap =
|
||||
std::min(copy.size(), m_schema.limits().max_notifications);
|
||||
for (std::size_t i = 0; i < notify_cap; ++i) {
|
||||
try {
|
||||
copy[i](new_snap, rep);
|
||||
} catch (const std::exception& ex) {
|
||||
rep.notification_errors.push_back(make_config_error(
|
||||
ConfigErrorCode::internal, ex.what()));
|
||||
} catch (...) {
|
||||
rep.notification_errors.push_back(make_config_error(
|
||||
ConfigErrorCode::internal,
|
||||
"ReloadController: notification callback threw"));
|
||||
}
|
||||
}
|
||||
co_return rep;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> attach_watcher(
|
||||
Void::SystemAsync::WatcherService& watcher,
|
||||
std::vector<std::filesystem::path> paths,
|
||||
std::function<SourceSet()> build_sources,
|
||||
Void::Async::Executor& exec)
|
||||
{
|
||||
std::lock_guard lk{m_watch_mu};
|
||||
if (m_closing) {
|
||||
return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::internal,
|
||||
"ReloadController::attach_watcher: controller closing"));
|
||||
}
|
||||
std::weak_ptr<ReloadController<T>> weak_self =
|
||||
this->weak_from_this();
|
||||
auto on_change = [weak_self, build = std::move(build_sources),
|
||||
&exec](const Void::SystemAsync::WatchEvent&) {
|
||||
auto self = weak_self.lock();
|
||||
if (!self) return;
|
||||
if (self->m_watcher_busy.exchange(
|
||||
true, std::memory_order_acq_rel)) {
|
||||
self->m_coalesced_events.fetch_add(
|
||||
1, std::memory_order_relaxed);
|
||||
self->m_watcher_dirty.store(true,
|
||||
std::memory_order_release);
|
||||
return;
|
||||
}
|
||||
self->schedule_watch_reload(build, exec);
|
||||
};
|
||||
|
||||
std::vector<Void::SystemAsync::WatchSubscription> subs;
|
||||
for (const auto& p : paths) {
|
||||
auto sr = watcher.watch(p, on_change);
|
||||
if (!sr) {
|
||||
for (auto& s : subs) (void)s.close_and_join();
|
||||
return Void::Result::fail(std::move(sr).error());
|
||||
}
|
||||
subs.push_back(std::move(*sr));
|
||||
}
|
||||
for (auto& s : subs) {
|
||||
m_watch_subs.push_back(std::move(s));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void close_and_join()
|
||||
{
|
||||
{
|
||||
std::lock_guard lk{m_part_mu};
|
||||
m_closing = true;
|
||||
}
|
||||
{
|
||||
std::lock_guard lk{m_pub_mu};
|
||||
m_closing = true;
|
||||
}
|
||||
std::vector<Void::SystemAsync::WatchSubscription> subs;
|
||||
{
|
||||
std::lock_guard lk{m_watch_mu};
|
||||
subs.swap(m_watch_subs);
|
||||
}
|
||||
for (auto& s : subs) {
|
||||
(void)s.close_and_join();
|
||||
}
|
||||
std::unique_lock lk{m_part_mu};
|
||||
m_part_cv.wait(lk, [&] {
|
||||
for (const auto& p : m_participants) {
|
||||
if (p.in_flight > 0) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
struct ParticipantEntry {
|
||||
std::string id{};
|
||||
std::size_t budget_bytes{0};
|
||||
PrepareFn prepare{};
|
||||
std::size_t in_flight{0};
|
||||
bool removing{false};
|
||||
};
|
||||
|
||||
ReloadController(Schema<T> schema, ControllerOptions opts)
|
||||
: m_schema(std::move(schema)),
|
||||
m_clock(opts.clock ? opts.clock
|
||||
: &Void::Time::SystemMonotonicClock::instance()),
|
||||
m_executor(opts.executor)
|
||||
{
|
||||
}
|
||||
|
||||
static Void::Coro::Task<void> run_watch_reload_task(
|
||||
std::weak_ptr<ReloadController<T>> weak_self,
|
||||
std::function<SourceSet()> build,
|
||||
Void::Async::Executor* exec)
|
||||
{
|
||||
for (;;) {
|
||||
auto self = weak_self.lock();
|
||||
if (!self) co_return;
|
||||
self->m_watcher_dirty.store(false,
|
||||
std::memory_order_release);
|
||||
auto res = co_await self->reload(build());
|
||||
(void)res;
|
||||
if (!self->m_watcher_dirty.load(
|
||||
std::memory_order_acquire)) {
|
||||
self->m_watcher_busy.store(false,
|
||||
std::memory_order_release);
|
||||
if (!self->m_watcher_dirty.load(
|
||||
std::memory_order_acquire)) {
|
||||
co_return;
|
||||
}
|
||||
if (self->m_watcher_busy.exchange(
|
||||
true, std::memory_order_acq_rel)) {
|
||||
co_return;
|
||||
}
|
||||
}
|
||||
}
|
||||
(void)exec;
|
||||
}
|
||||
|
||||
void schedule_watch_reload(const std::function<SourceSet()>& build,
|
||||
Void::Async::Executor& exec)
|
||||
{
|
||||
Void::Async::spawn(
|
||||
exec, run_watch_reload_task(this->weak_from_this(), build,
|
||||
&exec));
|
||||
}
|
||||
|
||||
Void::Coro::Task<Void::Result::Result<PreparedAggregate<T>>>
|
||||
prepare_candidate(SourceSet sources,
|
||||
const Snapshot<T>& old_snap,
|
||||
Void::Async::OperationOptions opts,
|
||||
std::vector<std::string>* restart_out)
|
||||
{
|
||||
auto merged = load_sources(sources, m_schema.limits(),
|
||||
m_schema.secret_keys());
|
||||
if (!merged) {
|
||||
co_return Void::Result::fail(std::move(merged).error());
|
||||
}
|
||||
auto validated = validate<T>(*merged, m_schema);
|
||||
if (!validated) {
|
||||
co_return Void::Result::fail(std::move(validated).error());
|
||||
}
|
||||
if (restart_out != nullptr && old_snap.raw) {
|
||||
auto rr = detect_restart_required_changes<T>(
|
||||
*old_snap.raw, *merged, m_schema);
|
||||
if (!rr.empty()) {
|
||||
*restart_out = std::move(rr);
|
||||
co_return Void::Result::fail(make_config_error(
|
||||
ConfigErrorCode::restart_required,
|
||||
"ReloadController: restart-required keys changed"));
|
||||
}
|
||||
}
|
||||
|
||||
auto merged_ptr =
|
||||
std::make_shared<const MergedConfig>(std::move(*merged));
|
||||
auto cand_ptr =
|
||||
std::make_shared<const T>(std::move(validated->value));
|
||||
auto res_map = std::make_shared<
|
||||
std::unordered_map<std::string, std::shared_ptr<const void>>>();
|
||||
std::vector<PreparedChange> prepared_list;
|
||||
|
||||
const auto prep_deadline =
|
||||
m_clock->now() + m_schema.limits().default_prepare_timeout;
|
||||
Void::Async::OperationOptions p_opts = opts;
|
||||
if (!p_opts.deadline.has_value() ||
|
||||
prep_deadline < *p_opts.deadline) {
|
||||
p_opts.deadline = prep_deadline;
|
||||
}
|
||||
|
||||
// Snapshot participants safely.
|
||||
struct ActivePart {
|
||||
std::string id;
|
||||
std::size_t budget_bytes;
|
||||
PrepareFn prepare;
|
||||
};
|
||||
std::vector<ActivePart> parts;
|
||||
{
|
||||
std::lock_guard lk{m_part_mu};
|
||||
for (auto& p : m_participants) {
|
||||
if (!p.removing && p.prepare) {
|
||||
++p.in_flight;
|
||||
parts.push_back(
|
||||
ActivePart{p.id, p.budget_bytes, p.prepare});
|
||||
}
|
||||
}
|
||||
}
|
||||
auto release_inflight = [&]() {
|
||||
std::lock_guard lk{m_part_mu};
|
||||
for (auto& ap : parts) {
|
||||
for (auto& p : m_participants) {
|
||||
if (p.id == ap.id && p.in_flight > 0) {
|
||||
--p.in_flight;
|
||||
}
|
||||
}
|
||||
}
|
||||
m_part_cv.notify_all();
|
||||
};
|
||||
|
||||
std::optional<Void::Result::Error> prep_err;
|
||||
std::size_t total_budget = 0;
|
||||
|
||||
for (auto& ap : parts) {
|
||||
if (p_opts.stop.stop_requested()) {
|
||||
prep_err = make_config_error(
|
||||
ConfigErrorCode::cancelled,
|
||||
"ReloadController: cancelled during participant prepare");
|
||||
break;
|
||||
}
|
||||
if (p_opts.deadline.has_value() &&
|
||||
m_clock->now() >= *p_opts.deadline) {
|
||||
prep_err = make_config_error(
|
||||
ConfigErrorCode::timeout,
|
||||
"ReloadController: participant prepare timed out");
|
||||
break;
|
||||
}
|
||||
try {
|
||||
auto pr =
|
||||
co_await ap.prepare(old_snap, cand_ptr, p_opts);
|
||||
if (!pr) {
|
||||
prep_err = std::move(pr).error();
|
||||
break;
|
||||
}
|
||||
const std::size_t item_budget = std::max(
|
||||
ap.budget_bytes, pr->declared_budget_bytes);
|
||||
if (total_budget + item_budget >
|
||||
m_schema.limits().max_merged_bytes) {
|
||||
if (pr->dispose_async) {
|
||||
(void)co_await pr->dispose_async();
|
||||
}
|
||||
prep_err = make_config_error(
|
||||
ConfigErrorCode::limit_exceeded,
|
||||
"ReloadController: participant budget exceeded");
|
||||
break;
|
||||
}
|
||||
total_budget += item_budget;
|
||||
if (pr->view) {
|
||||
res_map->insert_or_assign(ap.id, pr->view);
|
||||
}
|
||||
prepared_list.push_back(std::move(*pr));
|
||||
} catch (const std::exception& ex) {
|
||||
prep_err = make_config_error(
|
||||
ConfigErrorCode::prepare_failed, ex.what());
|
||||
break;
|
||||
} catch (...) {
|
||||
prep_err = make_config_error(
|
||||
ConfigErrorCode::prepare_failed,
|
||||
"ReloadController: participant prepare threw");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
release_inflight();
|
||||
|
||||
if (prep_err.has_value()) {
|
||||
for (auto it = prepared_list.rbegin();
|
||||
it != prepared_list.rend(); ++it) {
|
||||
if (it->dispose_async) {
|
||||
(void)co_await it->dispose_async();
|
||||
}
|
||||
}
|
||||
co_return Void::Result::fail(std::move(*prep_err));
|
||||
}
|
||||
|
||||
PreparedAggregate<T> agg;
|
||||
agg.values = std::move(cand_ptr);
|
||||
agg.provenance = merged_ptr->provenance;
|
||||
if (old_snap.raw) {
|
||||
agg.changed_keys =
|
||||
detail::diff_merged_keys(*old_snap.raw, *merged_ptr);
|
||||
}
|
||||
agg.raw = std::move(merged_ptr);
|
||||
agg.resources = std::move(res_map);
|
||||
agg.staged_changes = std::move(prepared_list);
|
||||
agg.warnings = std::move(validated->warnings);
|
||||
co_return agg;
|
||||
}
|
||||
|
||||
Schema<T> m_schema;
|
||||
const Void::Time::MonotonicClock* m_clock;
|
||||
Void::Async::Executor* m_executor{nullptr};
|
||||
|
||||
detail::AsyncReloadGate m_gate{};
|
||||
mutable std::mutex m_pub_mu{};
|
||||
Snapshot<T> m_current{};
|
||||
std::uint64_t m_generation{0};
|
||||
std::vector<std::weak_ptr<const void>> m_retention_tokens{};
|
||||
bool m_closing{false};
|
||||
|
||||
std::mutex m_part_mu{};
|
||||
std::condition_variable m_part_cv{};
|
||||
std::vector<ParticipantEntry> m_participants{};
|
||||
|
||||
std::mutex m_listener_mu{};
|
||||
std::vector<std::pair<std::size_t, CommitListener>> m_listeners{};
|
||||
std::size_t m_next_listener_id{1};
|
||||
|
||||
std::mutex m_watch_mu{};
|
||||
std::vector<Void::SystemAsync::WatchSubscription> m_watch_subs{};
|
||||
std::atomic<bool> m_watcher_busy{false};
|
||||
std::atomic<bool> m_watcher_dirty{false};
|
||||
std::atomic<std::size_t> m_coalesced_events{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Configuration
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/IO/Driver.hpp>
|
||||
#include <Void/IO/Stream.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
|
||||
namespace Void::CryptoAsync
|
||||
{
|
||||
struct StreamHashOptions {
|
||||
std::size_t chunk_bytes{
|
||||
Void::Crypto::CryptoLimits::kStreamChunkBytes};
|
||||
Void::Crypto::ProviderOptions provider{};
|
||||
};
|
||||
|
||||
/// Incrementally hash an IO::ByteStream using a Driver-owned BufferLease
|
||||
/// (default 64 KiB). Checks stop/deadline between chunks and finalizes only
|
||||
/// on clean EOF without cancellation.
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
|
||||
hash_stream(Void::Crypto::HashAlgorithm algorithm,
|
||||
Void::IO::Driver& driver, Void::IO::ByteStream& stream,
|
||||
Void::Async::OperationOptions options = {},
|
||||
StreamHashOptions hash_options = {});
|
||||
|
||||
struct FileHasherOptions {
|
||||
std::size_t max_concurrent{
|
||||
Void::Crypto::CryptoLimits::kDefaultMaxConcurrentFileHashes};
|
||||
std::size_t max_waiting{
|
||||
Void::Crypto::CryptoLimits::kDefaultMaxWaitingFileHashes};
|
||||
std::size_t buffer_budget_bytes{
|
||||
Void::Crypto::CryptoLimits::kDefaultAsyncBufferBudgetBytes};
|
||||
std::size_t chunk_bytes{
|
||||
Void::Crypto::CryptoLimits::kStreamChunkBytes};
|
||||
Void::Crypto::ProviderOptions provider{};
|
||||
};
|
||||
|
||||
struct FileHasherStats {
|
||||
std::size_t active{0};
|
||||
std::size_t waiting{0};
|
||||
std::size_t reserved_buffer_bytes{0};
|
||||
std::uint64_t completed{0};
|
||||
std::uint64_t rejected{0};
|
||||
bool closing{false};
|
||||
};
|
||||
|
||||
/// Bounded asynchronous file-hashing service with concurrency, queue, and
|
||||
/// owned buffer-budget limits plus explicit stop/join shutdown.
|
||||
class AsyncFileHasher
|
||||
{
|
||||
public:
|
||||
|
||||
explicit AsyncFileHasher(
|
||||
Void::Async::Executor& executor,
|
||||
FileHasherOptions options = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
~AsyncFileHasher();
|
||||
|
||||
AsyncFileHasher(const AsyncFileHasher&) = delete;
|
||||
AsyncFileHasher& operator=(const AsyncFileHasher&) = delete;
|
||||
AsyncFileHasher(AsyncFileHasher&&) = delete;
|
||||
AsyncFileHasher& operator=(AsyncFileHasher&&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<
|
||||
Void::Result::Result<Void::Crypto::Digest>>
|
||||
hash_file(Void::Crypto::HashAlgorithm algorithm,
|
||||
std::filesystem::path path,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
void request_stop() noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
|
||||
[[nodiscard]] FileHasherStats stats() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::CryptoAsync
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Crypto/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
@@ -12,27 +13,37 @@
|
||||
|
||||
namespace Void::Crypto
|
||||
{
|
||||
enum class HashAlgorithm { Sha1, Sha256, Sha512 };
|
||||
enum class HashAlgorithm { Sha1, Sha256, Sha512, Blake2b256, Blake2b512 };
|
||||
using Digest = std::vector<std::byte>;
|
||||
|
||||
/// Returns true if Void::Crypto was built with OpenSSL support (required
|
||||
/// for Ed25519; hashing/HMAC/HKDF work on the built-in pure-C++ backend
|
||||
/// with zero external dependencies).
|
||||
[[nodiscard]] bool has_openssl_backend() noexcept;
|
||||
|
||||
class Hasher
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Hasher>
|
||||
create(HashAlgorithm algorithm);
|
||||
[[nodiscard]] static Void::Result::Result<Hasher>
|
||||
create(HashAlgorithm algorithm,
|
||||
const ProviderOptions& provider);
|
||||
~Hasher();
|
||||
Hasher(Hasher&&) noexcept;
|
||||
Hasher& operator=(Hasher&&) noexcept;
|
||||
Hasher(const Hasher&) = delete;
|
||||
Hasher& operator=(const Hasher&) = delete;
|
||||
|
||||
[[nodiscard]] HasherState state() const noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
update(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
update(std::string_view data);
|
||||
/// Finalize this hash. Calling finalize or update again is an
|
||||
/// error.
|
||||
/// error. Backend update/finalize failures poison the hasher.
|
||||
[[nodiscard]] Void::Result::Result<Digest> finalize();
|
||||
|
||||
private:
|
||||
@@ -44,10 +55,21 @@ namespace Void::Crypto
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hash(HashAlgorithm algorithm, std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hash(HashAlgorithm algorithm, std::span<const std::byte> data,
|
||||
const ProviderOptions& provider);
|
||||
[[nodiscard]] Void::Result::Result<Digest> hash(HashAlgorithm algorithm,
|
||||
std::string_view data);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
|
||||
const ProviderOptions& provider);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
|
||||
const ProviderOptions& provider);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha1(std::span<const std::byte> data);
|
||||
@@ -58,21 +80,113 @@ namespace Void::Crypto
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha512(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b256(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<Digest> blake2b256(std::string_view data);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b512(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<Digest> blake2b512(std::string_view data);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha1File(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha256File(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha512File(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha1_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha256_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha512_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b256_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b512_file(const std::filesystem::path& path);
|
||||
|
||||
inline constexpr std::size_t Ed25519PublicKeySize = 32;
|
||||
inline constexpr std::size_t Ed25519SignatureSize = 64;
|
||||
/// Move-only owning Ed25519 private key handle. Has no implicit copy,
|
||||
/// string conversion, or secret formatting.
|
||||
class Ed25519PrivateKey
|
||||
{
|
||||
public:
|
||||
|
||||
Ed25519PrivateKey() noexcept = default;
|
||||
~Ed25519PrivateKey();
|
||||
Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept;
|
||||
Ed25519PrivateKey& operator=(Ed25519PrivateKey&&) noexcept;
|
||||
Ed25519PrivateKey(const Ed25519PrivateKey&) = delete;
|
||||
Ed25519PrivateKey& operator=(const Ed25519PrivateKey&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Ed25519PrivateKey>
|
||||
generate(const ProviderOptions& provider = {});
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Ed25519PrivateKey>
|
||||
from_raw_seed(std::span<const std::byte> seed,
|
||||
const ProviderOptions& provider = {});
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Ed25519PublicKey>
|
||||
public_key() const;
|
||||
|
||||
/// Explicit secret export into a move-only self-wiping seed handle.
|
||||
[[nodiscard]] Void::Result::Result<Ed25519Seed>
|
||||
export_raw_seed() const;
|
||||
|
||||
private:
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> m_impl;
|
||||
explicit Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept;
|
||||
|
||||
friend Void::Result::Result<Ed25519Signature>
|
||||
sign_ed25519(std::span<const std::byte> message,
|
||||
const Ed25519PrivateKey& private_key,
|
||||
const ProviderOptions& provider);
|
||||
};
|
||||
|
||||
/// Sign exact message bytes (up to CryptoLimits::kMaxOneShotMessageBytes)
|
||||
/// with an owning Ed25519 private key.
|
||||
[[nodiscard]] Void::Result::Result<Ed25519Signature>
|
||||
sign_ed25519(std::span<const std::byte> message,
|
||||
const Ed25519PrivateKey& private_key,
|
||||
const ProviderOptions& provider = {});
|
||||
|
||||
/// Verify an Ed25519 detached signature over the exact message bytes.
|
||||
/// Invalid key/signature sizes are errors; a well-formed but invalid
|
||||
/// signature returns false.
|
||||
/// Invalid key/signature sizes or oversized messages are errors; a
|
||||
/// well-formed but invalid signature returns false.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
verifyEd25519(std::span<const std::byte> message,
|
||||
std::span<const std::byte> signature,
|
||||
std::span<const std::byte> publicKey);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
verify_ed25519(std::span<const std::byte> message,
|
||||
const Ed25519Signature& signature,
|
||||
const Ed25519PublicKey& public_key,
|
||||
const ProviderOptions& provider = {});
|
||||
|
||||
/// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer.
|
||||
/// Wipes output on backend failure and rejects overlapping buffers.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
hmac_sha256_into(std::span<const std::byte> secret_key,
|
||||
std::span<const std::byte> message,
|
||||
std::span<std::byte> output,
|
||||
const ProviderOptions& provider = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hmac_sha256(std::span<const std::byte> secret_key,
|
||||
std::span<const std::byte> message,
|
||||
const ProviderOptions& provider = {});
|
||||
|
||||
/// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned
|
||||
/// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping
|
||||
/// buffers and wipes secret_output on any failure after validation.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
hkdf_sha256(std::span<const std::byte> secret_input,
|
||||
std::span<const std::byte> salt,
|
||||
std::span<const std::byte> context,
|
||||
std::span<std::byte> secret_output,
|
||||
const ProviderOptions& provider = {});
|
||||
|
||||
} // namespace Void::Crypto
|
||||
@@ -0,0 +1,288 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Crypto
|
||||
{
|
||||
inline constexpr std::size_t Ed25519PublicKeySize = 32;
|
||||
inline constexpr std::size_t Ed25519SignatureSize = 64;
|
||||
inline constexpr std::size_t Ed25519SeedSize = 32;
|
||||
inline constexpr std::size_t HmacSha256Size = 32;
|
||||
|
||||
struct CryptoLimits {
|
||||
static constexpr std::size_t kMaxOneShotMessageBytes =
|
||||
16ULL * 1024ULL * 1024ULL;
|
||||
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
|
||||
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
|
||||
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
|
||||
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
|
||||
static constexpr std::size_t kDefaultAsyncBufferBudgetBytes =
|
||||
8ULL * 1024ULL * 1024ULL;
|
||||
};
|
||||
|
||||
enum class CryptoErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
invalid_key_size = 2,
|
||||
invalid_signature_size = 3,
|
||||
message_too_large = 4,
|
||||
output_too_large = 5,
|
||||
overlapping_buffers = 6,
|
||||
invalid_state = 7,
|
||||
unsupported_algorithm = 8,
|
||||
provider_error = 9,
|
||||
backend_error = 10,
|
||||
io_error = 11,
|
||||
cancelled = 12,
|
||||
timeout = 13,
|
||||
overloaded = 14,
|
||||
resource_exhausted = 15,
|
||||
closed = 16
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_crypto_error(CryptoErrorCode code, std::string message = {},
|
||||
std::error_code sys_err = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case CryptoErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case CryptoErrorCode::invalid_argument:
|
||||
case CryptoErrorCode::invalid_key_size:
|
||||
case CryptoErrorCode::invalid_signature_size:
|
||||
case CryptoErrorCode::message_too_large:
|
||||
case CryptoErrorCode::output_too_large:
|
||||
case CryptoErrorCode::overlapping_buffers:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case CryptoErrorCode::invalid_state:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case CryptoErrorCode::unsupported_algorithm:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case CryptoErrorCode::provider_error:
|
||||
case CryptoErrorCode::backend_error:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case CryptoErrorCode::io_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case CryptoErrorCode::cancelled:
|
||||
case CryptoErrorCode::closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case CryptoErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case CryptoErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case CryptoErrorCode::resource_exhausted:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
}
|
||||
|
||||
const ErrorCode domain_code{Void::Result::kCryptoErrorDomain,
|
||||
static_cast<std::int32_t>(code)};
|
||||
return Error{kind, std::move(message), domain_code, sys_err};
|
||||
}
|
||||
|
||||
enum class HasherState : std::uint8_t {
|
||||
Ready = 0,
|
||||
Updating,
|
||||
Finalized,
|
||||
Failed,
|
||||
MovedFrom
|
||||
};
|
||||
|
||||
/// Per-operation backend/provider selection. Never mutates process-wide
|
||||
/// provider state.
|
||||
struct ProviderOptions {
|
||||
std::string property_query{};
|
||||
bool prefer_builtin{false};
|
||||
};
|
||||
|
||||
struct Ed25519PublicKey {
|
||||
std::array<std::byte, Ed25519PublicKeySize> bytes{};
|
||||
|
||||
[[nodiscard]] std::span<const std::byte> view() const noexcept
|
||||
{
|
||||
return bytes;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Ed25519PublicKey>
|
||||
from_bytes(std::span<const std::byte> raw)
|
||||
{
|
||||
if (raw.size() != Ed25519PublicKeySize) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::invalid_key_size,
|
||||
"Ed25519PublicKey requires exactly 32 bytes")};
|
||||
}
|
||||
Ed25519PublicKey key;
|
||||
for (std::size_t i = 0; i < Ed25519PublicKeySize; ++i) {
|
||||
key.bytes[i] = raw[i];
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool
|
||||
operator==(const Ed25519PublicKey&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct Ed25519Signature {
|
||||
std::array<std::byte, Ed25519SignatureSize> bytes{};
|
||||
|
||||
[[nodiscard]] std::span<const std::byte> view() const noexcept
|
||||
{
|
||||
return bytes;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Ed25519Signature>
|
||||
from_bytes(std::span<const std::byte> raw)
|
||||
{
|
||||
if (raw.size() != Ed25519SignatureSize) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::invalid_signature_size,
|
||||
"Ed25519Signature requires exactly 64 bytes")};
|
||||
}
|
||||
Ed25519Signature sig;
|
||||
for (std::size_t i = 0; i < Ed25519SignatureSize; ++i) {
|
||||
sig.bytes[i] = raw[i];
|
||||
}
|
||||
return sig;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool
|
||||
operator==(const Ed25519Signature&) const noexcept = default;
|
||||
};
|
||||
|
||||
/// Securely wipe a mutable byte buffer using the crypto backend's
|
||||
/// non-elidable cleanse routine.
|
||||
void secure_wipe(std::span<std::byte> buffer) noexcept;
|
||||
|
||||
/// Constant-time equality comparison for equal-length digests/MACs.
|
||||
[[nodiscard]] bool
|
||||
constant_time_equal(std::span<const std::byte> lhs,
|
||||
std::span<const std::byte> rhs) noexcept;
|
||||
|
||||
/// Move-only 32-byte Ed25519 raw seed cleared on release.
|
||||
class Ed25519Seed
|
||||
{
|
||||
public:
|
||||
|
||||
Ed25519Seed() noexcept = default;
|
||||
~Ed25519Seed() noexcept { clear(); }
|
||||
|
||||
Ed25519Seed(Ed25519Seed&& other) noexcept
|
||||
: m_bytes(other.m_bytes), m_valid(other.m_valid)
|
||||
{
|
||||
other.clear();
|
||||
}
|
||||
|
||||
Ed25519Seed& operator=(Ed25519Seed&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
clear();
|
||||
m_bytes = other.m_bytes;
|
||||
m_valid = other.m_valid;
|
||||
other.clear();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
Ed25519Seed(const Ed25519Seed&) = delete;
|
||||
Ed25519Seed& operator=(const Ed25519Seed&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<Ed25519Seed>
|
||||
from_bytes(std::span<const std::byte> raw)
|
||||
{
|
||||
if (raw.size() != Ed25519SeedSize) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::invalid_key_size,
|
||||
"Ed25519Seed requires exactly 32 bytes")};
|
||||
}
|
||||
Ed25519Seed seed;
|
||||
for (std::size_t i = 0; i < Ed25519SeedSize; ++i) {
|
||||
seed.m_bytes[i] = raw[i];
|
||||
}
|
||||
seed.m_valid = true;
|
||||
return seed;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept { return m_valid; }
|
||||
|
||||
[[nodiscard]] std::span<const std::byte> view() const noexcept
|
||||
{
|
||||
return m_valid ? std::span<const std::byte>{m_bytes}
|
||||
: std::span<const std::byte>{};
|
||||
}
|
||||
|
||||
void clear() noexcept
|
||||
{
|
||||
secure_wipe(m_bytes);
|
||||
m_valid = false;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::array<std::byte, Ed25519SeedSize> m_bytes{};
|
||||
bool m_valid{false};
|
||||
};
|
||||
|
||||
enum class FaultOperation : std::uint8_t {
|
||||
none = 0,
|
||||
any,
|
||||
hash_create,
|
||||
hash_update,
|
||||
hash_finalize,
|
||||
ed25519_keygen,
|
||||
ed25519_import,
|
||||
ed25519_sign,
|
||||
ed25519_verify,
|
||||
hmac,
|
||||
hkdf
|
||||
};
|
||||
|
||||
struct FaultConfig {
|
||||
FaultOperation op{FaultOperation::none};
|
||||
CryptoErrorCode code{CryptoErrorCode::provider_error};
|
||||
std::size_t fail_after{0};
|
||||
};
|
||||
|
||||
/// RAII thread-local backend fault injection guard for deterministic
|
||||
/// provider/backend failure testing.
|
||||
class ScopedFaultGuard
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ScopedFaultGuard(FaultConfig config) noexcept;
|
||||
~ScopedFaultGuard() noexcept;
|
||||
|
||||
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
|
||||
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
FaultConfig m_previous{};
|
||||
std::size_t m_previous_hits{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Crypto
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
@@ -16,6 +18,11 @@ namespace Void::Json::Strict
|
||||
{
|
||||
inline constexpr std::size_t default_maximum_depth{64U};
|
||||
|
||||
struct ParseOptions {
|
||||
std::size_t maximumDepth{default_maximum_depth};
|
||||
bool allowDecimals{true};
|
||||
};
|
||||
|
||||
struct ParseError {
|
||||
std::size_t offset{};
|
||||
std::string message;
|
||||
@@ -24,8 +31,8 @@ namespace Void::Json::Strict
|
||||
struct Value {
|
||||
using Array = std::vector<Value>;
|
||||
using Object = std::map<std::string, Value, std::less<>>;
|
||||
std::variant<std::nullptr_t, bool, std::int64_t, std::string, Array,
|
||||
Object>
|
||||
std::variant<std::nullptr_t, bool, std::int64_t, double,
|
||||
std::string, Array, Object>
|
||||
value;
|
||||
};
|
||||
|
||||
@@ -35,13 +42,79 @@ namespace Void::Json::Strict
|
||||
ParseError error;
|
||||
};
|
||||
|
||||
[[nodiscard]] constexpr std::size_t
|
||||
validate_utf8_at(const std::string_view input,
|
||||
const std::size_t pos) noexcept
|
||||
{
|
||||
if (pos >= input.size()) {
|
||||
return 0U;
|
||||
}
|
||||
const auto b0 = static_cast<unsigned char>(input[pos]);
|
||||
if (b0 <= 0x7FU) {
|
||||
return 1U;
|
||||
}
|
||||
if (b0 >= 0xC2U && b0 <= 0xDFU) {
|
||||
if (pos + 1U >= input.size()) {
|
||||
return 0U;
|
||||
}
|
||||
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
|
||||
return (b1 >= 0x80U && b1 <= 0xBFU) ? 2U : 0U;
|
||||
}
|
||||
if (b0 >= 0xE0U && b0 <= 0xEFU) {
|
||||
if (pos + 2U >= input.size()) {
|
||||
return 0U;
|
||||
}
|
||||
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
|
||||
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
|
||||
const unsigned char lo = (b0 == 0xE0U) ? 0xA0U : 0x80U;
|
||||
const unsigned char hi = (b0 == 0xEDU) ? 0x9FU : 0xBFU;
|
||||
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU) {
|
||||
return 0U;
|
||||
}
|
||||
return 3U;
|
||||
}
|
||||
if (b0 >= 0xF0U && b0 <= 0xF4U) {
|
||||
if (pos + 3U >= input.size()) {
|
||||
return 0U;
|
||||
}
|
||||
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
|
||||
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
|
||||
const auto b3 = static_cast<unsigned char>(input[pos + 3U]);
|
||||
const unsigned char lo = (b0 == 0xF0U) ? 0x90U : 0x80U;
|
||||
const unsigned char hi = (b0 == 0xF4U) ? 0x8FU : 0xBFU;
|
||||
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU ||
|
||||
b3 < 0x80U || b3 > 0xBFU) {
|
||||
return 0U;
|
||||
}
|
||||
return 4U;
|
||||
}
|
||||
return 0U;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::expected<void, ParseError>
|
||||
validate_utf8_bytes(const std::string_view input)
|
||||
{
|
||||
std::size_t pos = 0U;
|
||||
while (pos < input.size()) {
|
||||
const std::size_t len = validate_utf8_at(input, pos);
|
||||
if (len == 0U) {
|
||||
return std::unexpected{ParseError{
|
||||
.offset = pos,
|
||||
.message = "invalid UTF-8 sequence",
|
||||
}};
|
||||
}
|
||||
pos += len;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
class Parser final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Parser(const std::string_view input,
|
||||
const std::size_t maximumDepth)
|
||||
: input_{input}, maximumDepth_{maximumDepth}
|
||||
const ParseOptions options)
|
||||
: input_{input}, options_{options}
|
||||
{
|
||||
}
|
||||
|
||||
@@ -173,6 +246,18 @@ namespace Void::Json::Strict
|
||||
fail("control character in string");
|
||||
}
|
||||
if (value != '\\') {
|
||||
if (value >= 0x80U) {
|
||||
const std::size_t seq_start = position_ - 1U;
|
||||
const std::size_t len =
|
||||
validate_utf8_at(input_, seq_start);
|
||||
if (len == 0U) {
|
||||
position_ = seq_start;
|
||||
fail("invalid UTF-8 sequence");
|
||||
}
|
||||
output.append(input_.substr(seq_start, len));
|
||||
position_ = seq_start + len;
|
||||
continue;
|
||||
}
|
||||
output.push_back(static_cast<char>(value));
|
||||
continue;
|
||||
}
|
||||
@@ -231,6 +316,21 @@ namespace Void::Json::Strict
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] static bool isDigit(const char ch) noexcept
|
||||
{
|
||||
return ch >= '0' && ch <= '9';
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t consumeDigits() noexcept
|
||||
{
|
||||
const std::size_t begin = position_;
|
||||
while (position_ < input_.size() &&
|
||||
isDigit(input_[position_])) {
|
||||
++position_;
|
||||
}
|
||||
return position_ - begin;
|
||||
}
|
||||
|
||||
[[nodiscard]] Value parseNumber()
|
||||
{
|
||||
const std::size_t start = position_;
|
||||
@@ -242,21 +342,52 @@ namespace Void::Json::Strict
|
||||
}
|
||||
if (input_[position_] == '0') {
|
||||
++position_;
|
||||
if (position_ < input_.size() &&
|
||||
isDigit(input_[position_])) {
|
||||
fail("leading zero in number");
|
||||
}
|
||||
} else {
|
||||
if (input_[position_] < '1' ||
|
||||
input_[position_] > '9') {
|
||||
fail("invalid number");
|
||||
}
|
||||
while (position_ < input_.size() &&
|
||||
input_[position_] >= '0' &&
|
||||
input_[position_] <= '9') {
|
||||
++position_;
|
||||
static_cast<void>(consumeDigits());
|
||||
}
|
||||
bool isDecimal = false;
|
||||
if (position_ < input_.size() && input_[position_] == '.') {
|
||||
isDecimal = true;
|
||||
++position_;
|
||||
if (consumeDigits() == 0U) {
|
||||
fail("incomplete fractional part");
|
||||
}
|
||||
}
|
||||
if (position_ < input_.size() &&
|
||||
(input_[position_] == '.' || input_[position_] == 'e' ||
|
||||
input_[position_] == 'E')) {
|
||||
fail("floating-point numbers are not supported");
|
||||
(input_[position_] == 'e' || input_[position_] == 'E')) {
|
||||
isDecimal = true;
|
||||
++position_;
|
||||
if (position_ < input_.size() &&
|
||||
(input_[position_] == '+' ||
|
||||
input_[position_] == '-')) {
|
||||
++position_;
|
||||
}
|
||||
if (consumeDigits() == 0U) {
|
||||
fail("incomplete exponent");
|
||||
}
|
||||
}
|
||||
if (isDecimal) {
|
||||
if (!options_.allowDecimals) {
|
||||
fail("floating-point numbers are not supported");
|
||||
}
|
||||
double value{};
|
||||
const auto result = std::from_chars(
|
||||
input_.data() + start, input_.data() + position_,
|
||||
value, std::chars_format::general);
|
||||
if (result.ec != std::errc{} ||
|
||||
result.ptr != input_.data() + position_ ||
|
||||
!std::isfinite(value)) {
|
||||
fail("number is out of range");
|
||||
}
|
||||
return Value{value};
|
||||
}
|
||||
std::int64_t value{};
|
||||
const auto result =
|
||||
@@ -330,7 +461,8 @@ namespace Void::Json::Strict
|
||||
|
||||
[[nodiscard]] Value parseValue(const std::size_t depth)
|
||||
{
|
||||
if (depth > maximumDepth_ || position_ >= input_.size()) {
|
||||
if (depth > options_.maximumDepth ||
|
||||
position_ >= input_.size()) {
|
||||
fail("nesting limit or unexpected end of input");
|
||||
}
|
||||
switch (input_[position_]) {
|
||||
@@ -351,8 +483,7 @@ namespace Void::Json::Strict
|
||||
return Value{nullptr};
|
||||
default:
|
||||
if (input_[position_] == '-' ||
|
||||
(input_[position_] >= '0' &&
|
||||
input_[position_] <= '9')) {
|
||||
isDigit(input_[position_])) {
|
||||
return parseNumber();
|
||||
}
|
||||
fail("invalid value");
|
||||
@@ -360,17 +491,191 @@ namespace Void::Json::Strict
|
||||
}
|
||||
|
||||
std::string_view input_;
|
||||
std::size_t maximumDepth_;
|
||||
ParseOptions options_;
|
||||
std::size_t position_{};
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
[[nodiscard]] inline std::expected<Value, ParseError>
|
||||
parse(const std::string_view input, const ParseOptions options)
|
||||
{
|
||||
try {
|
||||
return Detail::Parser{input, options}.parse();
|
||||
} catch (const Detail::ParseFailure& failure) {
|
||||
return std::unexpected{failure.error};
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::expected<Value, ParseError>
|
||||
parse(const std::string_view input,
|
||||
const std::size_t maximumDepth = default_maximum_depth)
|
||||
{
|
||||
return parse(input, ParseOptions{.maximumDepth = maximumDepth,
|
||||
.allowDecimals = true});
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool is_valid_utf8(const std::string_view input) noexcept
|
||||
{
|
||||
std::size_t pos = 0U;
|
||||
while (pos < input.size()) {
|
||||
const std::size_t len = Detail::validate_utf8_at(input, pos);
|
||||
if (len == 0U) {
|
||||
return false;
|
||||
}
|
||||
pos += len;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::expected<void, ParseError>
|
||||
validate_utf8(const std::string_view input)
|
||||
{
|
||||
return Detail::validate_utf8_bytes(input);
|
||||
}
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
inline void append_escaped_string(std::string& out,
|
||||
const std::string_view text)
|
||||
{
|
||||
const auto utf8 = validate_utf8_bytes(text);
|
||||
if (!utf8.has_value()) {
|
||||
throw ParseFailure{.error = utf8.error()};
|
||||
}
|
||||
out.push_back('"');
|
||||
std::size_t pos = 0U;
|
||||
while (pos < text.size()) {
|
||||
const auto ch = static_cast<unsigned char>(text[pos]);
|
||||
switch (ch) {
|
||||
case '"':
|
||||
out += "\\\"";
|
||||
++pos;
|
||||
break;
|
||||
case '\\':
|
||||
out += "\\\\";
|
||||
++pos;
|
||||
break;
|
||||
case '\b':
|
||||
out += "\\b";
|
||||
++pos;
|
||||
break;
|
||||
case '\f':
|
||||
out += "\\f";
|
||||
++pos;
|
||||
break;
|
||||
case '\n':
|
||||
out += "\\n";
|
||||
++pos;
|
||||
break;
|
||||
case '\r':
|
||||
out += "\\r";
|
||||
++pos;
|
||||
break;
|
||||
case '\t':
|
||||
out += "\\t";
|
||||
++pos;
|
||||
break;
|
||||
default:
|
||||
if (ch < 0x20U) {
|
||||
static constexpr char kHex[] = "0123456789abcdef";
|
||||
out += "\\u00";
|
||||
out.push_back(kHex[(ch >> 4U) & 0x0FU]);
|
||||
out.push_back(kHex[ch & 0x0FU]);
|
||||
++pos;
|
||||
} else if (ch >= 0x80U) {
|
||||
const std::size_t len = validate_utf8_at(text, pos);
|
||||
out.append(text.substr(pos, len));
|
||||
pos += len;
|
||||
} else {
|
||||
out.push_back(static_cast<char>(ch));
|
||||
++pos;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.push_back('"');
|
||||
}
|
||||
|
||||
inline void serialize_value(std::string& out, const Value& val,
|
||||
const std::size_t depth,
|
||||
const std::size_t maximumDepth)
|
||||
{
|
||||
if (depth > maximumDepth) {
|
||||
throw ParseFailure{
|
||||
.error =
|
||||
{
|
||||
.offset = out.size(),
|
||||
.message = "nesting limit exceeded during serialize",
|
||||
},
|
||||
};
|
||||
}
|
||||
std::visit(
|
||||
[&](const auto& node) {
|
||||
using T = std::decay_t<decltype(node)>;
|
||||
if constexpr (std::same_as<T, std::nullptr_t>) {
|
||||
out += "null";
|
||||
} else if constexpr (std::same_as<T, bool>) {
|
||||
out += (node ? "true" : "false");
|
||||
} else if constexpr (std::same_as<T, std::int64_t>) {
|
||||
std::array<char, 32> buf{};
|
||||
const auto res = std::to_chars(
|
||||
buf.data(), buf.data() + buf.size(), node);
|
||||
out.append(buf.data(), res.ptr);
|
||||
} else if constexpr (std::same_as<T, double>) {
|
||||
if (!std::isfinite(node)) {
|
||||
throw ParseFailure{
|
||||
.error =
|
||||
{
|
||||
.offset = out.size(),
|
||||
.message =
|
||||
"non-finite double is not valid JSON",
|
||||
},
|
||||
};
|
||||
}
|
||||
std::array<char, 64> buf{};
|
||||
const auto res = std::to_chars(
|
||||
buf.data(), buf.data() + buf.size(), node,
|
||||
std::chars_format::general);
|
||||
out.append(buf.data(), res.ptr);
|
||||
} else if constexpr (std::same_as<T, std::string>) {
|
||||
append_escaped_string(out, node);
|
||||
} else if constexpr (std::same_as<T, Value::Array>) {
|
||||
out.push_back('[');
|
||||
for (std::size_t i = 0; i < node.size(); ++i) {
|
||||
if (i > 0U) {
|
||||
out.push_back(',');
|
||||
}
|
||||
serialize_value(out, node[i], depth + 1U,
|
||||
maximumDepth);
|
||||
}
|
||||
out.push_back(']');
|
||||
} else if constexpr (std::same_as<T, Value::Object>) {
|
||||
out.push_back('{');
|
||||
bool first = true;
|
||||
for (const auto& [k, v] : node) {
|
||||
if (!first) {
|
||||
out.push_back(',');
|
||||
}
|
||||
first = false;
|
||||
append_escaped_string(out, k);
|
||||
out.push_back(':');
|
||||
serialize_value(out, v, depth + 1U, maximumDepth);
|
||||
}
|
||||
out.push_back('}');
|
||||
}
|
||||
},
|
||||
val.value);
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
[[nodiscard]] inline std::expected<std::string, ParseError>
|
||||
serialize(const Value& value,
|
||||
const std::size_t maximumDepth = default_maximum_depth)
|
||||
{
|
||||
try {
|
||||
return Detail::Parser{input, maximumDepth}.parse();
|
||||
std::string out;
|
||||
Detail::serialize_value(out, value, 0U, maximumDepth);
|
||||
return out;
|
||||
} catch (const Detail::ParseFailure& failure) {
|
||||
return std::unexpected{failure.error};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,41 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <coroutine>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
/// One awaiter for every "wait for an event (optionally with a deadline)"
|
||||
/// operation on a machine. `Storage` is the type-list container (a
|
||||
/// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is
|
||||
/// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the
|
||||
/// awaited value (the matched event, an optional on timeout, a variant,
|
||||
/// …). Built on ExecutionContext::{try_take_any,set_waiter}.
|
||||
struct WaiterCancelFn {
|
||||
ExecutionContext* ctx{nullptr};
|
||||
ExecutionContext::WaiterId waiter_id{0};
|
||||
|
||||
void operator()() const
|
||||
{
|
||||
if (ctx != nullptr && waiter_id != 0) {
|
||||
(void)ctx->try_post_control(
|
||||
[c = ctx, wid = waiter_id] { c->cancel_waiter(wid); });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/// Unified awaiter for awaiting an event (or event set), optional timeout
|
||||
/// on injected clock, and cooperative stop cancellation across both
|
||||
/// per-state scope stop and caller-supplied OperationOptions stop tokens.
|
||||
template <typename Storage, typename Resume> struct EventAwaiter {
|
||||
ExecutionContext* ctx;
|
||||
Storage types;
|
||||
EventEnvelope env;
|
||||
ExecutionContext* ctx{nullptr};
|
||||
Storage types{};
|
||||
EventEnvelope env{};
|
||||
bool timed_out{false};
|
||||
std::optional<std::chrono::steady_clock::time_point> deadline;
|
||||
Resume resume;
|
||||
bool cancelled{false};
|
||||
std::optional<Time::MonotonicClock::time_point> deadline{};
|
||||
Resume resume{};
|
||||
ExecutionContext::ScopeId scope{ExecutionContext::kNoScope};
|
||||
std::stop_token scope_stop{};
|
||||
std::stop_token user_stop{};
|
||||
ExecutionContext::WaiterId waiter_id{0};
|
||||
std::optional<std::stop_callback<WaiterCancelFn>> scope_cb{};
|
||||
std::optional<std::stop_callback<WaiterCancelFn>> user_cb{};
|
||||
|
||||
[[nodiscard]] bool await_ready()
|
||||
{
|
||||
return ctx->try_take_any(span(), env);
|
||||
if (scope_stop.stop_requested() || user_stop.stop_requested()) {
|
||||
cancelled = true;
|
||||
return true;
|
||||
}
|
||||
if (ctx != nullptr && !types.empty() &&
|
||||
ctx->try_take_any(span(), env)) {
|
||||
return true;
|
||||
}
|
||||
if (deadline.has_value() && ctx != nullptr &&
|
||||
ctx->clock().now() >= *deadline) {
|
||||
timed_out = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void await_suspend(std::coroutine_handle<> h)
|
||||
{
|
||||
ctx->set_waiter(span(), h, &env, &timed_out, deadline);
|
||||
waiter_id = ctx->set_waiter(span(), h, &env, &timed_out,
|
||||
deadline, scope, &cancelled);
|
||||
if (scope_stop.stop_possible()) {
|
||||
scope_cb.emplace(scope_stop,
|
||||
WaiterCancelFn{ctx, waiter_id});
|
||||
}
|
||||
if (user_stop.stop_possible()) {
|
||||
user_cb.emplace(user_stop, WaiterCancelFn{ctx, waiter_id});
|
||||
}
|
||||
}
|
||||
[[nodiscard]] decltype(auto) await_resume()
|
||||
|
||||
decltype(auto) await_resume()
|
||||
{
|
||||
return resume(std::move(env), timed_out);
|
||||
scope_cb.reset();
|
||||
user_cb.reset();
|
||||
if constexpr (std::is_invocable_v<Resume&, EventEnvelope&&,
|
||||
bool, bool>) {
|
||||
return resume(std::move(env), timed_out, cancelled);
|
||||
} else {
|
||||
return resume(std::move(env), timed_out);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -49,10 +98,24 @@ namespace Void::Fsm::Detail
|
||||
template <typename Storage, typename Resume>
|
||||
[[nodiscard]] auto make_event_awaiter(
|
||||
ExecutionContext* ctx, Storage types,
|
||||
std::optional<std::chrono::steady_clock::time_point> deadline,
|
||||
Resume resume)
|
||||
std::optional<Time::MonotonicClock::time_point> deadline,
|
||||
Resume resume,
|
||||
ExecutionContext::ScopeId scope = ExecutionContext::kNoScope,
|
||||
std::stop_token scope_stop = {}, std::stop_token user_stop = {})
|
||||
{
|
||||
return EventAwaiter<Storage, Resume>{
|
||||
ctx, std::move(types), {}, false, deadline, std::move(resume)};
|
||||
ctx,
|
||||
std::move(types),
|
||||
{},
|
||||
false,
|
||||
false,
|
||||
deadline,
|
||||
std::move(resume),
|
||||
scope,
|
||||
std::move(scope_stop),
|
||||
std::move(user_stop),
|
||||
0,
|
||||
std::nullopt,
|
||||
std::nullopt};
|
||||
}
|
||||
} // namespace Void::Fsm::Detail
|
||||
@@ -4,6 +4,8 @@
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <atomic>
|
||||
@@ -14,6 +16,7 @@
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <semaphore>
|
||||
@@ -28,17 +31,14 @@ namespace Void::Fsm::Detail
|
||||
{
|
||||
/// Type-erased state. Concrete states derive the single Machine<Derived>::
|
||||
/// State base; the engine drives each via a signature-inferred per-state
|
||||
/// thunk (entry / reactive table / continuation handlers).
|
||||
/// thunk (entry / continuation handlers).
|
||||
class StateBase
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~StateBase() = default;
|
||||
|
||||
/// Optional entry/exit lifecycle hooks (default no-ops). The
|
||||
/// state's behaviour (entry / reactive table / continuation
|
||||
/// handlers) is discovered by signature via a per-state driver
|
||||
/// thunk — there is no virtual run().
|
||||
/// Optional entry/exit lifecycle hooks (default no-ops).
|
||||
virtual Coro::Task<void> on_enter();
|
||||
virtual Coro::Task<void> on_exit();
|
||||
};
|
||||
@@ -46,18 +46,28 @@ namespace Void::Fsm::Detail
|
||||
struct EventEnvelope {
|
||||
const std::type_info* type{nullptr};
|
||||
std::any value;
|
||||
std::size_t bytes{0};
|
||||
};
|
||||
|
||||
/// Shared execution substrate for a machine and any machines it nests:
|
||||
/// one executor + one worker thread + one typed event mailbox. A single
|
||||
/// consumer (the worker, or the embedder via pump()) touches all
|
||||
/// mailbox state, so state code runs lock-free and single-threaded;
|
||||
/// cross-thread post() only enqueues.
|
||||
/// one logical strand (owned worker, embedder pump(), or borrowed external
|
||||
/// executor) + bounded event mailbox + reserved control lane + Clock-driven
|
||||
/// timers. Cross-thread posts enqueue owned envelopes; only the active
|
||||
/// consumer strand touches waiter/timer/buffer tables.
|
||||
class ExecutionContext
|
||||
: public std::enable_shared_from_this<ExecutionContext>
|
||||
{
|
||||
public:
|
||||
|
||||
ExecutionContext() = default;
|
||||
using TimerId = std::uint64_t;
|
||||
using WaiterId = std::uint64_t;
|
||||
using ScopeId = std::uint64_t;
|
||||
static constexpr ScopeId kNoScope = 0;
|
||||
|
||||
explicit ExecutionContext(
|
||||
const Time::MonotonicClock* clock = nullptr,
|
||||
FsmLimits limits = {},
|
||||
Async::Executor* external_executor = nullptr);
|
||||
~ExecutionContext();
|
||||
|
||||
ExecutionContext(const ExecutionContext&) = delete;
|
||||
@@ -67,14 +77,61 @@ namespace Void::Fsm::Detail
|
||||
{
|
||||
return m_executor;
|
||||
}
|
||||
[[nodiscard]] Async::Executor& active_executor() noexcept
|
||||
{
|
||||
return m_external_executor != nullptr
|
||||
? *m_external_executor
|
||||
: static_cast<Async::Executor&>(m_executor);
|
||||
}
|
||||
[[nodiscard]] const Time::MonotonicClock& clock() const noexcept
|
||||
{
|
||||
return *m_clock;
|
||||
}
|
||||
[[nodiscard]] const FsmLimits& limits() const noexcept
|
||||
{
|
||||
return m_limits;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t dispatch_turn() const noexcept
|
||||
{
|
||||
return m_dispatch_turn;
|
||||
}
|
||||
[[nodiscard]] std::size_t last_turn_events() const noexcept
|
||||
{
|
||||
return m_last_turn_events;
|
||||
}
|
||||
[[nodiscard]] std::size_t queued_events() const noexcept
|
||||
{
|
||||
return m_queued_events.load(std::memory_order_acquire);
|
||||
}
|
||||
[[nodiscard]] std::size_t queued_bytes() const noexcept
|
||||
{
|
||||
return m_queued_bytes.load(std::memory_order_acquire);
|
||||
}
|
||||
[[nodiscard]] std::size_t active_child_regions() const noexcept
|
||||
{
|
||||
return m_active_child_regions.load(std::memory_order_acquire);
|
||||
}
|
||||
[[nodiscard]] std::size_t timer_count() const noexcept
|
||||
{
|
||||
return m_timers.size();
|
||||
}
|
||||
|
||||
// ── events (post is the only cross-thread entry point) ────────
|
||||
[[nodiscard]] bool
|
||||
try_acquire_child_regions(std::size_t count) noexcept;
|
||||
void release_child_regions(std::size_t count) noexcept;
|
||||
|
||||
// ── events & control (thread-safe entry points) ──────────────
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
try_post(EventEnvelope env);
|
||||
void post(EventEnvelope env);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
try_post_control(std::function<void()> fn);
|
||||
|
||||
// Mailbox ops — consumer thread only (called from awaiters that
|
||||
// run on the executor, and from the worker drain).
|
||||
|
||||
using TimerId = std::uint64_t;
|
||||
// ── strand-only scope/waiter/timer APIs ──────────────────────
|
||||
[[nodiscard]] ScopeId allocate_scope() noexcept
|
||||
{
|
||||
return m_next_scope.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/// Pop the oldest buffered event whose type is in `types`.
|
||||
[[nodiscard]] bool
|
||||
@@ -82,68 +139,66 @@ namespace Void::Fsm::Detail
|
||||
EventEnvelope& out);
|
||||
|
||||
/// Suspend until an event of one of `types` arrives, or (if
|
||||
/// `deadline` is set) the deadline passes. `slot` receives the
|
||||
/// matched event; `*timed_out` is set true on timeout.
|
||||
void set_waiter(
|
||||
/// `deadline` is set) the deadline passes, or the waiter/scope is
|
||||
/// cancelled.
|
||||
WaiterId set_waiter(
|
||||
std::span<const std::type_info* const> types,
|
||||
std::coroutine_handle<> cont, EventEnvelope* slot,
|
||||
bool* timed_out,
|
||||
std::optional<std::chrono::steady_clock::time_point> deadline);
|
||||
std::optional<Time::MonotonicClock::time_point> deadline,
|
||||
ScopeId scope = kNoScope, bool* cancelled = nullptr);
|
||||
|
||||
/// Schedule `on_fire` at `deadline`. Returns an id for
|
||||
/// cancel_timer.
|
||||
TimerId add_timer(std::chrono::steady_clock::time_point deadline,
|
||||
std::function<void()>
|
||||
on_fire);
|
||||
void cancel_waiter(WaiterId id);
|
||||
void cancel_scope(ScopeId scope);
|
||||
void purge_scope(ScopeId scope);
|
||||
void drain_control_queue();
|
||||
|
||||
/// Schedule `on_fire` at `deadline` (enforces max_timers).
|
||||
[[nodiscard]] Void::Result::Result<TimerId>
|
||||
try_add_timer(Time::MonotonicClock::time_point deadline,
|
||||
std::function<void()> on_fire,
|
||||
ScopeId scope = kNoScope);
|
||||
TimerId add_timer(Time::MonotonicClock::time_point deadline,
|
||||
std::function<void()> on_fire,
|
||||
ScopeId scope = kNoScope);
|
||||
void cancel_timer(TimerId id);
|
||||
|
||||
// ── worker lifecycle ─────────────────────────────────────────
|
||||
/// Spawn the worker thread (idempotent).
|
||||
// ── worker / pump lifecycle ──────────────────────────────────
|
||||
void start_worker();
|
||||
/// Mark finished and wake the worker so it can exit.
|
||||
void finish();
|
||||
/// Stop and join the worker.
|
||||
void stop();
|
||||
/// Join the worker without forcing finish (waits for the
|
||||
/// driver to finish() on its own).
|
||||
void join();
|
||||
[[nodiscard]] bool finished() const noexcept
|
||||
{
|
||||
return m_done.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
/// Embedder-driven step: deliver queued events + run ready
|
||||
/// coroutines. Returns work done count. Single consumer only.
|
||||
/// A no-op (returns 0) while paused.
|
||||
/// Embedder-driven step: drain control lane, fire due timers on
|
||||
/// injected clock, deliver up to max_events_per_turn /
|
||||
/// max_turn_duration user events, and drain internal executor.
|
||||
std::size_t pump();
|
||||
|
||||
/// Pause / resume event processing. While paused the worker stops
|
||||
/// draining (and pump() is a no-op); posted events buffer.
|
||||
void set_paused(bool paused);
|
||||
/// Called on external executor threads via scheduled task.
|
||||
void run_external_pump_step();
|
||||
|
||||
/// Wake the consumer (e.g. to re-check an external jump request).
|
||||
void set_paused(bool paused);
|
||||
void nudge() { wake(); }
|
||||
|
||||
private:
|
||||
|
||||
void deliver(EventEnvelope& env);
|
||||
void run_loop();
|
||||
void wake() noexcept;
|
||||
void fire_due_timers();
|
||||
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
|
||||
next_deadline() const;
|
||||
struct BufferedEvent {
|
||||
std::any value;
|
||||
std::size_t bytes{0};
|
||||
};
|
||||
|
||||
Async::ManualExecutor m_executor;
|
||||
Async::MpscQueue<EventEnvelope> m_queue;
|
||||
|
||||
std::unordered_map<std::type_index, std::deque<std::any>> m_buffers;
|
||||
using WaiterId = std::uint64_t;
|
||||
struct Waiter {
|
||||
WaiterId id{0};
|
||||
ScopeId scope{kNoScope};
|
||||
std::vector<const std::type_info*> types;
|
||||
std::coroutine_handle<> cont{};
|
||||
EventEnvelope* slot{nullptr};
|
||||
bool* timed_out{nullptr};
|
||||
bool* cancelled{nullptr};
|
||||
TimerId timer{0};
|
||||
|
||||
[[nodiscard]] bool wants(const std::type_info& t) const
|
||||
@@ -156,20 +211,52 @@ namespace Void::Fsm::Detail
|
||||
return false;
|
||||
}
|
||||
};
|
||||
// Several waiters can be parked at once (parallel regions, deferred
|
||||
// events). An event resumes the first (FIFO) that wants its type.
|
||||
|
||||
struct Timer {
|
||||
Time::MonotonicClock::time_point deadline;
|
||||
std::function<void()> on_fire;
|
||||
ScopeId scope{kNoScope};
|
||||
};
|
||||
|
||||
void deliver(EventEnvelope& env);
|
||||
void run_loop();
|
||||
void wake() noexcept;
|
||||
void schedule_external_pump() noexcept;
|
||||
void fire_due_timers();
|
||||
[[nodiscard]] std::optional<Time::MonotonicClock::time_point>
|
||||
next_deadline() const;
|
||||
|
||||
const Time::MonotonicClock* m_clock;
|
||||
FsmLimits m_limits;
|
||||
Async::Executor* m_external_executor{nullptr};
|
||||
Async::ManualExecutor m_executor;
|
||||
|
||||
Async::MpscQueue<EventEnvelope> m_queue;
|
||||
std::atomic<std::size_t> m_queued_events{0};
|
||||
std::atomic<std::size_t> m_queued_bytes{0};
|
||||
|
||||
Async::MpscQueue<std::function<void()>> m_control_queue;
|
||||
std::atomic<std::size_t> m_queued_control{0};
|
||||
|
||||
std::unordered_map<std::type_index, std::deque<BufferedEvent>>
|
||||
m_buffers;
|
||||
std::size_t m_buffered_events{0};
|
||||
std::size_t m_buffered_bytes{0};
|
||||
|
||||
std::vector<Waiter> m_waiters;
|
||||
WaiterId m_next_waiter{1};
|
||||
|
||||
struct Timer {
|
||||
std::chrono::steady_clock::time_point deadline;
|
||||
std::function<void()> on_fire;
|
||||
};
|
||||
std::map<TimerId, Timer> m_timers;
|
||||
TimerId m_next_timer{1};
|
||||
|
||||
std::atomic<ScopeId> m_next_scope{1};
|
||||
std::atomic<std::size_t> m_active_child_regions{0};
|
||||
std::uint64_t m_dispatch_turn{0};
|
||||
std::size_t m_last_turn_events{0};
|
||||
|
||||
std::counting_semaphore<> m_wakeup{0};
|
||||
std::atomic<bool> m_sleeping{false};
|
||||
std::atomic<bool> m_pump_scheduled{false};
|
||||
std::atomic<bool> m_done{false};
|
||||
std::atomic<bool> m_paused{false};
|
||||
std::atomic<bool> m_worker_started{false};
|
||||
|
||||
+1511
-397
File diff suppressed because it is too large.
Load diff
@@ -1,27 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Fsm/StateKey.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
enum class SupervisionMode : std::uint8_t {
|
||||
StopOnFault = 0,
|
||||
BoundedRestart
|
||||
};
|
||||
|
||||
struct SupervisionPolicy {
|
||||
SupervisionMode mode{SupervisionMode::StopOnFault};
|
||||
std::size_t max_restarts{3};
|
||||
std::chrono::nanoseconds restart_window{std::chrono::seconds{60}};
|
||||
std::chrono::nanoseconds initial_backoff{
|
||||
std::chrono::milliseconds{10}};
|
||||
};
|
||||
|
||||
struct OrchestratorLimits {
|
||||
std::size_t max_supervised{1024};
|
||||
};
|
||||
|
||||
struct SupervisionEvent {
|
||||
enum class Kind : std::uint8_t {
|
||||
Launched = 0,
|
||||
RestartScheduled,
|
||||
Restarted,
|
||||
Released,
|
||||
Exhausted
|
||||
};
|
||||
Kind kind{Kind::Launched};
|
||||
Status status{Status::Idle};
|
||||
TerminationReason reason{TerminationReason::none};
|
||||
std::size_t restarts{0};
|
||||
std::string detail{};
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
// Type-erased supervised FSM. Models wrap a concrete Machine<R>
|
||||
// subclass; the orchestrator only needs lifecycle + status.
|
||||
// subclass; the orchestrator drives lifecycle, status, and bounded
|
||||
// restart.
|
||||
class FsmConcept
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~FsmConcept() = default;
|
||||
virtual void stop() = 0;
|
||||
virtual void restart() = 0;
|
||||
[[nodiscard]] virtual Status status() const = 0;
|
||||
[[nodiscard]] virtual TerminationReason
|
||||
termination_reason() const = 0;
|
||||
[[nodiscard]] virtual std::optional<FsmError>
|
||||
system_error() const = 0;
|
||||
};
|
||||
|
||||
template <typename F> class FsmModel final : public FsmConcept
|
||||
@@ -33,11 +79,29 @@ namespace Void::Fsm
|
||||
{
|
||||
}
|
||||
|
||||
~FsmModel() override
|
||||
{
|
||||
if (m_fsm) {
|
||||
m_fsm->stop();
|
||||
}
|
||||
}
|
||||
|
||||
void stop() override { m_fsm->stop(); }
|
||||
void restart() override { m_fsm->restart(); }
|
||||
[[nodiscard]] Status status() const override
|
||||
{
|
||||
return m_fsm->status();
|
||||
}
|
||||
[[nodiscard]] TerminationReason
|
||||
termination_reason() const override
|
||||
{
|
||||
return m_fsm->termination_reason();
|
||||
}
|
||||
[[nodiscard]] std::optional<FsmError>
|
||||
system_error() const override
|
||||
{
|
||||
return m_fsm->system_error();
|
||||
}
|
||||
|
||||
[[nodiscard]] F& get() noexcept { return *m_fsm; }
|
||||
|
||||
@@ -45,10 +109,27 @@ namespace Void::Fsm
|
||||
|
||||
std::unique_ptr<F> m_fsm;
|
||||
};
|
||||
|
||||
struct SupervisedEntry {
|
||||
std::shared_ptr<FsmConcept> model;
|
||||
SupervisionPolicy policy{};
|
||||
std::vector<Time::MonotonicClock::time_point>
|
||||
restart_timestamps;
|
||||
std::optional<Time::MonotonicClock::time_point>
|
||||
next_restart_at;
|
||||
std::atomic<std::size_t> restarts{0};
|
||||
mutable std::mutex evidence_mu;
|
||||
bool released{false};
|
||||
Status final_status{Status::Idle};
|
||||
TerminationReason final_reason{TerminationReason::none};
|
||||
std::optional<FsmError> final_error{};
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
/// A non-owning supervision handle to a launched FSM: query status and
|
||||
/// stop it. The Orchestrator owns the FSM's lifetime.
|
||||
/// Owning handle to a supervised FSM instance: holds a shared_ptr so
|
||||
/// immutable termination evidence and any still-required cleanup ownership
|
||||
/// survive even after the Orchestrator releases a finished entry from
|
||||
/// active supervision.
|
||||
class FsmHandle
|
||||
{
|
||||
public:
|
||||
@@ -57,48 +138,92 @@ namespace Void::Fsm
|
||||
|
||||
void stop() const
|
||||
{
|
||||
if (m_impl) {
|
||||
m_impl->stop();
|
||||
if (m_entry && m_entry->model) {
|
||||
m_entry->model->stop();
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Status status() const
|
||||
{
|
||||
return m_impl ? m_impl->status() : Status::Idle;
|
||||
if (!m_entry) {
|
||||
return Status::Idle;
|
||||
}
|
||||
std::lock_guard lk{m_entry->evidence_mu};
|
||||
if (m_entry->released) {
|
||||
return m_entry->final_status;
|
||||
}
|
||||
return m_entry->model ? m_entry->model->status() : Status::Idle;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool finished() const
|
||||
[[nodiscard]] bool finished() const { return terminal(status()); }
|
||||
|
||||
[[nodiscard]] TerminationReason termination_reason() const
|
||||
{
|
||||
const auto s = status();
|
||||
return s == Status::Succeeded || s == Status::Failed;
|
||||
if (!m_entry) {
|
||||
return TerminationReason::none;
|
||||
}
|
||||
std::lock_guard lk{m_entry->evidence_mu};
|
||||
if (m_entry->released) {
|
||||
return m_entry->final_reason;
|
||||
}
|
||||
return m_entry->model ? m_entry->model->termination_reason()
|
||||
: TerminationReason::none;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<FsmError> system_error() const
|
||||
{
|
||||
if (!m_entry) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::lock_guard lk{m_entry->evidence_mu};
|
||||
if (m_entry->released) {
|
||||
return m_entry->final_error;
|
||||
}
|
||||
return m_entry->model ? m_entry->model->system_error()
|
||||
: std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t restart_count() const noexcept
|
||||
{
|
||||
return m_entry
|
||||
? m_entry->restarts.load(std::memory_order_acquire)
|
||||
: 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_impl != nullptr;
|
||||
return m_entry != nullptr && m_entry->model != nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
friend class Orchestrator;
|
||||
explicit FsmHandle(std::shared_ptr<Detail::FsmConcept> impl)
|
||||
: m_impl(std::move(impl))
|
||||
explicit FsmHandle(std::shared_ptr<Detail::SupervisedEntry> entry)
|
||||
: m_entry(std::move(entry))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<Detail::FsmConcept> m_impl;
|
||||
std::shared_ptr<Detail::SupervisedEntry> m_entry;
|
||||
};
|
||||
|
||||
// ── Orchestrator ──────────────────────────────────────────────────────
|
||||
// Owns a ServiceRegistry and supervises a set of FSM instances. Each
|
||||
// launched FSM is injected with the registry as its context, so its
|
||||
// states resolve dependencies by interface (no concrete coupling), and
|
||||
// is started immediately. stop_all() winds everything down.
|
||||
class Orchestrator
|
||||
{
|
||||
public:
|
||||
|
||||
Orchestrator() = default;
|
||||
using ObserverCallback =
|
||||
std::function<void(const SupervisionEvent&)>;
|
||||
|
||||
explicit Orchestrator(
|
||||
const Time::MonotonicClock* clock = nullptr,
|
||||
OrchestratorLimits limits = {}) noexcept
|
||||
: m_clock(clock != nullptr
|
||||
? clock
|
||||
: &Time::SystemMonotonicClock::instance()),
|
||||
m_limits(limits)
|
||||
{
|
||||
}
|
||||
|
||||
~Orchestrator() { stop_all(); }
|
||||
|
||||
Orchestrator(const Orchestrator&) = delete;
|
||||
@@ -109,8 +234,6 @@ namespace Void::Fsm
|
||||
return m_registry;
|
||||
}
|
||||
|
||||
/// Call on_start() on lifecycle services. Call before launching
|
||||
/// FSMs that expect started services.
|
||||
void start_services()
|
||||
{
|
||||
m_registry.start_all();
|
||||
@@ -118,36 +241,177 @@ namespace Void::Fsm
|
||||
m_services_stopped = false;
|
||||
}
|
||||
|
||||
/// Construct F, inject the registry, start it, and supervise.
|
||||
/// F must derive Fsm::Machine<...> (provides set_services /
|
||||
/// start / stop / status).
|
||||
template <typename F, typename... Args>
|
||||
[[nodiscard]] Void::Result::Result<FsmHandle>
|
||||
try_launch(SupervisionPolicy policy, Args&&... args)
|
||||
{
|
||||
std::vector<ObserverCallback> observers_copy;
|
||||
std::shared_ptr<Detail::SupervisedEntry> entry;
|
||||
{
|
||||
reap_finished_and_notify();
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (m_limits.max_supervised > 0 &&
|
||||
m_entries.size() >= m_limits.max_supervised) {
|
||||
return Void::Result::fail(make_fsm_error(
|
||||
FsmErrorCode::limit_exceeded,
|
||||
"Orchestrator: max_supervised limit reached"));
|
||||
}
|
||||
auto fsm =
|
||||
std::make_unique<F>(std::forward<Args>(args)...);
|
||||
fsm->set_services(m_registry);
|
||||
fsm->start();
|
||||
auto model =
|
||||
std::make_shared<Detail::FsmModel<F>>(std::move(fsm));
|
||||
entry = std::make_shared<Detail::SupervisedEntry>();
|
||||
entry->model = std::move(model);
|
||||
entry->policy = policy;
|
||||
m_entries.push_back(entry);
|
||||
}
|
||||
|
||||
notify_observers(SupervisionEvent{
|
||||
.kind = SupervisionEvent::Kind::Launched,
|
||||
.status = entry->model->status(),
|
||||
.reason = entry->model->termination_reason(),
|
||||
.restarts = 0,
|
||||
.detail = {}});
|
||||
return FsmHandle{std::move(entry)};
|
||||
}
|
||||
|
||||
template <typename F, typename... Args>
|
||||
FsmHandle launch(Args&&... args)
|
||||
{
|
||||
auto fsm = std::make_unique<F>(std::forward<Args>(args)...);
|
||||
fsm->set_services(m_registry);
|
||||
fsm->start();
|
||||
auto model =
|
||||
std::make_shared<Detail::FsmModel<F>>(std::move(fsm));
|
||||
std::lock_guard lock{m_mutex};
|
||||
m_running.push_back(model);
|
||||
return FsmHandle{model};
|
||||
auto r = try_launch<F>(SupervisionPolicy{},
|
||||
std::forward<Args>(args)...);
|
||||
return r ? *r : FsmHandle{};
|
||||
}
|
||||
|
||||
/// Stop and release every supervised FSM, then stop services.
|
||||
void stop_all()
|
||||
/// Drive supervision rules (bounded restarts with injected Time
|
||||
/// backoff, and releasing terminal entries while handles keep
|
||||
/// immutable evidence). Returns actions taken (restarts + releases).
|
||||
std::size_t supervise_step()
|
||||
{
|
||||
std::vector<std::shared_ptr<Detail::FsmConcept>> running;
|
||||
std::vector<SupervisionEvent> events;
|
||||
std::vector<std::shared_ptr<Detail::SupervisedEntry>>
|
||||
to_restart;
|
||||
const auto now = m_clock->now();
|
||||
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
running.swap(m_running);
|
||||
for (auto it = m_entries.begin(); it != m_entries.end();) {
|
||||
auto& e = *it;
|
||||
const auto st = e->model->status();
|
||||
if (!terminal(st)) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (e->policy.mode == SupervisionMode::BoundedRestart &&
|
||||
st == Status::Faulted) {
|
||||
std::erase_if(
|
||||
e->restart_timestamps, [&](const auto ts) {
|
||||
return (now - ts) >=
|
||||
e->policy.restart_window;
|
||||
});
|
||||
if (e->restart_timestamps.size() <
|
||||
e->policy.max_restarts) {
|
||||
if (!e->next_restart_at.has_value()) {
|
||||
const std::size_t attempt =
|
||||
e->restart_timestamps.size();
|
||||
const auto shift =
|
||||
attempt < 16 ? attempt : 16;
|
||||
const auto backoff =
|
||||
e->policy.initial_backoff *
|
||||
(std::size_t{1} << shift);
|
||||
e->next_restart_at = now + backoff;
|
||||
events.push_back(SupervisionEvent{
|
||||
.kind = SupervisionEvent::Kind::
|
||||
RestartScheduled,
|
||||
.status = st,
|
||||
.reason =
|
||||
e->model->termination_reason(),
|
||||
.restarts = e->restarts.load(
|
||||
std::memory_order_acquire),
|
||||
.detail = e->model->system_error()
|
||||
? e->model->system_error()
|
||||
->message
|
||||
: std::string{}});
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
if (now < *e->next_restart_at) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
e->restart_timestamps.push_back(now);
|
||||
e->next_restart_at.reset();
|
||||
e->restarts.fetch_add(
|
||||
1, std::memory_order_acq_rel);
|
||||
to_restart.push_back(e);
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
|
||||
snapshot_released_evidence(*e);
|
||||
events.push_back(SupervisionEvent{
|
||||
.kind = SupervisionEvent::Kind::Exhausted,
|
||||
.status = e->final_status,
|
||||
.reason = e->final_reason,
|
||||
.restarts =
|
||||
e->restarts.load(std::memory_order_acquire),
|
||||
.detail =
|
||||
e->final_error
|
||||
? e->final_error->message
|
||||
: std::string{"restart budget exhausted"}});
|
||||
it = m_entries.erase(it);
|
||||
continue;
|
||||
}
|
||||
|
||||
snapshot_released_evidence(*e);
|
||||
events.push_back(SupervisionEvent{
|
||||
.kind = SupervisionEvent::Kind::Released,
|
||||
.status = e->final_status,
|
||||
.reason = e->final_reason,
|
||||
.restarts =
|
||||
e->restarts.load(std::memory_order_acquire),
|
||||
.detail = e->final_error ? e->final_error->message
|
||||
: std::string{}});
|
||||
it = m_entries.erase(it);
|
||||
}
|
||||
}
|
||||
for (auto& m : running) {
|
||||
m->stop();
|
||||
|
||||
for (auto& e : to_restart) {
|
||||
e->model->restart();
|
||||
events.push_back(SupervisionEvent{
|
||||
.kind = SupervisionEvent::Kind::Restarted,
|
||||
.status = e->model->status(),
|
||||
.reason = e->model->termination_reason(),
|
||||
.restarts = e->restarts.load(std::memory_order_acquire),
|
||||
.detail = {}});
|
||||
}
|
||||
|
||||
const std::size_t count = events.size();
|
||||
for (const auto& ev : events) {
|
||||
notify_observers(ev);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/// Release finished stop-on-fault (or non-faulted) entries from
|
||||
/// active supervision while existing handles retain evidence.
|
||||
std::size_t reap_finished() { return reap_finished_and_notify(); }
|
||||
|
||||
void stop_all()
|
||||
{
|
||||
std::vector<std::shared_ptr<Detail::SupervisedEntry>> running;
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
running.swap(m_entries);
|
||||
}
|
||||
for (auto& e : running) {
|
||||
e->model->stop();
|
||||
snapshot_released_evidence(*e);
|
||||
}
|
||||
running.clear();
|
||||
// Balance start_services() exactly once (stop_all may run
|
||||
// explicitly and again from the destructor).
|
||||
if (m_services_started && !m_services_stopped) {
|
||||
m_registry.stop_all();
|
||||
m_services_stopped = true;
|
||||
@@ -157,16 +421,118 @@ namespace Void::Fsm
|
||||
[[nodiscard]] std::size_t running_count() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_running.size();
|
||||
return m_entries.size();
|
||||
}
|
||||
|
||||
std::size_t observe_supervision(ObserverCallback cb)
|
||||
{
|
||||
std::lock_guard lock{m_obs_mu};
|
||||
const std::size_t id = m_next_obs_id++;
|
||||
m_observers.emplace_back(id, std::move(cb));
|
||||
return id;
|
||||
}
|
||||
|
||||
void remove_supervision_observer(std::size_t id)
|
||||
{
|
||||
std::lock_guard lock{m_obs_mu};
|
||||
std::erase_if(m_observers, [id](const auto& pair) {
|
||||
return pair.first == id;
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<std::string> observer_errors() const
|
||||
{
|
||||
std::lock_guard lock{m_obs_mu};
|
||||
return m_observer_errors;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static void
|
||||
snapshot_released_evidence(Detail::SupervisedEntry& entry)
|
||||
{
|
||||
std::lock_guard elk{entry.evidence_mu};
|
||||
if (entry.released) {
|
||||
return;
|
||||
}
|
||||
entry.final_status = entry.model->status();
|
||||
entry.final_reason = entry.model->termination_reason();
|
||||
entry.final_error = entry.model->system_error();
|
||||
entry.released = true;
|
||||
}
|
||||
|
||||
std::size_t reap_finished_and_notify()
|
||||
{
|
||||
std::vector<SupervisionEvent> events;
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
for (auto it = m_entries.begin(); it != m_entries.end();) {
|
||||
auto& e = *it;
|
||||
const auto st = e->model->status();
|
||||
if (!terminal(st)) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
if (e->policy.mode == SupervisionMode::BoundedRestart &&
|
||||
st == Status::Faulted) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
snapshot_released_evidence(*e);
|
||||
events.push_back(SupervisionEvent{
|
||||
.kind = SupervisionEvent::Kind::Released,
|
||||
.status = e->final_status,
|
||||
.reason = e->final_reason,
|
||||
.restarts =
|
||||
e->restarts.load(std::memory_order_acquire),
|
||||
.detail = e->final_error ? e->final_error->message
|
||||
: std::string{}});
|
||||
it = m_entries.erase(it);
|
||||
}
|
||||
}
|
||||
for (const auto& ev : events) {
|
||||
notify_observers(ev);
|
||||
}
|
||||
return events.size();
|
||||
}
|
||||
|
||||
void notify_observers(const SupervisionEvent& ev)
|
||||
{
|
||||
std::vector<ObserverCallback> copy;
|
||||
{
|
||||
std::lock_guard lock{m_obs_mu};
|
||||
copy.reserve(m_observers.size());
|
||||
for (const auto& [id, fn] : m_observers) {
|
||||
if (fn) {
|
||||
copy.push_back(fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto& fn : copy) {
|
||||
try {
|
||||
fn(ev);
|
||||
} catch (const std::exception& ex) {
|
||||
std::lock_guard lock{m_obs_mu};
|
||||
m_observer_errors.push_back(ex.what());
|
||||
} catch (...) {
|
||||
std::lock_guard lock{m_obs_mu};
|
||||
m_observer_errors.push_back("observer threw unknown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const Time::MonotonicClock* m_clock;
|
||||
OrchestratorLimits m_limits{};
|
||||
Service::ServiceRegistry m_registry;
|
||||
mutable std::mutex m_mutex;
|
||||
std::vector<std::shared_ptr<Detail::FsmConcept>> m_running;
|
||||
std::vector<std::shared_ptr<Detail::SupervisedEntry>> m_entries;
|
||||
bool m_services_started{false};
|
||||
bool m_services_stopped{false};
|
||||
|
||||
mutable std::mutex m_obs_mu;
|
||||
std::vector<std::pair<std::size_t, ObserverCallback>> m_observers;
|
||||
std::vector<std::string> m_observer_errors;
|
||||
std::size_t m_next_obs_id{1};
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -1,10 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
|
||||
@@ -33,6 +45,153 @@ namespace Void::Fsm
|
||||
Faulted // stopped by a system fault (see system_error())
|
||||
};
|
||||
|
||||
/// Canonical shared predicate identifying every terminal Status value.
|
||||
[[nodiscard]] constexpr bool terminal(Status s) noexcept
|
||||
{
|
||||
return s == Status::Succeeded || s == Status::Failed ||
|
||||
s == Status::Faulted;
|
||||
}
|
||||
|
||||
/// Why a machine finished (preserving Status values while distinguishing
|
||||
/// cooperative cancellation and deadline expiration from application
|
||||
/// outcomes and system faults).
|
||||
enum class TerminationReason : std::uint8_t {
|
||||
none = 0,
|
||||
succeeded,
|
||||
failed,
|
||||
faulted,
|
||||
cancelled,
|
||||
timed_out
|
||||
};
|
||||
|
||||
enum class FsmErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
invalid_state = 2,
|
||||
not_found = 3,
|
||||
overloaded = 4,
|
||||
cancelled = 5,
|
||||
timeout = 6,
|
||||
limit_exceeded = 7,
|
||||
fault = 8,
|
||||
checkpoint_rejected = 9,
|
||||
schema_mismatch = 10,
|
||||
migration_failed = 11,
|
||||
service_unavailable = 12,
|
||||
internal = 13
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_fsm_error(FsmErrorCode code, std::string message = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case FsmErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case FsmErrorCode::invalid_argument:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case FsmErrorCode::invalid_state:
|
||||
case FsmErrorCode::checkpoint_rejected:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case FsmErrorCode::not_found:
|
||||
case FsmErrorCode::service_unavailable:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case FsmErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case FsmErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case FsmErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case FsmErrorCode::limit_exceeded:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case FsmErrorCode::schema_mismatch:
|
||||
case FsmErrorCode::migration_failed:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case FsmErrorCode::fault:
|
||||
case FsmErrorCode::internal:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kFsmErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
/// Explicit resource and scheduling bounds for FSM execution.
|
||||
struct FsmLimits {
|
||||
std::size_t max_mailbox_events{1024};
|
||||
std::size_t max_mailbox_bytes{std::size_t{4} * 1024 * 1024};
|
||||
std::size_t max_deferred_events{256};
|
||||
std::size_t max_timers{1024};
|
||||
std::size_t max_child_regions{128};
|
||||
std::size_t max_hierarchy_depth{32};
|
||||
std::size_t max_retained_transitions{256};
|
||||
std::size_t max_checkpoint_bytes{std::size_t{4} * 1024 * 1024};
|
||||
std::size_t max_events_per_turn{64};
|
||||
std::chrono::nanoseconds max_turn_duration{
|
||||
std::chrono::milliseconds{1}};
|
||||
std::size_t max_control_messages{256};
|
||||
};
|
||||
|
||||
/// Explicit borrowed execution binding passed to Machine::run().
|
||||
struct ExecutionBinding {
|
||||
Async::Executor* executor{nullptr};
|
||||
const Time::MonotonicClock* clock{
|
||||
&Time::SystemMonotonicClock::instance()};
|
||||
FsmLimits limits{};
|
||||
};
|
||||
|
||||
/// Versioned boundary checkpoint capturing machine identity, schema,
|
||||
/// durable state ID, optional application safe-point resume label, and
|
||||
/// serialized application state.
|
||||
struct Checkpoint {
|
||||
static constexpr std::uint32_t kFormatVersion = 1;
|
||||
std::uint32_t format_version{kFormatVersion};
|
||||
std::string machine_type;
|
||||
std::uint32_t application_schema{1};
|
||||
std::uint64_t transition_sequence{0};
|
||||
std::string state_id;
|
||||
std::string resume_label;
|
||||
Json::Value state;
|
||||
};
|
||||
|
||||
/// Annotation tag specifying a durable state ID (`[[= Void::Fsm::StateId{"..."}]]`).
|
||||
struct StateId {
|
||||
Void::Meta::Str value;
|
||||
};
|
||||
|
||||
/// Byte-size accounting helper for typed event admission into bounded
|
||||
/// FSM mailboxes.
|
||||
template <typename E>
|
||||
[[nodiscard]] constexpr std::size_t event_payload_bytes(const E& e) noexcept
|
||||
{
|
||||
if constexpr (requires {
|
||||
{
|
||||
e.payload_bytes()
|
||||
} -> std::convertible_to<std::size_t>;
|
||||
}) {
|
||||
return static_cast<std::size_t>(e.payload_bytes());
|
||||
} else if constexpr (std::is_same_v<std::remove_cvref_t<E>,
|
||||
std::string>) {
|
||||
return sizeof(E) + e.size();
|
||||
} else {
|
||||
return sizeof(E);
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome of a sub-machine launched via startMachine<Sub, Next>():
|
||||
/// a typed Success value, a typed Failure value, or a system fault.
|
||||
struct LaunchResult {
|
||||
|
||||
@@ -60,6 +60,26 @@ 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;
|
||||
inline constexpr std::uint32_t kIpcErrorDomain = 16;
|
||||
inline constexpr std::uint32_t kArchiveErrorDomain = 17;
|
||||
inline constexpr std::uint32_t kCryptoErrorDomain = 18;
|
||||
inline constexpr std::uint32_t kSecurityErrorDomain = 19;
|
||||
inline constexpr std::uint32_t kUpdateErrorDomain = 20;
|
||||
inline constexpr std::uint32_t kSqliteErrorDomain = 21;
|
||||
inline constexpr std::uint32_t kServiceErrorDomain = 22;
|
||||
inline constexpr std::uint32_t kPluginErrorDomain = 23;
|
||||
inline constexpr std::uint32_t kConfigurationErrorDomain = 24;
|
||||
inline constexpr std::uint32_t kFsmErrorDomain = 25;
|
||||
inline constexpr std::uint32_t kNetErrorDomain = 26;
|
||||
inline constexpr std::uint32_t kTestingMockErrorDomain = 27;
|
||||
inline constexpr std::uint32_t kShortUrlErrorDomain = 28;
|
||||
inline constexpr std::uint32_t kRpcErrorDomain = 29;
|
||||
inline constexpr std::uint32_t kDiscoveryErrorDomain = 30;
|
||||
|
||||
struct ErrorCode {
|
||||
std::uint32_t domain{kGenericErrorDomain};
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Binary/ByteBuffer.hpp>
|
||||
#include <Void/IPC/Types.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <memory_resource>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::IPC
|
||||
{
|
||||
|
||||
struct FrameHeader {
|
||||
std::uint16_t version{kWireVersion};
|
||||
std::uint8_t flags{0};
|
||||
FrameType type{FrameType::request};
|
||||
std::uint32_t payload_len{0};
|
||||
std::uint32_t stream_id{0};
|
||||
std::uint64_t request_id{0};
|
||||
};
|
||||
|
||||
class BufferQuota;
|
||||
|
||||
class QuotaPermit
|
||||
{
|
||||
public:
|
||||
QuotaPermit() noexcept = default;
|
||||
~QuotaPermit() noexcept;
|
||||
|
||||
QuotaPermit(const QuotaPermit&) = delete;
|
||||
QuotaPermit& operator=(const QuotaPermit&) = delete;
|
||||
QuotaPermit(QuotaPermit&& other) noexcept;
|
||||
QuotaPermit& operator=(QuotaPermit&& other) noexcept;
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept { return bytes_ > 0; }
|
||||
[[nodiscard]] std::size_t bytes() const noexcept { return bytes_; }
|
||||
void reset() noexcept;
|
||||
|
||||
private:
|
||||
friend class BufferQuota;
|
||||
std::weak_ptr<BufferQuota> quota_{};
|
||||
std::size_t bytes_{0};
|
||||
};
|
||||
|
||||
class BufferQuota : public std::enable_shared_from_this<BufferQuota>
|
||||
{
|
||||
public:
|
||||
explicit BufferQuota(std::size_t capacity_bytes);
|
||||
|
||||
[[nodiscard]] static std::shared_ptr<BufferQuota>
|
||||
create(std::size_t capacity_bytes);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<QuotaPermit, Void::Result::Error>
|
||||
reserve(std::size_t bytes);
|
||||
|
||||
[[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
|
||||
[[nodiscard]] std::size_t used() const noexcept;
|
||||
|
||||
private:
|
||||
friend class QuotaPermit;
|
||||
void release(std::size_t bytes) noexcept;
|
||||
|
||||
std::size_t capacity_{0};
|
||||
mutable std::mutex mu_{};
|
||||
std::size_t used_{0};
|
||||
};
|
||||
|
||||
struct DecodedFrame {
|
||||
FrameHeader header{};
|
||||
Void::Binary::FrozenBytes payload{};
|
||||
QuotaPermit global_permit{};
|
||||
QuotaPermit session_permit{};
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
validate_frame_header(const FrameHeader& header, const IpcLimits& limits);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
encode_frame_header(const FrameHeader& header,
|
||||
std::span<std::byte, kFrameHeaderSize> out);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<FrameHeader, Void::Result::Error>
|
||||
decode_frame_header(std::span<const std::byte, kFrameHeaderSize> in);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
|
||||
encode_frame(
|
||||
const FrameHeader& header,
|
||||
std::span<const std::byte> payload = {},
|
||||
const IpcLimits& limits = {},
|
||||
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
|
||||
encode_hello(const HelloInfo& info,
|
||||
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
|
||||
|
||||
[[nodiscard]] Void::Result::Result<HelloInfo, Void::Result::Error>
|
||||
decode_hello(std::span<const std::byte> payload,
|
||||
std::size_t max_bytes = 4096);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
|
||||
encode_error_payload(
|
||||
IpcErrorCode code,
|
||||
std::string_view message,
|
||||
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::pair<IpcErrorCode, std::string>,
|
||||
Void::Result::Error>
|
||||
decode_error_payload(std::span<const std::byte> payload);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
|
||||
encode_goaway_payload(
|
||||
IpcErrorCode code,
|
||||
std::uint64_t last_request_id,
|
||||
std::string_view reason,
|
||||
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
|
||||
|
||||
[[nodiscard]] Void::Result::Result<
|
||||
std::tuple<IpcErrorCode, std::uint64_t, std::string>,
|
||||
Void::Result::Error>
|
||||
decode_goaway_payload(std::span<const std::byte> payload);
|
||||
|
||||
class FrameDecoder
|
||||
{
|
||||
public:
|
||||
explicit FrameDecoder(
|
||||
IpcLimits limits = {},
|
||||
std::shared_ptr<BufferQuota> global_quota = {},
|
||||
std::shared_ptr<BufferQuota> session_quota = {},
|
||||
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
|
||||
|
||||
[[nodiscard]] static constexpr std::size_t
|
||||
frame_quota_cost(std::size_t payload_len) noexcept
|
||||
{
|
||||
return kFrameHeaderSize + payload_len;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<DecodedFrame>,
|
||||
Void::Result::Error>
|
||||
feed(std::span<const std::byte> chunk);
|
||||
|
||||
[[nodiscard]] std::size_t header_bytes_buffered() const noexcept
|
||||
{
|
||||
return header_len_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t payload_bytes_buffered() const noexcept
|
||||
{
|
||||
return has_header_ ? payload_written_ : 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool in_mid_frame() const noexcept
|
||||
{
|
||||
return header_len_ > 0 || has_header_;
|
||||
}
|
||||
|
||||
private:
|
||||
enum class State {
|
||||
reading_header,
|
||||
reading_payload,
|
||||
failed,
|
||||
};
|
||||
|
||||
IpcLimits limits_{};
|
||||
std::shared_ptr<BufferQuota> global_quota_{};
|
||||
std::shared_ptr<BufferQuota> session_quota_{};
|
||||
std::pmr::memory_resource* mr_{nullptr};
|
||||
|
||||
State state_{State::reading_header};
|
||||
std::array<std::byte, kFrameHeaderSize> header_buf_{};
|
||||
std::size_t header_len_{0};
|
||||
bool has_header_{false};
|
||||
FrameHeader current_header_{};
|
||||
QuotaPermit current_global_permit_{};
|
||||
QuotaPermit current_session_permit_{};
|
||||
std::optional<Void::Binary::ByteBuffer> payload_buf_{};
|
||||
std::size_t payload_written_{0};
|
||||
|
||||
void reset_frame_state() noexcept;
|
||||
};
|
||||
|
||||
} // namespace Void::IPC
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/IPC/Codec.hpp>
|
||||
#include <Void/IPC/Session.hpp>
|
||||
#include <Void/IPC/Transport.hpp>
|
||||
#include <Void/IPC/Types.hpp>
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Binary/ByteBuffer.hpp>
|
||||
#include <Void/IO/Driver.hpp>
|
||||
#include <Void/IPC/Codec.hpp>
|
||||
#include <Void/IPC/Transport.hpp>
|
||||
#include <Void/IPC/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <stop_token>
|
||||
|
||||
namespace Void::IPC
|
||||
{
|
||||
|
||||
using RequestHandler = std::function<Void::Coro::Task<
|
||||
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>>(
|
||||
Void::Binary::FrozenBytes payload, std::stop_token cancel)>;
|
||||
|
||||
using OneWayHandler = std::function<void(Void::Binary::FrozenBytes payload)>;
|
||||
|
||||
class Session
|
||||
{
|
||||
public:
|
||||
struct State;
|
||||
|
||||
explicit Session(
|
||||
Void::IO::Driver& driver,
|
||||
Void::Async::Executor& executor,
|
||||
DuplexTransport transport,
|
||||
IpcLimits limits = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance(),
|
||||
std::shared_ptr<BufferQuota> global_quota = {});
|
||||
|
||||
~Session() noexcept;
|
||||
|
||||
Session(const Session&) = delete;
|
||||
Session& operator=(const Session&) = delete;
|
||||
Session(Session&&) = delete;
|
||||
Session& operator=(Session&&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<HelloInfo, Void::Result::Error>>
|
||||
handshake(HelloInfo local_hello = {},
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
start(RequestHandler on_request, OneWayHandler on_one_way = {});
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<
|
||||
std::expected<Void::Binary::FrozenBytes, CallFailure>>
|
||||
request(Void::Binary::FrozenBytes payload,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
send_one_way(Void::Binary::FrozenBytes payload);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
send_goaway(IpcErrorCode code = IpcErrorCode::closed,
|
||||
std::string_view reason = "closing");
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
|
||||
close_and_join(Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] SessionStats stats() const noexcept;
|
||||
[[nodiscard]] HelloInfo negotiated_hello() const;
|
||||
[[nodiscard]] const PeerCredentials& peer_credentials() const noexcept;
|
||||
|
||||
// Test hook to inspect/force request ID near exhaustion without 2^64 calls.
|
||||
void set_next_request_id_for_test(std::uint64_t next_id) noexcept;
|
||||
|
||||
private:
|
||||
std::shared_ptr<State> state_{};
|
||||
};
|
||||
|
||||
} // namespace Void::IPC
|
||||
@@ -0,0 +1,118 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/IO/Driver.hpp>
|
||||
#include <Void/IO/Stream.hpp>
|
||||
#include <Void/IPC/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
|
||||
namespace Void::IPC
|
||||
{
|
||||
|
||||
class DuplexTransport
|
||||
{
|
||||
public:
|
||||
DuplexTransport() noexcept = default;
|
||||
DuplexTransport(Void::IO::ByteStream unified_stream,
|
||||
PeerCredentials creds) noexcept;
|
||||
DuplexTransport(Void::IO::ByteStream read_stream,
|
||||
Void::IO::ByteStream write_stream,
|
||||
PeerCredentials creds) noexcept;
|
||||
|
||||
DuplexTransport(const DuplexTransport&) = delete;
|
||||
DuplexTransport& operator=(const DuplexTransport&) = delete;
|
||||
DuplexTransport(DuplexTransport&&) noexcept = default;
|
||||
DuplexTransport& operator=(DuplexTransport&&) noexcept = default;
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept;
|
||||
[[nodiscard]] bool is_split() const noexcept { return split_; }
|
||||
[[nodiscard]] const PeerCredentials& credentials() const noexcept
|
||||
{
|
||||
return credentials_;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::IO::ByteStream& reader_stream() noexcept
|
||||
{
|
||||
return read_stream_;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::IO::ByteStream& writer_stream() noexcept
|
||||
{
|
||||
return split_ ? write_stream_ : read_stream_;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
|
||||
close_and_join(Void::Async::OperationOptions options = {});
|
||||
|
||||
private:
|
||||
friend class LocalListener;
|
||||
bool split_{false};
|
||||
Void::IO::ByteStream read_stream_{};
|
||||
Void::IO::ByteStream write_stream_{};
|
||||
PeerCredentials credentials_{};
|
||||
std::shared_ptr<void> listener_slot_{};
|
||||
};
|
||||
|
||||
class LocalListener
|
||||
{
|
||||
public:
|
||||
struct SlotState;
|
||||
|
||||
LocalListener() noexcept = default;
|
||||
~LocalListener() noexcept;
|
||||
|
||||
LocalListener(const LocalListener&) = delete;
|
||||
LocalListener& operator=(const LocalListener&) = delete;
|
||||
LocalListener(LocalListener&& other) noexcept;
|
||||
LocalListener& operator=(LocalListener&& other) noexcept;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<LocalListener, Void::Result::Error>
|
||||
listen(const std::filesystem::path& socket_path,
|
||||
IpcLimits limits = {},
|
||||
PeerPolicy policy = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<DuplexTransport>,
|
||||
Void::Result::Error>
|
||||
try_accept(Void::IO::Driver& driver);
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept { return listen_fd_ >= 0; }
|
||||
[[nodiscard]] std::size_t active_sessions() const noexcept;
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return socket_path_;
|
||||
}
|
||||
[[nodiscard]] int fd() const noexcept { return listen_fd_; }
|
||||
|
||||
void close() noexcept;
|
||||
|
||||
private:
|
||||
int listen_fd_{-1};
|
||||
int dir_fd_{-1};
|
||||
int lock_fd_{-1};
|
||||
std::filesystem::path socket_path_{};
|
||||
std::string socket_name_{};
|
||||
std::uint64_t socket_dev_{0};
|
||||
std::uint64_t socket_ino_{0};
|
||||
IpcLimits limits_{};
|
||||
PeerPolicy policy_{};
|
||||
std::shared_ptr<SlotState> slot_state_{};
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<DuplexTransport, Void::Result::Error>
|
||||
connect_local(Void::IO::Driver& driver,
|
||||
const std::filesystem::path& socket_path,
|
||||
PeerPolicy policy = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<DuplexTransport, Void::Result::Error>
|
||||
adopt_pipe_pair(Void::IO::Driver& driver, int read_fd, int write_fd);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::pair<DuplexTransport, DuplexTransport>,
|
||||
Void::Result::Error>
|
||||
create_socket_pair_transports(Void::IO::Driver& driver);
|
||||
|
||||
} // namespace Void::IPC
|
||||
@@ -0,0 +1,181 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
|
||||
namespace Void::IPC
|
||||
{
|
||||
|
||||
inline constexpr std::size_t kFrameHeaderSize = 24;
|
||||
inline constexpr std::uint16_t kWireVersion = 1;
|
||||
|
||||
enum class IpcErrorCode : std::int32_t {
|
||||
invalid_argument = 1,
|
||||
corrupt_frame = 2,
|
||||
unsupported_version = 3,
|
||||
frame_too_large = 4,
|
||||
quota_exceeded = 5,
|
||||
overloaded = 6,
|
||||
rate_limited = 7,
|
||||
cancelled = 8,
|
||||
timed_out = 9,
|
||||
transport_lost = 10,
|
||||
closed = 11,
|
||||
permission_denied = 12,
|
||||
already_exists = 13,
|
||||
not_found = 14,
|
||||
handshake_failed = 15,
|
||||
id_exhausted = 16,
|
||||
self_join = 17,
|
||||
peer_error = 18,
|
||||
internal = 19,
|
||||
};
|
||||
|
||||
[[nodiscard]] constexpr Void::Result::ErrorKind
|
||||
classify_ipc_error(IpcErrorCode code) noexcept
|
||||
{
|
||||
switch (code) {
|
||||
case IpcErrorCode::invalid_argument:
|
||||
return Void::Result::ErrorKind::invalid_argument;
|
||||
case IpcErrorCode::corrupt_frame:
|
||||
return Void::Result::ErrorKind::corrupt;
|
||||
case IpcErrorCode::unsupported_version:
|
||||
return Void::Result::ErrorKind::unsupported;
|
||||
case IpcErrorCode::frame_too_large:
|
||||
case IpcErrorCode::quota_exceeded:
|
||||
case IpcErrorCode::id_exhausted:
|
||||
return Void::Result::ErrorKind::exhausted;
|
||||
case IpcErrorCode::overloaded:
|
||||
case IpcErrorCode::rate_limited:
|
||||
return Void::Result::ErrorKind::overloaded;
|
||||
case IpcErrorCode::cancelled:
|
||||
case IpcErrorCode::closed:
|
||||
return Void::Result::ErrorKind::cancelled;
|
||||
case IpcErrorCode::timed_out:
|
||||
return Void::Result::ErrorKind::timeout;
|
||||
case IpcErrorCode::not_found:
|
||||
return Void::Result::ErrorKind::not_found;
|
||||
case IpcErrorCode::already_exists:
|
||||
case IpcErrorCode::self_join:
|
||||
return Void::Result::ErrorKind::conflict;
|
||||
case IpcErrorCode::permission_denied:
|
||||
case IpcErrorCode::transport_lost:
|
||||
case IpcErrorCode::handshake_failed:
|
||||
case IpcErrorCode::peer_error:
|
||||
return Void::Result::ErrorKind::io;
|
||||
case IpcErrorCode::internal:
|
||||
return Void::Result::ErrorKind::internal;
|
||||
}
|
||||
return Void::Result::ErrorKind::internal;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error make_ipc_error(
|
||||
IpcErrorCode code, std::string_view message, int sys_errno = 0)
|
||||
{
|
||||
std::string detail;
|
||||
std::error_code sys_ec{};
|
||||
if (sys_errno != 0) {
|
||||
detail = std::format(
|
||||
"{} (errno={}: {})", message, sys_errno, std::strerror(sys_errno));
|
||||
sys_ec = std::error_code{sys_errno, std::generic_category()};
|
||||
} else {
|
||||
detail.assign(message);
|
||||
}
|
||||
return Void::Result::Error{
|
||||
classify_ipc_error(code),
|
||||
std::move(detail),
|
||||
Void::Result::ErrorCode{Void::Result::kIpcErrorDomain,
|
||||
static_cast<std::int32_t>(code)},
|
||||
sys_ec};
|
||||
}
|
||||
|
||||
enum class FrameType : std::uint8_t {
|
||||
hello = 1,
|
||||
request = 2,
|
||||
response = 3,
|
||||
error = 4,
|
||||
cancel = 5,
|
||||
one_way = 6,
|
||||
goaway = 7,
|
||||
};
|
||||
|
||||
enum class EffectStatus : std::uint8_t {
|
||||
not_sent = 0,
|
||||
unknown = 1,
|
||||
};
|
||||
|
||||
struct CallFailure {
|
||||
Void::Result::Error error{};
|
||||
EffectStatus effect{EffectStatus::not_sent};
|
||||
bool may_have_executed{false};
|
||||
};
|
||||
|
||||
struct IpcLimits {
|
||||
std::size_t max_frame_payload{1024ULL * 1024ULL};
|
||||
std::size_t max_hello_bytes{4096};
|
||||
std::size_t max_inflight_requests{64};
|
||||
std::size_t max_active_handlers{64};
|
||||
std::size_t max_outbound_frames{128};
|
||||
std::size_t max_outbound_bytes{4ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_recv_buffer_bytes{2ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_tombstones{256};
|
||||
std::size_t max_sessions{128};
|
||||
std::size_t global_buffer_budget_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_waiters{128};
|
||||
std::size_t control_lane_max_bytes{8192};
|
||||
std::size_t control_lane_max_frames{16};
|
||||
double rate_limit_per_sec{1000.0};
|
||||
double rate_limit_burst{128.0};
|
||||
std::chrono::milliseconds handshake_timeout{std::chrono::milliseconds{5000}};
|
||||
std::chrono::milliseconds progress_timeout{std::chrono::milliseconds{5000}};
|
||||
std::chrono::milliseconds idle_timeout{std::chrono::milliseconds{60000}};
|
||||
};
|
||||
|
||||
struct PeerCredentials {
|
||||
bool available{false};
|
||||
long long pid{-1};
|
||||
unsigned long uid{0};
|
||||
unsigned long gid{0};
|
||||
};
|
||||
|
||||
struct PeerPolicy {
|
||||
bool require_uid_match{true};
|
||||
bool set_allowed_uid_to_current_user{true};
|
||||
unsigned long allowed_uid{0};
|
||||
std::optional<unsigned long> required_gid{};
|
||||
};
|
||||
|
||||
struct HelloInfo {
|
||||
std::string protocol_id{"void.ipc.v1"};
|
||||
std::uint32_t protocol_version{1};
|
||||
std::uint32_t capabilities{0};
|
||||
std::uint32_t max_frame_payload{1024u * 1024u};
|
||||
std::uint32_t max_inflight_requests{64u};
|
||||
std::uint32_t max_active_handlers{64u};
|
||||
};
|
||||
|
||||
struct SessionStats {
|
||||
std::uint64_t frames_sent{0};
|
||||
std::uint64_t frames_received{0};
|
||||
std::uint64_t requests_sent{0};
|
||||
std::uint64_t requests_received{0};
|
||||
std::uint64_t late_responses_dropped{0};
|
||||
std::uint64_t cancels_coalesced{0};
|
||||
std::size_t active_inflight{0};
|
||||
std::size_t active_handlers{0};
|
||||
std::size_t outbound_queued_bytes{0};
|
||||
std::size_t control_queued_frames{0};
|
||||
std::uint64_t next_request_id{1};
|
||||
};
|
||||
|
||||
} // namespace Void::IPC
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
@@ -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
@@ -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
|
||||
@@ -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
@@ -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
|
||||
+182
-2
@@ -4,13 +4,79 @@
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
enum class NetErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_url = 1,
|
||||
invalid_argument = 2,
|
||||
connect_failed = 3,
|
||||
tls_error = 4,
|
||||
protocol_error = 5,
|
||||
timeout = 6,
|
||||
cancelled = 7,
|
||||
quota_exceeded = 8,
|
||||
io_error = 9,
|
||||
redirect_blocked = 10,
|
||||
payload_too_large = 11,
|
||||
headers_too_large = 12
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_net_error(NetErrorCode code, std::string message = {},
|
||||
std::error_code sys_err = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case NetErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case NetErrorCode::invalid_url:
|
||||
case NetErrorCode::invalid_argument:
|
||||
case NetErrorCode::redirect_blocked:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case NetErrorCode::connect_failed:
|
||||
case NetErrorCode::io_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case NetErrorCode::tls_error:
|
||||
case NetErrorCode::protocol_error:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case NetErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case NetErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case NetErrorCode::quota_exceeded:
|
||||
case NetErrorCode::payload_too_large:
|
||||
case NetErrorCode::headers_too_large:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kNetErrorDomain,
|
||||
static_cast<std::int32_t>(code)},
|
||||
sys_err};
|
||||
}
|
||||
|
||||
enum class Method { Get, Post, Put, Delete, Patch, Head, Options };
|
||||
|
||||
@@ -62,6 +128,54 @@ namespace Void::Net
|
||||
}
|
||||
};
|
||||
|
||||
struct HttpClientOptions {
|
||||
ProxyConfig proxy{};
|
||||
std::string user_agent{"Void.Net/1.0"};
|
||||
bool verify_tls{true};
|
||||
std::string ca_file{};
|
||||
std::uint64_t max_body_size{64ULL * 1024 * 1024};
|
||||
int max_redirects{0};
|
||||
bool allow_insecure_redirects{false};
|
||||
};
|
||||
|
||||
struct TransferProgress {
|
||||
std::uint64_t bytes_transferred{0};
|
||||
std::optional<std::uint64_t> total_bytes{};
|
||||
};
|
||||
|
||||
struct DownloadOptions {
|
||||
std::vector<Header> headers{};
|
||||
std::chrono::seconds timeout{30};
|
||||
std::uint64_t max_bytes{0};
|
||||
std::stop_token stop{};
|
||||
std::function<void(std::span<const std::byte>)> on_chunk{};
|
||||
std::function<void(const TransferProgress&)> on_progress{};
|
||||
};
|
||||
|
||||
struct DownloadResult {
|
||||
std::uint16_t status{0};
|
||||
std::vector<Header> headers{};
|
||||
std::uint64_t bytes_written{0};
|
||||
std::chrono::milliseconds elapsed{0};
|
||||
|
||||
[[nodiscard]] bool ok() const noexcept
|
||||
{
|
||||
return status >= 200 && status < 300;
|
||||
}
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const;
|
||||
};
|
||||
|
||||
struct UploadOptions {
|
||||
Method method{Method::Put};
|
||||
std::vector<Header> headers{};
|
||||
std::string content_type{"application/octet-stream"};
|
||||
std::chrono::seconds timeout{30};
|
||||
std::uint64_t max_upload_bytes{0};
|
||||
std::stop_token stop{};
|
||||
std::function<void(const TransferProgress&)> on_progress{};
|
||||
};
|
||||
|
||||
/// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL.
|
||||
/// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS.
|
||||
/// Generic: no application-specific defaults beyond a configurable
|
||||
@@ -73,6 +187,12 @@ namespace Void::Net
|
||||
|
||||
HttpClient() = default;
|
||||
explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {}
|
||||
explicit HttpClient(HttpClientOptions options);
|
||||
|
||||
/// Preset with TLS peer & hostname certificate verification enabled
|
||||
/// by default (`verify_tls = true`).
|
||||
[[nodiscard]] static HttpClient
|
||||
secure(ProxyConfig proxy = {});
|
||||
|
||||
void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); }
|
||||
[[nodiscard]] const ProxyConfig& proxy() const noexcept
|
||||
@@ -83,9 +203,33 @@ namespace Void::Net
|
||||
/// Default User-Agent applied when a request sets none.
|
||||
void set_user_agent(std::string ua) { m_user_agent = std::move(ua); }
|
||||
|
||||
/// Verify TLS peer certificates (default: false, matching common
|
||||
/// scraping/proxy use; enable for security-sensitive callers).
|
||||
/// Verify TLS peer certificates (default constructor keeps `false`
|
||||
/// for 1.x compatibility; `HttpClient::secure()` defaults `true`).
|
||||
void set_verify_tls(bool on) noexcept { m_verify_tls = on; }
|
||||
[[nodiscard]] bool verify_tls() const noexcept
|
||||
{
|
||||
return m_verify_tls;
|
||||
}
|
||||
|
||||
/// Optional custom PEM CA bundle/certificate file used when
|
||||
/// `verify_tls` is enabled.
|
||||
void set_ca_file(std::string ca_file)
|
||||
{
|
||||
m_ca_file = std::move(ca_file);
|
||||
}
|
||||
[[nodiscard]] const std::string& ca_file() const noexcept
|
||||
{
|
||||
return m_ca_file;
|
||||
}
|
||||
|
||||
void set_allow_insecure_redirects(bool allow) noexcept
|
||||
{
|
||||
m_allow_insecure_redirects = allow;
|
||||
}
|
||||
[[nodiscard]] bool allow_insecure_redirects() const noexcept
|
||||
{
|
||||
return m_allow_insecure_redirects;
|
||||
}
|
||||
|
||||
/// Maximum response body size in bytes. 0 means unlimited. Default
|
||||
/// is 64 MiB (Beast's own default of ~1 MiB is too small for binary
|
||||
@@ -100,12 +244,34 @@ namespace Void::Net
|
||||
/// header). Opt-in so callers that inspect redirects keep working.
|
||||
void set_max_redirects(int n) noexcept { m_max_redirects = n; }
|
||||
|
||||
/// Format request method, scrubbed URL, and headers for logs while
|
||||
/// redacting `Authorization`, `Proxy-Authorization`, `Cookie`, and
|
||||
/// `X-Api-Key`.
|
||||
[[nodiscard]] static std::string
|
||||
format_request_diagnostics(const Request& req);
|
||||
|
||||
/// Execute a request. A per-request `Request::proxy` is not modelled;
|
||||
/// the client-level proxy applies. Returns an Error only on transport
|
||||
/// failure — a non-2xx HTTP response is a successful Result.
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
send(const Request& req) const;
|
||||
|
||||
/// Stream response body directly to `destination` without buffering
|
||||
/// the full payload in memory, enforcing `options.max_bytes` and
|
||||
/// `options.stop` cancellation.
|
||||
[[nodiscard]] Void::Result::Result<DownloadResult,
|
||||
Void::Result::Error>
|
||||
download_to_file(std::string_view url,
|
||||
const std::filesystem::path& destination,
|
||||
const DownloadOptions& options = {}) const;
|
||||
|
||||
/// Stream a regular file directly as the HTTP request body without
|
||||
/// buffering the full file in memory.
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
upload_file(std::string_view url,
|
||||
const std::filesystem::path& source_path,
|
||||
const UploadOptions& options = {}) const;
|
||||
|
||||
// Convenience wrappers.
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
get(std::string_view url,
|
||||
@@ -113,14 +279,28 @@ namespace Void::Net
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
post(std::string_view url, std::string body,
|
||||
std::vector<Header> headers = {}) const;
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
put_file(std::string_view url,
|
||||
const std::filesystem::path& source_path,
|
||||
std::vector<Header> headers = {},
|
||||
std::string content_type =
|
||||
"application/octet-stream") const;
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
post_file(std::string_view url,
|
||||
const std::filesystem::path& source_path,
|
||||
std::vector<Header> headers = {},
|
||||
std::string content_type =
|
||||
"application/octet-stream") const;
|
||||
|
||||
private:
|
||||
|
||||
ProxyConfig m_proxy{};
|
||||
std::string m_user_agent = "Void.Net/1.0";
|
||||
bool m_verify_tls = false;
|
||||
std::string m_ca_file{};
|
||||
std::uint64_t m_max_body = 64ull * 1024 * 1024;
|
||||
int m_max_redirects = 0;
|
||||
bool m_allow_insecure_redirects = false;
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,172 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
struct HttpCodecLimits {
|
||||
std::size_t max_start_line_bytes{8ULL * 1024};
|
||||
std::size_t max_header_bytes{32ULL * 1024};
|
||||
std::size_t max_headers{100};
|
||||
std::uint64_t max_body_bytes{8ULL * 1024 * 1024};
|
||||
std::size_t max_chunk_line_bytes{1024};
|
||||
std::size_t max_trailer_bytes{8ULL * 1024};
|
||||
std::size_t max_informational_responses{8};
|
||||
};
|
||||
|
||||
enum class HttpParseStatus : std::uint8_t {
|
||||
NeedMoreData,
|
||||
Complete,
|
||||
};
|
||||
|
||||
struct ParsedHttpRequest {
|
||||
Method method{Method::Get};
|
||||
std::string target{};
|
||||
std::uint8_t version_major{1};
|
||||
std::uint8_t version_minor{1};
|
||||
std::vector<Header> headers{};
|
||||
std::string body{};
|
||||
std::vector<Header> trailers{};
|
||||
bool keep_alive{true};
|
||||
bool chunked{false};
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const noexcept;
|
||||
};
|
||||
|
||||
struct ParsedHttpResponse {
|
||||
std::uint16_t status{200};
|
||||
std::string reason{};
|
||||
std::uint8_t version_major{1};
|
||||
std::uint8_t version_minor{1};
|
||||
std::vector<Header> headers{};
|
||||
std::string body{};
|
||||
std::vector<Header> trailers{};
|
||||
std::vector<std::uint16_t> informational_statuses{};
|
||||
bool keep_alive{true};
|
||||
bool chunked{false};
|
||||
bool close_delimited{false};
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const noexcept;
|
||||
};
|
||||
|
||||
/// Native incremental RFC 9110/9112 HTTP/1.1 request parser.
|
||||
/// Enforces strict CRLF framing, header/body limits, and rejects
|
||||
/// Transfer-Encoding + Content-Length smuggling ambiguity and conflicting
|
||||
/// Content-Length values.
|
||||
class HttpRequestParser
|
||||
{
|
||||
public:
|
||||
|
||||
explicit HttpRequestParser(HttpCodecLimits limits = {}) noexcept;
|
||||
|
||||
void reset() noexcept;
|
||||
|
||||
/// Feed arbitrary byte chunks. Returns Complete once a full message
|
||||
/// has been parsed; `consumed` reports bytes consumed from `input`.
|
||||
[[nodiscard]] Void::Result::Result<HttpParseStatus>
|
||||
feed(std::span<const std::byte> input, std::size_t& consumed);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<HttpParseStatus>
|
||||
feed(std::string_view input, std::size_t& consumed);
|
||||
|
||||
[[nodiscard]] bool complete() const noexcept;
|
||||
[[nodiscard]] bool connection_reusable() const noexcept;
|
||||
[[nodiscard]] const ParsedHttpRequest& request() const noexcept;
|
||||
[[nodiscard]] ParsedHttpRequest take_request();
|
||||
|
||||
private:
|
||||
|
||||
enum class Phase : std::uint8_t {
|
||||
Headers,
|
||||
FixedBody,
|
||||
ChunkSize,
|
||||
ChunkData,
|
||||
ChunkDataCrlf,
|
||||
Trailers,
|
||||
Complete,
|
||||
Failed,
|
||||
};
|
||||
|
||||
HttpCodecLimits m_limits{};
|
||||
Phase m_phase{Phase::Headers};
|
||||
std::string m_buf{};
|
||||
std::size_t m_header_bytes_seen{0};
|
||||
std::size_t m_trailer_bytes_seen{0};
|
||||
std::uint64_t m_remaining{0};
|
||||
std::uint64_t m_body_received{0};
|
||||
ParsedHttpRequest m_req{};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> parse_header_block(
|
||||
std::string_view block);
|
||||
};
|
||||
|
||||
/// Native incremental RFC 9110/9112 HTTP/1.1 response parser.
|
||||
/// Supports 1xx informational responses, HEAD/204/304 no-body responses,
|
||||
/// fixed Content-Length, chunked transfer encoding with extensions and
|
||||
/// trailers, and close-delimited bodies (completed via `finish_eof()`).
|
||||
class HttpResponseParser
|
||||
{
|
||||
public:
|
||||
|
||||
explicit HttpResponseParser(
|
||||
HttpCodecLimits limits = {},
|
||||
Method request_method = Method::Get) noexcept;
|
||||
|
||||
void reset(Method request_method = Method::Get) noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<HttpParseStatus>
|
||||
feed(std::span<const std::byte> input, std::size_t& consumed);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<HttpParseStatus>
|
||||
feed(std::string_view input, std::size_t& consumed);
|
||||
|
||||
/// Signal peer EOF. Completes close-delimited responses cleanly;
|
||||
/// errors on truncated fixed-length, chunked, or header frames.
|
||||
[[nodiscard]] Void::Result::Result<void> finish_eof();
|
||||
|
||||
[[nodiscard]] bool complete() const noexcept;
|
||||
[[nodiscard]] bool connection_reusable() const noexcept;
|
||||
[[nodiscard]] const ParsedHttpResponse& response() const noexcept;
|
||||
[[nodiscard]] ParsedHttpResponse take_response();
|
||||
|
||||
private:
|
||||
|
||||
enum class Phase : std::uint8_t {
|
||||
Headers,
|
||||
FixedBody,
|
||||
ChunkSize,
|
||||
ChunkData,
|
||||
ChunkDataCrlf,
|
||||
Trailers,
|
||||
CloseDelimitedBody,
|
||||
Complete,
|
||||
Failed,
|
||||
};
|
||||
|
||||
HttpCodecLimits m_limits{};
|
||||
Method m_request_method{Method::Get};
|
||||
Phase m_phase{Phase::Headers};
|
||||
std::string m_buf{};
|
||||
std::size_t m_header_bytes_seen{0};
|
||||
std::size_t m_trailer_bytes_seen{0};
|
||||
std::uint64_t m_remaining{0};
|
||||
std::uint64_t m_body_received{0};
|
||||
ParsedHttpResponse m_resp{};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<bool> parse_header_block(
|
||||
std::string_view block);
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/Server.hpp>
|
||||
#include <Void/Net/WebSocket.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
struct HttpServerOptions {
|
||||
std::string bind_host{"127.0.0.1"};
|
||||
std::uint16_t port{0};
|
||||
std::size_t max_header_bytes{64ULL * 1024};
|
||||
std::size_t max_headers{128};
|
||||
std::uint64_t max_body_bytes{16ULL * 1024 * 1024};
|
||||
std::uint64_t max_streaming_body_bytes{512ULL * 1024 * 1024};
|
||||
std::size_t max_concurrent_connections{64};
|
||||
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
|
||||
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
|
||||
int listen_backlog{128};
|
||||
};
|
||||
|
||||
/// Streaming request body reader passed to streaming HTTP route handlers.
|
||||
class BodyReader
|
||||
{
|
||||
public:
|
||||
|
||||
struct State;
|
||||
|
||||
explicit BodyReader(State& state) noexcept : m_state(&state) {}
|
||||
BodyReader(const BodyReader&) = delete;
|
||||
BodyReader& operator=(const BodyReader&) = delete;
|
||||
|
||||
[[nodiscard]] std::optional<std::uint64_t>
|
||||
content_length() const noexcept;
|
||||
[[nodiscard]] bool is_chunked() const noexcept;
|
||||
[[nodiscard]] std::uint64_t bytes_read() const noexcept;
|
||||
|
||||
/// Read up to dst.size() decoded body bytes. Returns 0 at EOF.
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
read_some(std::span<std::byte> dst);
|
||||
|
||||
/// Stream the request body atomically to `destination`, enforcing
|
||||
/// `max_bytes` (or server max_streaming_body_bytes when 0).
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
read_to_file(const std::filesystem::path& destination,
|
||||
std::uint64_t max_bytes = 0);
|
||||
|
||||
private:
|
||||
|
||||
State* m_state{nullptr};
|
||||
};
|
||||
|
||||
using StreamingRouteHandler =
|
||||
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
|
||||
|
||||
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
|
||||
/// `Void::Net::Router` and streaming routes via `BodyReader`.
|
||||
class HttpServer
|
||||
{
|
||||
public:
|
||||
|
||||
explicit HttpServer(HttpServerOptions options = {});
|
||||
explicit HttpServer(Router& external_router,
|
||||
HttpServerOptions options = {});
|
||||
~HttpServer() noexcept;
|
||||
|
||||
HttpServer(HttpServer&&) noexcept;
|
||||
HttpServer& operator=(HttpServer&&) noexcept;
|
||||
HttpServer(const HttpServer&) = delete;
|
||||
HttpServer& operator=(const HttpServer&) = delete;
|
||||
|
||||
[[nodiscard]] Router& router() noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
add_route(Method method, std::string pattern,
|
||||
RouteHandler handler);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
add_streaming_route(Method method, std::string pattern,
|
||||
StreamingRouteHandler handler);
|
||||
|
||||
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
|
||||
/// `sessions` (caller must keep `sessions` alive until after
|
||||
/// `shutdown()`).
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
add_websocket_route(std::string pattern,
|
||||
WebSocketSessions& sessions,
|
||||
WebSocketUpgradeOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
|
||||
void shutdown(std::chrono::milliseconds drain_timeout =
|
||||
std::chrono::seconds{5}) noexcept;
|
||||
|
||||
[[nodiscard]] bool running() const noexcept;
|
||||
[[nodiscard]] std::uint16_t bound_port() const noexcept;
|
||||
[[nodiscard]] std::string bind_address() const;
|
||||
[[nodiscard]] std::string base_url() const;
|
||||
|
||||
private:
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> m_impl;
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,142 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
struct PoolLimits {
|
||||
std::size_t max_total_connections{256};
|
||||
std::size_t max_per_origin{8};
|
||||
std::size_t max_idle_connections{128};
|
||||
std::chrono::milliseconds idle_timeout{std::chrono::seconds{30}};
|
||||
};
|
||||
|
||||
/// Pool partition key isolating origins, proxy identity, and TLS/trust
|
||||
/// policy generations so connections never cross trust boundaries.
|
||||
struct PoolKey {
|
||||
std::string scheme{};
|
||||
std::string host{};
|
||||
std::uint16_t port{0};
|
||||
std::string proxy_identity{};
|
||||
std::uint64_t tls_policy_generation{0};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const PoolKey&) const noexcept = default;
|
||||
};
|
||||
|
||||
/// Abstract pooled transport entry owned by ConnectionPool / leases.
|
||||
class PooledConnection
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~PooledConnection() = default;
|
||||
[[nodiscard]] virtual bool is_open() const noexcept = 0;
|
||||
virtual void close() noexcept = 0;
|
||||
};
|
||||
|
||||
using ConnectionFactory =
|
||||
std::function<Void::Result::Result<std::unique_ptr<PooledConnection>>(
|
||||
const PoolKey&)>;
|
||||
|
||||
struct PoolStats {
|
||||
std::size_t total_connections{0};
|
||||
std::size_t active_leases{0};
|
||||
std::size_t idle_connections{0};
|
||||
std::uint64_t total_acquires{0};
|
||||
std::uint64_t idle_hits{0};
|
||||
std::uint64_t idle_evictions{0};
|
||||
std::uint64_t closed_dirty{0};
|
||||
};
|
||||
|
||||
class ConnectionPool;
|
||||
|
||||
/// Move-only RAII lease for one HTTP/1.1 exchange. Only leases explicitly
|
||||
/// marked reusable via `mark_reusable(true)` (after full body+trailers)
|
||||
/// return to the idle pool on destruction; unmarked or dirty leases close.
|
||||
class ConnectionLease final
|
||||
{
|
||||
public:
|
||||
|
||||
ConnectionLease() noexcept = default;
|
||||
~ConnectionLease() noexcept;
|
||||
|
||||
ConnectionLease(ConnectionLease&& other) noexcept;
|
||||
ConnectionLease& operator=(ConnectionLease&& other) noexcept;
|
||||
ConnectionLease(const ConnectionLease&) = delete;
|
||||
ConnectionLease& operator=(const ConnectionLease&) = delete;
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept;
|
||||
[[nodiscard]] bool reused() const noexcept;
|
||||
[[nodiscard]] const PoolKey& key() const noexcept;
|
||||
[[nodiscard]] PooledConnection* get() const noexcept;
|
||||
[[nodiscard]] PooledConnection& operator*() const noexcept;
|
||||
[[nodiscard]] PooledConnection* operator->() const noexcept;
|
||||
|
||||
void mark_reusable(bool reusable = true) noexcept;
|
||||
void release() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class ConnectionPool;
|
||||
|
||||
struct Impl;
|
||||
std::shared_ptr<void> m_pool_state{};
|
||||
PoolKey m_key{};
|
||||
std::unique_ptr<PooledConnection> m_conn{};
|
||||
bool m_reused{false};
|
||||
bool m_reusable{false};
|
||||
bool m_active{false};
|
||||
};
|
||||
|
||||
/// Bounded HTTP/1.1 connection pool keyed by origin, proxy identity, and
|
||||
/// TLS policy generation, with deterministic clock-driven idle eviction.
|
||||
class ConnectionPool final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ConnectionPool(
|
||||
PoolLimits limits = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
~ConnectionPool() noexcept;
|
||||
|
||||
ConnectionPool(ConnectionPool&&) noexcept;
|
||||
ConnectionPool& operator=(ConnectionPool&&) noexcept;
|
||||
ConnectionPool(const ConnectionPool&) = delete;
|
||||
ConnectionPool& operator=(const ConnectionPool&) = delete;
|
||||
|
||||
/// Acquire an idle connection for `key` or invoke `factory(key)`
|
||||
/// outside pool locks while enforcing total and per-origin limits.
|
||||
[[nodiscard]] Void::Result::Result<ConnectionLease>
|
||||
acquire(const PoolKey& key, const ConnectionFactory& factory);
|
||||
|
||||
/// Evict all idle connections older than `idle_timeout` or closed.
|
||||
std::size_t evict_expired();
|
||||
|
||||
/// Close all idle connections (e.g. on trust-store rotation).
|
||||
std::size_t clear_idle();
|
||||
|
||||
/// Prevent new leases and close all currently idle connections.
|
||||
void shutdown() noexcept;
|
||||
|
||||
[[nodiscard]] PoolStats stats() const;
|
||||
|
||||
private:
|
||||
|
||||
friend class ConnectionLease;
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -30,6 +30,7 @@ namespace Void::Net
|
||||
std::vector<Header> headers;
|
||||
std::string body;
|
||||
RouteParameters parameters;
|
||||
std::string query{};
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const noexcept;
|
||||
@@ -39,6 +40,12 @@ namespace Void::Net
|
||||
std::uint16_t status{200};
|
||||
std::vector<Header> headers;
|
||||
std::string body;
|
||||
std::optional<std::filesystem::path> file_body{};
|
||||
|
||||
[[nodiscard]] static ServerResponse
|
||||
from_file(std::filesystem::path path,
|
||||
std::string content_type = {},
|
||||
std::uint16_t status = 200);
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const noexcept;
|
||||
@@ -67,6 +74,9 @@ namespace Void::Net
|
||||
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
|
||||
dispatch(ServerRequest request) const;
|
||||
|
||||
[[nodiscard]] std::vector<Method>
|
||||
allowed_methods(std::string_view path) const;
|
||||
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
|
||||
private:
|
||||
@@ -88,6 +98,49 @@ namespace Void::Net
|
||||
std::uintmax_t size{};
|
||||
};
|
||||
|
||||
/// Move-only RAII handle for a regular file opened beneath a pinned root
|
||||
/// directory descriptor using `openat(..., O_NOFOLLOW)` (zero TOCTOU).
|
||||
class OpenedStaticFile final
|
||||
{
|
||||
public:
|
||||
|
||||
OpenedStaticFile() noexcept = default;
|
||||
OpenedStaticFile(int fd, std::filesystem::path relative_path,
|
||||
std::string_view content_type,
|
||||
std::uint64_t size) noexcept;
|
||||
~OpenedStaticFile() noexcept;
|
||||
|
||||
OpenedStaticFile(OpenedStaticFile&& other) noexcept;
|
||||
OpenedStaticFile& operator=(OpenedStaticFile&& other) noexcept;
|
||||
OpenedStaticFile(const OpenedStaticFile&) = delete;
|
||||
OpenedStaticFile& operator=(const OpenedStaticFile&) = delete;
|
||||
|
||||
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
|
||||
[[nodiscard]] int native_handle() const noexcept { return fd_; }
|
||||
[[nodiscard]] const std::filesystem::path&
|
||||
relative_path() const noexcept
|
||||
{
|
||||
return relative_path_;
|
||||
}
|
||||
[[nodiscard]] std::string_view content_type() const noexcept
|
||||
{
|
||||
return content_type_;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t size() const noexcept { return size_; }
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
read_all(std::uint64_t max_bytes = 64ULL * 1024 * 1024) const;
|
||||
|
||||
void close() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
int fd_{-1};
|
||||
std::filesystem::path relative_path_{};
|
||||
std::string_view content_type_{};
|
||||
std::uint64_t size_{0};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
content_type_for(const std::filesystem::path& path);
|
||||
|
||||
@@ -105,6 +158,12 @@ namespace Void::Net
|
||||
[[nodiscard]] Void::Result::Result<std::optional<StaticFile>>
|
||||
resolve(std::string_view request_path) const;
|
||||
|
||||
/// Descriptor-pinned open beneath the retained root directory
|
||||
/// descriptor (`openat` + `O_NOFOLLOW` per component). Rejects
|
||||
/// symlinks, traversal, and non-regular files without TOCTOU races.
|
||||
[[nodiscard]] Void::Result::Result<std::optional<OpenedStaticFile>>
|
||||
open_safe(std::string_view request_path) const;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& root() const noexcept
|
||||
{
|
||||
return root_;
|
||||
@@ -112,14 +171,25 @@ namespace Void::Net
|
||||
|
||||
private:
|
||||
|
||||
struct DirHandle {
|
||||
int fd{-1};
|
||||
explicit DirHandle(int d) noexcept : fd(d) {}
|
||||
~DirHandle() noexcept;
|
||||
DirHandle(const DirHandle&) = delete;
|
||||
DirHandle& operator=(const DirHandle&) = delete;
|
||||
};
|
||||
|
||||
StaticFileResolver(std::filesystem::path root,
|
||||
std::string index_file)
|
||||
: root_(std::move(root)), index_file_(std::move(index_file))
|
||||
std::string index_file,
|
||||
std::shared_ptr<DirHandle> root_dir)
|
||||
: root_(std::move(root)), index_file_(std::move(index_file)),
|
||||
root_dir_(std::move(root_dir))
|
||||
{
|
||||
}
|
||||
|
||||
std::filesystem::path root_;
|
||||
std::string index_file_;
|
||||
std::shared_ptr<DirHandle> root_dir_;
|
||||
};
|
||||
|
||||
struct WebSocketConnectionId {
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/Server.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
enum class WebSocketOpcode : std::uint8_t {
|
||||
Continuation = 0x0,
|
||||
Text = 0x1,
|
||||
Binary = 0x2,
|
||||
Close = 0x8,
|
||||
Ping = 0x9,
|
||||
Pong = 0xA,
|
||||
};
|
||||
|
||||
struct WebSocketLimits {
|
||||
std::size_t max_message_bytes{1024ULL * 1024};
|
||||
std::size_t max_output_messages{64};
|
||||
std::size_t max_output_bytes{4ULL * 1024 * 1024};
|
||||
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
|
||||
};
|
||||
|
||||
struct WebSocketUpgradeOptions {
|
||||
std::vector<std::string> allowed_origins{};
|
||||
std::vector<std::string> supported_subprotocols{};
|
||||
WebSocketLimits limits{};
|
||||
};
|
||||
|
||||
struct WebSocketUpgradeHandshake {
|
||||
std::string accept_key{};
|
||||
std::optional<std::string> selected_subprotocol{};
|
||||
};
|
||||
|
||||
struct WebSocketFrame {
|
||||
bool fin{true};
|
||||
WebSocketOpcode opcode{WebSocketOpcode::Text};
|
||||
bool masked{false};
|
||||
std::array<std::byte, 4> mask_key{};
|
||||
std::vector<std::byte> payload{};
|
||||
};
|
||||
|
||||
struct WebSocketMessage {
|
||||
WebSocketOpcode opcode{WebSocketOpcode::Text};
|
||||
std::vector<std::byte> payload{};
|
||||
std::optional<WebSocketClose> close_info{};
|
||||
|
||||
[[nodiscard]] std::string_view text_view() const noexcept
|
||||
{
|
||||
return std::string_view{
|
||||
reinterpret_cast<const char*>(payload.data()),
|
||||
payload.size()};
|
||||
}
|
||||
};
|
||||
|
||||
/// Compute RFC 6455 Sec-WebSocket-Accept = Base64(SHA1(key + GUID)).
|
||||
[[nodiscard]] std::string compute_websocket_accept(std::string_view key);
|
||||
|
||||
/// Validate strict RFC 3629 UTF-8 byte sequences (required for text frames
|
||||
/// and close reasons by RFC 6455 section 5.6 / 8.1).
|
||||
[[nodiscard]] bool is_valid_utf8(std::span<const std::byte> data) noexcept;
|
||||
[[nodiscard]] bool is_valid_utf8(std::string_view data) noexcept;
|
||||
|
||||
/// Validate a client HTTP/1.1 Upgrade request per RFC 6455 section 4.2.1.
|
||||
[[nodiscard]] Void::Result::Result<WebSocketUpgradeHandshake>
|
||||
validate_websocket_upgrade_request(
|
||||
const ServerRequest& request,
|
||||
const WebSocketUpgradeOptions& options = {});
|
||||
|
||||
/// Encode a single RFC 6455 frame. When `masked == true`, applies
|
||||
/// `mask_key` XOR masking to payload bytes.
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
|
||||
encode_websocket_frame(const WebSocketFrame& frame);
|
||||
|
||||
/// Encode a RFC 6455 Close control frame (2-byte big-endian code + UTF-8
|
||||
/// reason <= 123 bytes).
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
|
||||
encode_websocket_close_frame(const WebSocketClose& close, bool masked,
|
||||
std::array<std::byte, 4> mask_key = {});
|
||||
|
||||
/// Incremental RFC 6455 frame decoder & fragmented message assembler.
|
||||
/// `expect_masked_incoming = true` for server side, `false` for client.
|
||||
class WebSocketDecoder final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit WebSocketDecoder(bool expect_masked_incoming,
|
||||
WebSocketLimits limits = {}) noexcept;
|
||||
|
||||
void reset() noexcept;
|
||||
|
||||
/// Feed arbitrary bytes and append any completed data or control
|
||||
/// messages (Text, Binary, Ping, Pong, Close) to `out_messages`.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
feed(std::span<const std::byte> input,
|
||||
std::vector<WebSocketMessage>& out_messages);
|
||||
|
||||
[[nodiscard]] bool close_received() const noexcept
|
||||
{
|
||||
return m_close_received;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
bool m_expect_masked{true};
|
||||
WebSocketLimits m_limits{};
|
||||
std::vector<std::byte> m_buf{};
|
||||
bool m_in_fragment{false};
|
||||
WebSocketOpcode m_fragment_opcode{WebSocketOpcode::Text};
|
||||
std::vector<std::byte> m_fragment_payload{};
|
||||
bool m_close_received{false};
|
||||
};
|
||||
|
||||
struct WebSocketConnectOptions {
|
||||
std::vector<Header> extra_headers{};
|
||||
std::optional<std::string> subprotocol{};
|
||||
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
|
||||
WebSocketLimits limits{};
|
||||
};
|
||||
|
||||
/// Synchronous RFC 6455 WebSocket client over loopback/TCP HTTP/1.1 Upgrade
|
||||
/// (for direct ws:// endpoints and independent conformance testing).
|
||||
class WebSocketClient final
|
||||
{
|
||||
public:
|
||||
|
||||
using ConnectOptions = WebSocketConnectOptions;
|
||||
|
||||
WebSocketClient() noexcept = default;
|
||||
~WebSocketClient() noexcept;
|
||||
|
||||
WebSocketClient(WebSocketClient&&) noexcept;
|
||||
WebSocketClient& operator=(WebSocketClient&&) noexcept;
|
||||
WebSocketClient(const WebSocketClient&) = delete;
|
||||
WebSocketClient& operator=(const WebSocketClient&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<WebSocketClient>
|
||||
connect(std::string_view ws_url,
|
||||
const ConnectOptions& options = ConnectOptions{});
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept;
|
||||
[[nodiscard]] const std::optional<std::string>&
|
||||
selected_subprotocol() const noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_text(std::string_view text);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_binary(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_ping(std::span<const std::byte> payload = {});
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_pong(std::span<const std::byte> payload = {});
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_fragmented_text(std::span<const std::string_view> chunks);
|
||||
|
||||
/// Receive the next decoded WebSocket message (auto-answering Ping
|
||||
/// when `auto_pong == true` unless callers want to inspect Ping).
|
||||
[[nodiscard]] Void::Result::Result<WebSocketMessage>
|
||||
receive(std::chrono::milliseconds timeout =
|
||||
std::chrono::seconds{5});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
close(WebSocketClose close_info = {1000, ""});
|
||||
|
||||
private:
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> m_impl;
|
||||
explicit WebSocketClient(std::unique_ptr<Impl> impl) noexcept;
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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
|
||||
@@ -0,0 +1,184 @@
|
||||
#ifndef VOID_PLUGIN_CABI_H
|
||||
#define VOID_PLUGIN_CABI_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define VOID_CABI_MAJOR_V1 UINT32_C(1)
|
||||
#define VOID_CABI_MINOR_V1 UINT32_C(0)
|
||||
#define VOID_MODULE_QUERY_SYMBOL_V1 "void_module_query_v1"
|
||||
|
||||
#define VOID_CAP_STATELESS_RELOAD (UINT64_C(1) << 0)
|
||||
#define VOID_CAP_STATEFUL_CHECKPOINT (UINT64_C(1) << 1)
|
||||
#define VOID_CAP_ASYNC_OPS (UINT64_C(1) << 2)
|
||||
#define VOID_CAP_SERVICE_INTERFACES (UINT64_C(1) << 3)
|
||||
|
||||
enum void_status_v1 {
|
||||
VOID_STATUS_OK = 0,
|
||||
VOID_STATUS_INVALID_ARGUMENT = 1,
|
||||
VOID_STATUS_NOT_FOUND = 2,
|
||||
VOID_STATUS_CONFLICT = 3,
|
||||
VOID_STATUS_CANCELLED = 4,
|
||||
VOID_STATUS_TIMEOUT = 5,
|
||||
VOID_STATUS_OVERLOADED = 6,
|
||||
VOID_STATUS_UNSUPPORTED = 7,
|
||||
VOID_STATUS_CORRUPT = 8,
|
||||
VOID_STATUS_EXHAUSTED = 9,
|
||||
VOID_STATUS_INTERNAL = 10,
|
||||
VOID_STATUS_NOT_READY = 11,
|
||||
VOID_STATUS_QUIESCING = 12,
|
||||
VOID_STATUS_STATE_REJECTED = 13,
|
||||
VOID_STATUS_RESTART_REQUIRED = 14
|
||||
};
|
||||
|
||||
enum void_activation_policy_v1 {
|
||||
VOID_POLICY_RELOADABLE = 0,
|
||||
VOID_POLICY_RESTART_REQUIRED = 1,
|
||||
VOID_POLICY_INSTALLER_REQUIRED = 2
|
||||
};
|
||||
|
||||
typedef struct void_module_handle void_module_handle;
|
||||
typedef struct void_operation_handle void_operation_handle;
|
||||
typedef struct void_host_context void_host_context;
|
||||
|
||||
typedef struct void_bytes_v1 {
|
||||
const uint8_t* data;
|
||||
uint64_t size;
|
||||
} void_bytes_v1;
|
||||
|
||||
typedef struct void_owned_bytes_v1 {
|
||||
const uint8_t* data;
|
||||
uint64_t size;
|
||||
void (*release)(void* release_ctx, const uint8_t* data, uint64_t size);
|
||||
void* release_ctx;
|
||||
} void_owned_bytes_v1;
|
||||
|
||||
typedef struct void_interface_id_v1 {
|
||||
uint8_t bytes[16];
|
||||
} void_interface_id_v1;
|
||||
|
||||
typedef struct void_dependency_v1 {
|
||||
const char* module_id;
|
||||
const char* version_range;
|
||||
uint8_t optional_dep;
|
||||
uint8_t reserved[7];
|
||||
} void_dependency_v1;
|
||||
|
||||
typedef struct void_module_info_v1 {
|
||||
uint32_t struct_size;
|
||||
uint32_t reserved;
|
||||
const char* module_id;
|
||||
const char* version;
|
||||
uint32_t activation_policy;
|
||||
uint32_t state_schema_version;
|
||||
const void_dependency_v1* dependencies;
|
||||
uint64_t dependency_count;
|
||||
} void_module_info_v1;
|
||||
|
||||
typedef struct void_op_options_v1 {
|
||||
uint32_t struct_size;
|
||||
uint32_t flags;
|
||||
uint64_t deadline_ns;
|
||||
uint8_t stop_requested;
|
||||
uint8_t reserved[7];
|
||||
} void_op_options_v1;
|
||||
|
||||
typedef struct void_error_detail_v1 {
|
||||
uint32_t struct_size;
|
||||
int32_t status;
|
||||
const char* message;
|
||||
void (*release)(void* release_ctx, const char* message);
|
||||
void* release_ctx;
|
||||
} void_error_detail_v1;
|
||||
|
||||
typedef struct void_interface_view_v1 {
|
||||
uint32_t struct_size;
|
||||
uint32_t major;
|
||||
uint32_t minor;
|
||||
uint32_t table_size;
|
||||
const void* function_table;
|
||||
} void_interface_view_v1;
|
||||
|
||||
typedef struct void_host_api_v1 {
|
||||
uint32_t struct_size;
|
||||
uint32_t abi_major;
|
||||
uint32_t abi_minor;
|
||||
uint32_t reserved;
|
||||
void_host_context* host_ctx;
|
||||
uint64_t generation;
|
||||
uint64_t (*monotonic_now_ns)(void_host_context* ctx);
|
||||
int32_t (*acquire_activity_pin)(void_host_context* ctx, uint64_t generation);
|
||||
void (*release_activity_pin)(void_host_context* ctx, uint64_t generation);
|
||||
void (*log_message)(void_host_context* ctx, int32_t level, const char* msg);
|
||||
} void_host_api_v1;
|
||||
|
||||
typedef void (*void_async_complete_fn)(void* user_ctx,
|
||||
int32_t status,
|
||||
const void_bytes_v1* result_bytes);
|
||||
|
||||
typedef struct void_module_api_v1 {
|
||||
uint32_t struct_size;
|
||||
uint32_t abi_major;
|
||||
uint32_t abi_minor;
|
||||
uint32_t reserved;
|
||||
uint64_t capabilities;
|
||||
|
||||
int32_t (*get_info)(void_module_info_v1* out_info);
|
||||
int32_t (*create)(const void_host_api_v1* host_api,
|
||||
void_module_handle** out_handle);
|
||||
int32_t (*activate)(void_module_handle* handle,
|
||||
void_bytes_v1 config,
|
||||
void_error_detail_v1* out_err);
|
||||
int32_t (*readiness)(void_module_handle* handle,
|
||||
uint32_t* out_ready,
|
||||
void_error_detail_v1* out_err);
|
||||
int32_t (*quiesce)(void_module_handle* handle,
|
||||
const void_op_options_v1* opts,
|
||||
void_error_detail_v1* out_err);
|
||||
int32_t (*resume)(void_module_handle* handle, void_error_detail_v1* out_err);
|
||||
int32_t (*checkpoint)(void_module_handle* handle,
|
||||
const void_op_options_v1* opts,
|
||||
void_owned_bytes_v1* out_state,
|
||||
void_error_detail_v1* out_err);
|
||||
int32_t (*restore)(void_module_handle* handle,
|
||||
void_bytes_v1 state,
|
||||
void_error_detail_v1* out_err);
|
||||
int32_t (*query_interface)(void_module_handle* handle,
|
||||
const void_interface_id_v1* iface_id,
|
||||
uint32_t min_major,
|
||||
uint32_t min_table_size,
|
||||
void_interface_view_v1* out_view);
|
||||
void (*release_interface)(void_module_handle* handle,
|
||||
const void_interface_id_v1* iface_id,
|
||||
const void_interface_view_v1* view);
|
||||
int32_t (*submit_async)(void_module_handle* handle,
|
||||
uint32_t op_kind,
|
||||
void_bytes_v1 payload,
|
||||
const void_op_options_v1* opts,
|
||||
void_async_complete_fn cb,
|
||||
void* cb_ctx,
|
||||
void_operation_handle** out_op,
|
||||
void_error_detail_v1* out_err);
|
||||
int32_t (*cancel_async)(void_module_handle* handle,
|
||||
void_operation_handle* op);
|
||||
void (*release_async)(void_module_handle* handle,
|
||||
void_operation_handle* op);
|
||||
int32_t (*request_stop)(void_module_handle* handle);
|
||||
int32_t (*deactivate)(void_module_handle* handle);
|
||||
void (*destroy)(void_module_handle* handle);
|
||||
} void_module_api_v1;
|
||||
|
||||
#define VOID_MODULE_API_V1_MIN_SIZE sizeof(void_module_api_v1)
|
||||
|
||||
typedef int32_t (*void_module_query_v1_fn)(uint32_t host_struct_size,
|
||||
void_module_api_v1* out_api);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* VOID_PLUGIN_CABI_H */
|
||||
@@ -0,0 +1,165 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Plugin/CAbi.h>
|
||||
#include <Void/Plugin/Module.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Plugin
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
inline void free_cabi_cstring(void* /*ctx*/, const char* msg)
|
||||
{
|
||||
delete[] msg;
|
||||
}
|
||||
|
||||
inline void set_error_detail(void_error_detail_v1* out_err,
|
||||
std::int32_t status,
|
||||
const std::string& msg) noexcept
|
||||
{
|
||||
if (out_err == nullptr ||
|
||||
out_err->struct_size < sizeof(void_error_detail_v1)) {
|
||||
return;
|
||||
}
|
||||
out_err->status = status;
|
||||
try {
|
||||
char* buf = new char[msg.size() + 1];
|
||||
std::memcpy(buf, msg.c_str(), msg.size() + 1);
|
||||
out_err->message = buf;
|
||||
out_err->release = &free_cabi_cstring;
|
||||
out_err->release_ctx = nullptr;
|
||||
} catch (...) {
|
||||
out_err->message = nullptr;
|
||||
out_err->release = nullptr;
|
||||
out_err->release_ctx = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
inline void free_cabi_bytes(void* /*ctx*/, const std::uint8_t* data,
|
||||
std::uint64_t /*size*/)
|
||||
{
|
||||
delete[] data;
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
/// Exception-safe bridge adapting a C++ IModule instance to the C11
|
||||
/// void_module_api_v1 contract without letting C++ exceptions unwind across C.
|
||||
struct CModuleAdapterBox {
|
||||
std::unique_ptr<IModule> module;
|
||||
Service::ServiceRegistry fallback_registry;
|
||||
ModuleHost host{fallback_registry};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
};
|
||||
|
||||
template <typename CallbackFn>
|
||||
[[nodiscard]] inline std::int32_t
|
||||
invoke_contained(void_error_detail_v1* out_err, CallbackFn&& fn) noexcept
|
||||
{
|
||||
try {
|
||||
return fn();
|
||||
} catch (const std::exception& ex) {
|
||||
detail::set_error_detail(out_err, VOID_STATUS_INTERNAL, ex.what());
|
||||
return VOID_STATUS_INTERNAL;
|
||||
} catch (...) {
|
||||
detail::set_error_detail(out_err, VOID_STATUS_INTERNAL,
|
||||
"CAbiAdapter: unknown C++ exception");
|
||||
return VOID_STATUS_INTERNAL;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int32_t
|
||||
adapt_checkpoint(CModuleAdapterBox* box,
|
||||
void_owned_bytes_v1* out_state,
|
||||
void_error_detail_v1* out_err) noexcept
|
||||
{
|
||||
if (box == nullptr || !box->module || out_state == nullptr) {
|
||||
return VOID_STATUS_INVALID_ARGUMENT;
|
||||
}
|
||||
return invoke_contained(out_err, [&]() -> std::int32_t {
|
||||
const auto json = Void::Json::serialize(box->module->checkpoint());
|
||||
auto* buf = new std::uint8_t[json.size()];
|
||||
if (!json.empty()) {
|
||||
std::memcpy(buf, json.data(), json.size());
|
||||
}
|
||||
out_state->data = buf;
|
||||
out_state->size = static_cast<std::uint64_t>(json.size());
|
||||
out_state->release = &detail::free_cabi_bytes;
|
||||
out_state->release_ctx = nullptr;
|
||||
return VOID_STATUS_OK;
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int32_t
|
||||
adapt_restore(CModuleAdapterBox* box, void_bytes_v1 state,
|
||||
void_error_detail_v1* out_err) noexcept
|
||||
{
|
||||
if (box == nullptr || !box->module) {
|
||||
return VOID_STATUS_INVALID_ARGUMENT;
|
||||
}
|
||||
return invoke_contained(out_err, [&]() -> std::int32_t {
|
||||
const std::string_view sv{
|
||||
reinterpret_cast<const char*>(state.data),
|
||||
static_cast<std::size_t>(state.size)};
|
||||
const auto parsed = Void::Json::parse(sv);
|
||||
if (!parsed.has_value()) {
|
||||
detail::set_error_detail(out_err, VOID_STATUS_CORRUPT,
|
||||
parsed.error().message);
|
||||
return VOID_STATUS_CORRUPT;
|
||||
}
|
||||
const auto res = box->module->restore(*parsed);
|
||||
if (!res.has_value()) {
|
||||
detail::set_error_detail(out_err, VOID_STATUS_STATE_REJECTED,
|
||||
res.error().message());
|
||||
return VOID_STATUS_STATE_REJECTED;
|
||||
}
|
||||
return VOID_STATUS_OK;
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int32_t
|
||||
adapt_activate(CModuleAdapterBox* box,
|
||||
void_error_detail_v1* out_err) noexcept
|
||||
{
|
||||
if (box == nullptr || !box->module) {
|
||||
return VOID_STATUS_INVALID_ARGUMENT;
|
||||
}
|
||||
return invoke_contained(out_err, [&]() -> std::int32_t {
|
||||
const auto r = box->module->activate(box->host);
|
||||
if (!r.has_value()) {
|
||||
detail::set_error_detail(out_err, VOID_STATUS_INTERNAL,
|
||||
r.error().message());
|
||||
return VOID_STATUS_INTERNAL;
|
||||
}
|
||||
return VOID_STATUS_OK;
|
||||
});
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int32_t
|
||||
adapt_readiness(CModuleAdapterBox* box, std::uint32_t* out_ready,
|
||||
void_error_detail_v1* out_err) noexcept
|
||||
{
|
||||
if (box == nullptr || !box->module || out_ready == nullptr) {
|
||||
return VOID_STATUS_INVALID_ARGUMENT;
|
||||
}
|
||||
*out_ready = 0;
|
||||
return invoke_contained(out_err, [&]() -> std::int32_t {
|
||||
const auto r = box->module->readiness();
|
||||
*out_ready = r.ready ? 1u : 0u;
|
||||
if (!r.ready && !r.detail.empty()) {
|
||||
detail::set_error_detail(out_err, VOID_STATUS_NOT_READY,
|
||||
r.detail);
|
||||
}
|
||||
return VOID_STATUS_OK;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace Void::Plugin
|
||||
@@ -0,0 +1,350 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Plugin/CAbi.h>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Plugin
|
||||
{
|
||||
enum class PluginErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
file_not_found = 2,
|
||||
dlopen_failed = 3,
|
||||
symbol_missing = 4,
|
||||
abi_mismatch = 5,
|
||||
activation_failed = 6,
|
||||
not_ready = 7,
|
||||
quiesce_failed = 8,
|
||||
resume_degraded = 9,
|
||||
checkpoint_failed = 10,
|
||||
restore_failed = 11,
|
||||
restart_required = 12,
|
||||
cycle_detected = 13,
|
||||
missing_dependency = 14,
|
||||
retention_limit = 15,
|
||||
budget_exceeded = 16,
|
||||
conflict = 17,
|
||||
cancelled = 18,
|
||||
timeout = 19,
|
||||
not_found = 20,
|
||||
internal = 21,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_plugin_error(PluginErrorCode code, std::string message = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case PluginErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case PluginErrorCode::invalid_argument:
|
||||
case PluginErrorCode::abi_mismatch:
|
||||
case PluginErrorCode::cycle_detected:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case PluginErrorCode::file_not_found:
|
||||
case PluginErrorCode::symbol_missing:
|
||||
case PluginErrorCode::missing_dependency:
|
||||
case PluginErrorCode::not_found:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case PluginErrorCode::dlopen_failed:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case PluginErrorCode::conflict:
|
||||
case PluginErrorCode::restart_required:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case PluginErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case PluginErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case PluginErrorCode::retention_limit:
|
||||
case PluginErrorCode::budget_exceeded:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case PluginErrorCode::activation_failed:
|
||||
case PluginErrorCode::not_ready:
|
||||
case PluginErrorCode::quiesce_failed:
|
||||
case PluginErrorCode::resume_degraded:
|
||||
case PluginErrorCode::checkpoint_failed:
|
||||
case PluginErrorCode::restore_failed:
|
||||
case PluginErrorCode::internal:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kPluginErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct PluginHostLimits {
|
||||
std::size_t max_modules{64};
|
||||
std::size_t max_interfaces_per_module{256};
|
||||
std::size_t max_retained_generations{4};
|
||||
std::size_t max_mapped_bytes_per_module{64 * 1024 * 1024};
|
||||
std::size_t max_checkpoint_bytes{4 * 1024 * 1024};
|
||||
std::size_t max_config_bytes{1 * 1024 * 1024};
|
||||
std::size_t max_async_activities{1024};
|
||||
std::size_t max_pending_callbacks{256};
|
||||
std::chrono::milliseconds prepare_timeout{
|
||||
std::chrono::seconds{5}};
|
||||
std::chrono::milliseconds quiesce_timeout{
|
||||
std::chrono::seconds{5}};
|
||||
std::chrono::milliseconds readiness_timeout{
|
||||
std::chrono::seconds{10}};
|
||||
std::chrono::milliseconds total_reload_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
bool allow_safe_dlclose{false};
|
||||
};
|
||||
|
||||
enum class GenerationHealth : std::uint8_t {
|
||||
Healthy = 0,
|
||||
Quiescing,
|
||||
Degraded,
|
||||
Retiring,
|
||||
Retired,
|
||||
};
|
||||
|
||||
struct GenerationSummary {
|
||||
std::uint64_t generation{0};
|
||||
std::string module_id{};
|
||||
std::string version{};
|
||||
std::uint64_t image_bytes{0};
|
||||
std::size_t external_refs{0};
|
||||
std::size_t activity_pins{0};
|
||||
GenerationHealth health{GenerationHealth::Healthy};
|
||||
bool dlclosed{false};
|
||||
};
|
||||
|
||||
struct ReloadEvent {
|
||||
std::string module_id{};
|
||||
std::uint64_t generation{0};
|
||||
bool rollback{false};
|
||||
std::string detail{};
|
||||
};
|
||||
|
||||
struct BatchModuleSpec {
|
||||
std::filesystem::path path{};
|
||||
std::string config{};
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
struct GenerationRecord;
|
||||
}
|
||||
|
||||
/// RAII pin holding an async activity count on a generation. Destroying
|
||||
/// it may schedule asynchronous host retirement if no refs/pins remain.
|
||||
class ActivityPin
|
||||
{
|
||||
public:
|
||||
|
||||
ActivityPin() noexcept = default;
|
||||
~ActivityPin();
|
||||
ActivityPin(ActivityPin&& other) noexcept;
|
||||
ActivityPin& operator=(ActivityPin&& other) noexcept;
|
||||
ActivityPin(const ActivityPin&) = delete;
|
||||
ActivityPin& operator=(const ActivityPin&) = delete;
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_rec != nullptr;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class CModuleHost;
|
||||
friend class GenerationLease;
|
||||
explicit ActivityPin(std::shared_ptr<detail::GenerationRecord> rec)
|
||||
: m_rec(std::move(rec))
|
||||
{
|
||||
}
|
||||
std::shared_ptr<detail::GenerationRecord> m_rec{};
|
||||
};
|
||||
|
||||
/// Owning lease to a queried C interface function table from an exact
|
||||
/// generation. Releases via release_interface before dropping generation ref.
|
||||
class InterfaceLease
|
||||
{
|
||||
public:
|
||||
|
||||
InterfaceLease() noexcept = default;
|
||||
~InterfaceLease();
|
||||
InterfaceLease(InterfaceLease&& other) noexcept;
|
||||
InterfaceLease& operator=(InterfaceLease&& other) noexcept;
|
||||
InterfaceLease(const InterfaceLease&) = delete;
|
||||
InterfaceLease& operator=(const InterfaceLease&) = delete;
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_view.function_table != nullptr;
|
||||
}
|
||||
|
||||
template <typename TableT>
|
||||
[[nodiscard]] const TableT* table() const noexcept
|
||||
{
|
||||
if (m_view.function_table == nullptr ||
|
||||
m_view.table_size < sizeof(TableT)) {
|
||||
return nullptr;
|
||||
}
|
||||
return static_cast<const TableT*>(m_view.function_table);
|
||||
}
|
||||
|
||||
[[nodiscard]] const void_interface_view_v1& view() const noexcept
|
||||
{
|
||||
return m_view;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class GenerationLease;
|
||||
InterfaceLease(std::shared_ptr<detail::GenerationRecord> rec,
|
||||
void_interface_id_v1 id,
|
||||
void_interface_view_v1 view) noexcept
|
||||
: m_rec(std::move(rec)), m_id(id), m_view(view)
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<detail::GenerationRecord> m_rec{};
|
||||
void_interface_id_v1 m_id{};
|
||||
void_interface_view_v1 m_view{};
|
||||
};
|
||||
|
||||
/// Owning generation reference acquired from CModuleHost. Prevents module
|
||||
/// deactivation and dlclose while held, and supports activity pinning,
|
||||
/// C interface querying, and bounded async operation submission.
|
||||
class GenerationLease
|
||||
{
|
||||
public:
|
||||
|
||||
GenerationLease() noexcept = default;
|
||||
~GenerationLease();
|
||||
GenerationLease(const GenerationLease& other);
|
||||
GenerationLease& operator=(const GenerationLease& other);
|
||||
GenerationLease(GenerationLease&& other) noexcept;
|
||||
GenerationLease& operator=(GenerationLease&& other) noexcept;
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_rec != nullptr;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept;
|
||||
[[nodiscard]] std::string_view module_id() const noexcept;
|
||||
[[nodiscard]] std::string_view version() const noexcept;
|
||||
[[nodiscard]] GenerationHealth health() const noexcept;
|
||||
|
||||
[[nodiscard]] ActivityPin acquire_activity_pin() const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<InterfaceLease>
|
||||
query_interface(const void_interface_id_v1& id,
|
||||
std::uint32_t min_major,
|
||||
std::uint32_t min_table_size) const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::uint8_t>>
|
||||
run_async(std::uint32_t op_kind,
|
||||
const std::vector<std::uint8_t>& payload,
|
||||
Void::Async::OperationOptions options = {}) const;
|
||||
|
||||
private:
|
||||
|
||||
friend class CModuleHost;
|
||||
struct AlreadyRefCountedTag {};
|
||||
explicit GenerationLease(
|
||||
std::shared_ptr<detail::GenerationRecord> rec);
|
||||
GenerationLease(std::shared_ptr<detail::GenerationRecord> rec,
|
||||
AlreadyRefCountedTag) noexcept
|
||||
: m_rec(std::move(rec))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<detail::GenerationRecord> m_rec{};
|
||||
};
|
||||
|
||||
/// Hardened C-ABI module host implementing size/version negotiation,
|
||||
/// independent external_refs & activity_pins, host-thread retirement queue,
|
||||
/// unlocked quiesce/checkpoint/restore/readiness/resume reload, and
|
||||
/// dependency-ordered batch loading.
|
||||
class CModuleHost
|
||||
{
|
||||
public:
|
||||
|
||||
struct Impl;
|
||||
|
||||
explicit CModuleHost(
|
||||
PluginHostLimits limits = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
~CModuleHost();
|
||||
|
||||
CModuleHost(const CModuleHost&) = delete;
|
||||
CModuleHost& operator=(const CModuleHost&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
load(const std::filesystem::path& path,
|
||||
std::string_view config = {},
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::string>>
|
||||
load_batch(const std::vector<BatchModuleSpec>& specs,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
replace(std::string_view module_id,
|
||||
const std::filesystem::path& new_path,
|
||||
std::string_view config = {},
|
||||
std::optional<std::uint64_t> expected_generation =
|
||||
std::nullopt,
|
||||
Void::Async::OperationOptions options = {},
|
||||
std::function<Void::Result::Result<void>(
|
||||
const GenerationLease&)>
|
||||
on_publish_locked = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
unload(std::string_view module_id);
|
||||
|
||||
[[nodiscard]] GenerationLease
|
||||
acquire(std::string_view module_id) const;
|
||||
|
||||
[[nodiscard]] std::vector<GenerationSummary>
|
||||
retained_generations(std::string_view module_id) const;
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
mapped_bytes(std::string_view module_id) const;
|
||||
|
||||
std::size_t add_observer(std::function<void(const ReloadEvent&)> cb);
|
||||
void remove_observer(std::size_t id);
|
||||
|
||||
/// Drain retirement queue and shutdown background retirement worker.
|
||||
void close_and_join();
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<Impl> m_impl;
|
||||
};
|
||||
|
||||
} // namespace Void::Plugin
|
||||
@@ -215,18 +215,20 @@ namespace Void::Plugin
|
||||
std::filesystem::path path;
|
||||
std::atomic<std::shared_ptr<detail::Instance>> current;
|
||||
bool watched{false};
|
||||
std::mutex reload_mutex;
|
||||
};
|
||||
|
||||
Entry* find(std::string_view name) const;
|
||||
std::expected<void, LoadError>
|
||||
reload_locked(Entry& entry, std::string_view name,
|
||||
const std::filesystem::path& sourcePath);
|
||||
std::shared_ptr<Entry> find_shared(std::string_view name) const;
|
||||
std::expected<void, LoadError> reload_entry_unlocked(
|
||||
const std::shared_ptr<Entry>& entry, std::string_view name,
|
||||
const std::optional<std::filesystem::path>& newPath);
|
||||
std::vector<std::function<void(std::string_view)>>
|
||||
reload_callbacks_locked() const;
|
||||
|
||||
Options m_options;
|
||||
mutable std::mutex m_mutex; // guards the registry map + reloads
|
||||
std::unordered_map<std::string, std::unique_ptr<Entry>> m_plugins;
|
||||
mutable std::mutex m_mutex; // guards the registry map & observer list
|
||||
std::unordered_map<std::string, std::shared_ptr<Entry>> m_plugins;
|
||||
std::vector<std::pair<ReloadCallbackId,
|
||||
std::function<void(std::string_view)>>>
|
||||
m_on_reloaded;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/RPC/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::RPC
|
||||
{
|
||||
/// Decoded Wire v1 envelope (deterministic big-endian binary format).
|
||||
struct WireEnvelope {
|
||||
std::uint16_t major{kWireMajorV1};
|
||||
std::uint16_t minor{kWireMinorV1};
|
||||
FrameKind kind{FrameKind::UnaryRequest};
|
||||
std::uint8_t flags{kFlagEndOfMessage};
|
||||
CallId call_id{};
|
||||
MethodId method{};
|
||||
std::uint32_t schema_version{1};
|
||||
std::uint32_t remaining_timeout_ms{0};
|
||||
RpcStatusCode status_code{RpcStatusCode::Ok};
|
||||
std::vector<MetadataEntry> metadata{};
|
||||
std::vector<std::byte> payload{};
|
||||
};
|
||||
|
||||
/// Fixed Wire v1 header prefix size in bytes before metadata entries:
|
||||
/// magic(4) + major(2) + minor(2) + header_len(4) + total_len(4) +
|
||||
/// kind(1) + flags(1) + reserved(2) + call_id(16) + service_id(8) +
|
||||
/// method_id(4) + schema_ver(4) + timeout_ms(4) + status_code(2) +
|
||||
/// metadata_count(2) = 60 bytes.
|
||||
inline constexpr std::size_t kWireFixedHeaderBytes{60};
|
||||
|
||||
/// Encode a Wire v1 envelope in explicit network byte order, validating
|
||||
/// all header, metadata, and payload limits before allocation.
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
|
||||
encode_envelope(const WireEnvelope& env,
|
||||
const RpcLimits& limits = {});
|
||||
|
||||
/// Decode a Wire v1 envelope in explicit network byte order. Rejects bad
|
||||
/// magic, unsupported major versions, non-zero reserved bytes, unknown
|
||||
/// required flags, integer overflow, truncation, trailing garbage, and
|
||||
/// limit violations BEFORE allocating payload/metadata buffers. Unknown
|
||||
/// optional minor header extensions beyond metadata are length-skipped.
|
||||
[[nodiscard]] Void::Result::Result<WireEnvelope>
|
||||
decode_envelope(std::span<const std::byte> bytes,
|
||||
const RpcLimits& limits = {});
|
||||
|
||||
} // namespace Void::RPC
|
||||
@@ -0,0 +1,184 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/RPC/Codec.hpp>
|
||||
#include <Void/RPC/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::RPC
|
||||
{
|
||||
using OwnedBytes = std::vector<std::byte>;
|
||||
|
||||
struct CallContext {
|
||||
CallId call_id{};
|
||||
MethodDescriptor method{};
|
||||
PrincipalView principal{};
|
||||
Void::Time::MonotonicClock::time_point deadline{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
std::vector<MetadataEntry> metadata{};
|
||||
std::stop_token stop{};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
remaining_timeout() const noexcept
|
||||
{
|
||||
const auto rem = Void::Time::remaining_until(*clock, deadline);
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
rem);
|
||||
}
|
||||
};
|
||||
|
||||
struct CallOptions {
|
||||
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
|
||||
std::vector<MetadataEntry> metadata{};
|
||||
std::vector<Void::Net::Header> transport_headers{};
|
||||
std::stop_token stop{};
|
||||
std::uint32_t schema_version{1};
|
||||
};
|
||||
|
||||
using UnaryHandler =
|
||||
std::function<Void::Result::Result<OwnedBytes>(const CallContext&,
|
||||
OwnedBytes)>;
|
||||
|
||||
struct AuthHook {
|
||||
std::function<Void::Result::Result<PrincipalView>(
|
||||
const std::vector<Void::Net::Header>& transport_headers,
|
||||
const std::vector<MetadataEntry>& metadata)>
|
||||
authenticate{};
|
||||
|
||||
std::function<Void::Result::Result<void>(
|
||||
const MethodDescriptor& method, const PrincipalView& principal)>
|
||||
authorize{};
|
||||
};
|
||||
|
||||
/// Move-only RAII method registration handle. Unregistering stops new
|
||||
/// admission for the method and drains already-admitted calls before
|
||||
/// returning.
|
||||
class Registration final
|
||||
{
|
||||
public:
|
||||
|
||||
Registration() noexcept = default;
|
||||
~Registration() noexcept;
|
||||
|
||||
Registration(Registration&& other) noexcept;
|
||||
Registration& operator=(Registration&& other) noexcept;
|
||||
Registration(const Registration&) = delete;
|
||||
Registration& operator=(const Registration&) = delete;
|
||||
|
||||
[[nodiscard]] bool active() const noexcept;
|
||||
void unregister_and_drain() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class Server;
|
||||
struct Entry;
|
||||
std::shared_ptr<void> m_server_state{};
|
||||
MethodId m_id{};
|
||||
std::uint64_t m_reg_gen{0};
|
||||
bool m_active{false};
|
||||
};
|
||||
|
||||
struct ServerOptions {
|
||||
Void::Net::HttpServerOptions http_options{};
|
||||
RpcLimits limits{};
|
||||
AuthHook auth{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
};
|
||||
|
||||
/// Ownership-safe unary HTTP/1.1 RPC server implementing `/void-rpc/v1/call`.
|
||||
class Server final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Server(ServerOptions options = {});
|
||||
~Server() noexcept;
|
||||
|
||||
Server(Server&&) noexcept;
|
||||
Server& operator=(Server&&) noexcept;
|
||||
Server(const Server&) = delete;
|
||||
Server& operator=(const Server&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Registration>
|
||||
bind(MethodDescriptor descriptor, UnaryHandler handler);
|
||||
|
||||
/// Mount `/void-rpc/v1/call` onto an external HttpServer (or call
|
||||
/// `start()` to run the owned HttpServer directly).
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
mount(Void::Net::HttpServer& http_server);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
|
||||
void shutdown(std::chrono::milliseconds drain_timeout =
|
||||
std::chrono::seconds{10}) noexcept;
|
||||
|
||||
[[nodiscard]] bool running() const noexcept;
|
||||
[[nodiscard]] std::uint16_t bound_port() const noexcept;
|
||||
[[nodiscard]] std::string base_url() const;
|
||||
|
||||
/// Direct in-process Wire v1 dispatch (useful for deterministic
|
||||
/// unit/fault testing without TCP sockets).
|
||||
[[nodiscard]] Void::Result::Result<OwnedBytes>
|
||||
handle_raw_envelope(
|
||||
std::span<const std::byte> request_bytes,
|
||||
const std::vector<Void::Net::Header>& transport_headers =
|
||||
{});
|
||||
|
||||
private:
|
||||
|
||||
friend class Registration;
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
struct ClientOptions {
|
||||
std::string endpoint_base_url{};
|
||||
Void::Net::HttpClientOptions http_options{
|
||||
.verify_tls = true,
|
||||
};
|
||||
RpcLimits limits{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
};
|
||||
|
||||
/// Unary HTTP/1.1 RPC client encoding Wire v1 envelopes over
|
||||
/// `Void::Net::HttpClient`.
|
||||
class Client final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Client(ClientOptions options);
|
||||
~Client() noexcept;
|
||||
|
||||
Client(Client&&) noexcept;
|
||||
Client& operator=(Client&&) noexcept;
|
||||
Client(const Client&) = delete;
|
||||
Client& operator=(const Client&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<OwnedBytes>
|
||||
call(MethodId method, OwnedBytes payload,
|
||||
const CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] std::size_t in_flight_calls() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::RPC
|
||||
@@ -0,0 +1,205 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::RPC
|
||||
{
|
||||
inline constexpr std::array<std::byte, 4> kWireMagic{
|
||||
std::byte{'V'}, std::byte{'R'}, std::byte{'P'}, std::byte{'C'}};
|
||||
inline constexpr std::uint16_t kWireMajorV1{1};
|
||||
inline constexpr std::uint16_t kWireMinorV1{0};
|
||||
inline constexpr std::string_view kUnaryHttpPath{"/void-rpc/v1/call"};
|
||||
inline constexpr std::string_view kWireContentType{
|
||||
"application/vnd.void.rpc.v1"};
|
||||
|
||||
enum class RpcStatusCode : std::uint16_t {
|
||||
Ok = 0,
|
||||
Cancelled = 1,
|
||||
InvalidArgument = 2,
|
||||
DeadlineExceeded = 3,
|
||||
NotFound = 4,
|
||||
PermissionDenied = 5,
|
||||
Unauthenticated = 6,
|
||||
ResourceExhausted = 7,
|
||||
FailedPrecondition = 8,
|
||||
Unimplemented = 9,
|
||||
Unavailable = 10,
|
||||
Internal = 11,
|
||||
DataLoss = 12,
|
||||
UnknownOutcome = 13,
|
||||
ProtocolError = 14,
|
||||
IncompatibleVersion = 15,
|
||||
};
|
||||
|
||||
enum class FrameKind : std::uint8_t {
|
||||
UnaryRequest = 1,
|
||||
UnaryResponse = 2,
|
||||
StreamOpen = 3,
|
||||
StreamData = 4,
|
||||
StreamCredit = 5,
|
||||
StreamHalfClose = 6,
|
||||
StreamCancel = 7,
|
||||
StreamTerminal = 8,
|
||||
};
|
||||
|
||||
/// Wire v1 frame flags. Bits 0..3 are optional/informational; bits 4..7 are
|
||||
/// required-to-understand (unknown required flags fail closed).
|
||||
inline constexpr std::uint8_t kFlagNone = 0x00U;
|
||||
inline constexpr std::uint8_t kFlagEndOfMessage = 0x01U;
|
||||
inline constexpr std::uint8_t kFlagRequiredMask = 0xF0U;
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_rpc_error(RpcStatusCode code, std::string message)
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case RpcStatusCode::Ok:
|
||||
case RpcStatusCode::Internal:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case RpcStatusCode::Cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case RpcStatusCode::InvalidArgument:
|
||||
case RpcStatusCode::PermissionDenied:
|
||||
case RpcStatusCode::Unauthenticated:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case RpcStatusCode::DeadlineExceeded:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case RpcStatusCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case RpcStatusCode::ResourceExhausted:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case RpcStatusCode::FailedPrecondition:
|
||||
case RpcStatusCode::UnknownOutcome:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case RpcStatusCode::Unimplemented:
|
||||
case RpcStatusCode::IncompatibleVersion:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case RpcStatusCode::Unavailable:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case RpcStatusCode::DataLoss:
|
||||
case RpcStatusCode::ProtocolError:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kRpcErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
[[nodiscard]] inline RpcStatusCode
|
||||
rpc_status_from_error(const Void::Result::Error& err) noexcept
|
||||
{
|
||||
if (err.code().domain == Void::Result::kRpcErrorDomain) {
|
||||
return static_cast<RpcStatusCode>(err.code().value);
|
||||
}
|
||||
switch (err.kind()) {
|
||||
case Void::Result::ErrorKind::cancelled:
|
||||
return RpcStatusCode::Cancelled;
|
||||
case Void::Result::ErrorKind::invalid_argument:
|
||||
return RpcStatusCode::InvalidArgument;
|
||||
case Void::Result::ErrorKind::timeout:
|
||||
return RpcStatusCode::DeadlineExceeded;
|
||||
case Void::Result::ErrorKind::not_found:
|
||||
return RpcStatusCode::NotFound;
|
||||
case Void::Result::ErrorKind::exhausted:
|
||||
return RpcStatusCode::ResourceExhausted;
|
||||
case Void::Result::ErrorKind::conflict:
|
||||
return RpcStatusCode::FailedPrecondition;
|
||||
case Void::Result::ErrorKind::unsupported:
|
||||
return RpcStatusCode::Unimplemented;
|
||||
case Void::Result::ErrorKind::overloaded:
|
||||
return RpcStatusCode::Unavailable;
|
||||
case Void::Result::ErrorKind::corrupt:
|
||||
return RpcStatusCode::ProtocolError;
|
||||
default:
|
||||
return RpcStatusCode::Internal;
|
||||
}
|
||||
}
|
||||
|
||||
struct MethodId {
|
||||
std::uint64_t service{0};
|
||||
std::uint32_t method{0};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const MethodId&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct CallId {
|
||||
std::array<std::byte, 16> bytes{};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const CallId&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] static CallId generate();
|
||||
};
|
||||
|
||||
struct MetadataEntry {
|
||||
std::string key{};
|
||||
std::string value{};
|
||||
|
||||
[[nodiscard]] bool
|
||||
operator==(const MetadataEntry&) const noexcept = default;
|
||||
};
|
||||
|
||||
/// Immutable authenticated principal descriptor provided by AuthHook.
|
||||
struct PrincipalView {
|
||||
bool authenticated{false};
|
||||
std::string subject{};
|
||||
std::vector<std::string> roles{};
|
||||
std::map<std::string, std::string, std::less<>> attributes{};
|
||||
};
|
||||
|
||||
struct MethodDescriptor {
|
||||
MethodId id{};
|
||||
std::string service_name{};
|
||||
std::string method_name{};
|
||||
std::uint32_t schema_version{1};
|
||||
bool replay_safe{false};
|
||||
};
|
||||
|
||||
struct RpcLimits {
|
||||
std::size_t max_header_bytes{16ULL * 1024};
|
||||
std::size_t max_metadata_entries{64};
|
||||
std::size_t max_payload_bytes{4ULL * 1024 * 1024};
|
||||
std::size_t max_client_calls{1024};
|
||||
std::size_t max_server_executing{256};
|
||||
std::size_t max_server_queued_bytes{64ULL * 1024 * 1024};
|
||||
std::chrono::milliseconds max_server_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
};
|
||||
|
||||
struct RpcStatus {
|
||||
RpcStatusCode code{RpcStatusCode::Ok};
|
||||
std::string message{};
|
||||
|
||||
[[nodiscard]] bool ok() const noexcept
|
||||
{
|
||||
return code == RpcStatusCode::Ok;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::RPC
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,353 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Resilience/KeyedRateLimiter.hpp>
|
||||
#include <Void/Security/Authorization.hpp>
|
||||
#include <Void/Security/SecureBuffer.hpp>
|
||||
#include <Void/Security/Security.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::SecurityAsync
|
||||
{
|
||||
struct AccountRecord {
|
||||
std::string subject{};
|
||||
std::string normalized_username{};
|
||||
std::string password_hash{};
|
||||
std::vector<std::string> roles{};
|
||||
std::uint64_t credential_version{1};
|
||||
std::uint64_t revocation_generation{1};
|
||||
std::uint64_t policy_generation{1};
|
||||
bool enabled{true};
|
||||
};
|
||||
|
||||
struct SessionRecord {
|
||||
std::string session_id{};
|
||||
std::string token_digest{};
|
||||
std::string subject{};
|
||||
std::vector<std::string> roles{};
|
||||
std::uint64_t credential_version{1};
|
||||
std::uint64_t revocation_generation{1};
|
||||
std::uint64_t policy_generation{1};
|
||||
Void::Time::CivilClock::time_point created_at{};
|
||||
Void::Time::CivilClock::time_point expires_at{};
|
||||
bool revoked{false};
|
||||
};
|
||||
|
||||
class AccountSessionPort
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~AccountSessionPort() = default;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<AccountRecord>>
|
||||
find_account_by_username(
|
||||
std::string_view normalized_username) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<AccountRecord>>
|
||||
find_account_by_subject(std::string_view subject) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
update_password_hash_if_version(
|
||||
std::string_view subject,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::string new_password_hash) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
create_session_if_version(
|
||||
const SessionRecord& session,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::size_t max_total_sessions,
|
||||
std::size_t max_per_subject,
|
||||
Void::Time::CivilClock::time_point now) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<SessionRecord>>
|
||||
find_session_by_token_digest(std::string_view token_digest) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
revoke_session(std::string_view session_id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<std::size_t>
|
||||
cleanup_expired_sessions(
|
||||
Void::Time::CivilClock::time_point now,
|
||||
std::size_t batch_limit) = 0;
|
||||
};
|
||||
|
||||
class InMemoryAccountSessionStore final : public AccountSessionPort
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
upsert_account(AccountRecord account);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
bump_credential_version(std::string_view subject,
|
||||
std::string new_password_hash = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
set_account_enabled(std::string_view subject, bool enabled);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
bump_revocation_generation(std::string_view subject);
|
||||
|
||||
void set_available(bool available) noexcept;
|
||||
[[nodiscard]] std::size_t session_count() const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<AccountRecord>>
|
||||
find_account_by_username(
|
||||
std::string_view normalized_username) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<AccountRecord>>
|
||||
find_account_by_subject(std::string_view subject) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
update_password_hash_if_version(
|
||||
std::string_view subject,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::string new_password_hash) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> create_session_if_version(
|
||||
const SessionRecord& session,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::size_t max_total_sessions, std::size_t max_per_subject,
|
||||
Void::Time::CivilClock::time_point now) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<SessionRecord>>
|
||||
find_session_by_token_digest(
|
||||
std::string_view token_digest) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
revoke_session(std::string_view session_id) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
cleanup_expired_sessions(Void::Time::CivilClock::time_point now,
|
||||
std::size_t batch_limit) override;
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mu{};
|
||||
bool m_available{true};
|
||||
std::map<std::string, AccountRecord, std::less<>>
|
||||
m_accounts_by_subject{};
|
||||
std::map<std::string, std::string, std::less<>>
|
||||
m_subject_by_username{};
|
||||
std::map<std::string, SessionRecord, std::less<>>
|
||||
m_sessions_by_id{};
|
||||
std::map<std::string, std::string, std::less<>>
|
||||
m_session_id_by_digest{};
|
||||
};
|
||||
|
||||
struct AuditEvent {
|
||||
std::string event_type{};
|
||||
std::string subject{};
|
||||
std::string internal_reason{};
|
||||
bool success{false};
|
||||
Void::Time::CivilClock::time_point timestamp{};
|
||||
};
|
||||
|
||||
class AuditSink
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~AuditSink() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
record(const AuditEvent& event) = 0;
|
||||
};
|
||||
|
||||
class InMemoryAuditSink final : public AuditSink
|
||||
{
|
||||
public:
|
||||
|
||||
explicit InMemoryAuditSink(std::size_t max_events = 1024) noexcept
|
||||
: m_max_events(max_events)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
record(const AuditEvent& event) override;
|
||||
|
||||
[[nodiscard]] std::vector<AuditEvent> snapshot() const;
|
||||
void clear();
|
||||
|
||||
private:
|
||||
|
||||
std::size_t m_max_events{1024};
|
||||
mutable std::mutex m_mu{};
|
||||
std::vector<AuditEvent> m_events{};
|
||||
};
|
||||
|
||||
enum class AuditFailurePolicy : std::uint8_t {
|
||||
FailClosed = 0,
|
||||
BestEffort
|
||||
};
|
||||
|
||||
struct PasswordJobBudget {
|
||||
std::size_t max_memory_bytes{
|
||||
Void::Security::SecurityLimits::
|
||||
kDefaultPasswordJobMemoryBudgetBytes};
|
||||
std::size_t max_concurrent_jobs{
|
||||
Void::Security::SecurityLimits::
|
||||
kDefaultMaxConcurrentPasswordJobs};
|
||||
std::size_t max_waiters{
|
||||
Void::Security::SecurityLimits::kDefaultMaxWaitingPasswordJobs};
|
||||
};
|
||||
|
||||
struct SessionPolicy {
|
||||
std::chrono::seconds ttl{
|
||||
Void::Security::SecurityLimits::kDefaultSessionTtl};
|
||||
std::size_t max_total_sessions{
|
||||
Void::Security::SecurityLimits::kDefaultMaxTotalSessions};
|
||||
std::size_t max_per_subject{
|
||||
Void::Security::SecurityLimits::kDefaultMaxSessionsPerSubject};
|
||||
std::chrono::seconds clock_rollback_tolerance{
|
||||
Void::Security::SecurityLimits::
|
||||
kDefaultClockRollbackTolerance};
|
||||
std::size_t expiry_cleanup_batch{
|
||||
Void::Security::SecurityLimits::kDefaultExpiryCleanupBatch};
|
||||
};
|
||||
|
||||
struct AuthenticatorOptions {
|
||||
SessionPolicy session{};
|
||||
PasswordJobBudget password_budget{};
|
||||
Void::Security::PasswordVerifyBudget verify_budget{};
|
||||
Void::Security::PasswordHashStrength dummy_hash_strength{
|
||||
Void::Security::PasswordHashStrength::Moderate};
|
||||
std::string precomputed_dummy_hash{};
|
||||
AuditFailurePolicy audit_policy{AuditFailurePolicy::FailClosed};
|
||||
Void::Resilience::KeyedBucketConfig rate_limit{
|
||||
.capacity = 20.0,
|
||||
.refill_per_second = 5.0,
|
||||
.max_keys = 4096,
|
||||
.max_key_bytes = 256,
|
||||
};
|
||||
std::optional<Void::Time::CivilClock::time_point>
|
||||
last_known_civil_time{};
|
||||
Void::Security::LockPolicy secret_lock_policy{
|
||||
Void::Security::LockPolicy::StandardWiped};
|
||||
std::function<void()> before_password_verify_hook{};
|
||||
};
|
||||
|
||||
class BearerToken
|
||||
{
|
||||
public:
|
||||
|
||||
BearerToken() noexcept = default;
|
||||
BearerToken(BearerToken&&) noexcept = default;
|
||||
BearerToken& operator=(BearerToken&&) noexcept = default;
|
||||
BearerToken(const BearerToken&) = delete;
|
||||
BearerToken& operator=(const BearerToken&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<BearerToken>
|
||||
from_string(std::string_view raw,
|
||||
Void::Security::LockPolicy policy =
|
||||
Void::Security::LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] std::string_view expose_secret() const noexcept
|
||||
{
|
||||
return m_buf.string_view();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept { return m_buf.empty(); }
|
||||
void clear() noexcept { m_buf.clear(); }
|
||||
|
||||
private:
|
||||
|
||||
explicit BearerToken(Void::Security::SecureBuffer buf) noexcept
|
||||
: m_buf(std::move(buf))
|
||||
{
|
||||
}
|
||||
|
||||
Void::Security::SecureBuffer m_buf{};
|
||||
friend class Authenticator;
|
||||
};
|
||||
|
||||
struct LoginInput {
|
||||
std::string username{};
|
||||
std::string password{};
|
||||
};
|
||||
|
||||
struct SessionGrant {
|
||||
std::string session_id{};
|
||||
BearerToken bearer_token{};
|
||||
Void::Time::CivilClock::time_point expires_at{};
|
||||
Void::Security::Principal principal{};
|
||||
};
|
||||
|
||||
struct AuthenticatorStats {
|
||||
std::size_t active_password_jobs{0};
|
||||
std::size_t waiting_password_jobs{0};
|
||||
std::size_t reserved_password_memory_bytes{0};
|
||||
bool closing{false};
|
||||
};
|
||||
|
||||
class Authenticator
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<
|
||||
std::unique_ptr<Authenticator>>
|
||||
create(std::shared_ptr<AccountSessionPort> port,
|
||||
Void::Async::Executor& executor,
|
||||
AuthenticatorOptions options = {},
|
||||
std::shared_ptr<AuditSink> audit_sink = {},
|
||||
const Void::Time::MonotonicClock& monotonic_clock =
|
||||
Void::Time::SystemMonotonicClock::instance(),
|
||||
const Void::Time::CivilClock& civil_clock =
|
||||
Void::Time::SystemCivilClock::instance());
|
||||
|
||||
~Authenticator();
|
||||
Authenticator(const Authenticator&) = delete;
|
||||
Authenticator& operator=(const Authenticator&) = delete;
|
||||
Authenticator(Authenticator&&) = delete;
|
||||
Authenticator& operator=(Authenticator&&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<SessionGrant>>
|
||||
login(LoginInput input,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<
|
||||
Void::Result::Result<Void::Security::Principal>>
|
||||
authenticate(const BearerToken& token,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void>>
|
||||
revoke(std::string session_id,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
cleanup_expired_step();
|
||||
|
||||
void reconcile_clock(
|
||||
Void::Time::CivilClock::time_point new_watermark) noexcept;
|
||||
|
||||
void request_stop() noexcept;
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
|
||||
[[nodiscard]] AuthenticatorStats stats() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
explicit Authenticator(std::shared_ptr<State> state) noexcept;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::SecurityAsync
|
||||
@@ -0,0 +1,170 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
struct Principal {
|
||||
std::string subject{};
|
||||
std::vector<std::string> roles{};
|
||||
std::uint64_t policy_generation{0};
|
||||
std::map<std::string, std::string, std::less<>> attributes{};
|
||||
};
|
||||
|
||||
struct ResourceAttributes {
|
||||
std::string resource_type{};
|
||||
std::string resource_id{};
|
||||
std::map<std::string, std::string, std::less<>> attributes{};
|
||||
};
|
||||
|
||||
enum class Effect : std::uint8_t { Deny = 0, Allow = 1 };
|
||||
|
||||
/// Native typed policy predicate AST with bounded depth (<= 16) and zero
|
||||
/// script/filesystem/network side effects.
|
||||
struct Predicate {
|
||||
enum class Kind : std::uint8_t {
|
||||
AlwaysTrue = 0,
|
||||
AlwaysFalse,
|
||||
HasRole,
|
||||
SubjectEquals,
|
||||
ResourceTypeEquals,
|
||||
ResourceIdEquals,
|
||||
ResourceAttrEquals,
|
||||
PrincipalAttrEquals,
|
||||
ResourceOwnerMatchesSubject,
|
||||
AllOf,
|
||||
AnyOf,
|
||||
Not
|
||||
};
|
||||
|
||||
Kind kind{Kind::AlwaysFalse};
|
||||
std::string key{};
|
||||
std::string value{};
|
||||
std::vector<Predicate> children{};
|
||||
|
||||
[[nodiscard]] static Predicate always_true()
|
||||
{
|
||||
return Predicate{.kind = Kind::AlwaysTrue};
|
||||
}
|
||||
[[nodiscard]] static Predicate always_false()
|
||||
{
|
||||
return Predicate{.kind = Kind::AlwaysFalse};
|
||||
}
|
||||
[[nodiscard]] static Predicate has_role(std::string role)
|
||||
{
|
||||
return Predicate{.kind = Kind::HasRole,
|
||||
.value = std::move(role)};
|
||||
}
|
||||
[[nodiscard]] static Predicate subject_equals(std::string subject)
|
||||
{
|
||||
return Predicate{.kind = Kind::SubjectEquals,
|
||||
.value = std::move(subject)};
|
||||
}
|
||||
[[nodiscard]] static Predicate resource_type(std::string type)
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceTypeEquals,
|
||||
.value = std::move(type)};
|
||||
}
|
||||
[[nodiscard]] static Predicate resource_id(std::string id)
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceIdEquals,
|
||||
.value = std::move(id)};
|
||||
}
|
||||
[[nodiscard]] static Predicate resource_attr(std::string k,
|
||||
std::string v)
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceAttrEquals,
|
||||
.key = std::move(k),
|
||||
.value = std::move(v)};
|
||||
}
|
||||
[[nodiscard]] static Predicate principal_attr(std::string k,
|
||||
std::string v)
|
||||
{
|
||||
return Predicate{.kind = Kind::PrincipalAttrEquals,
|
||||
.key = std::move(k),
|
||||
.value = std::move(v)};
|
||||
}
|
||||
[[nodiscard]] static Predicate
|
||||
owner_is_subject(std::string owner_attr = "owner")
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceOwnerMatchesSubject,
|
||||
.key = std::move(owner_attr)};
|
||||
}
|
||||
[[nodiscard]] static Predicate all_of(std::vector<Predicate> items)
|
||||
{
|
||||
return Predicate{.kind = Kind::AllOf,
|
||||
.children = std::move(items)};
|
||||
}
|
||||
[[nodiscard]] static Predicate any_of(std::vector<Predicate> items)
|
||||
{
|
||||
return Predicate{.kind = Kind::AnyOf,
|
||||
.children = std::move(items)};
|
||||
}
|
||||
[[nodiscard]] static Predicate negate(Predicate child)
|
||||
{
|
||||
Predicate p{.kind = Kind::Not};
|
||||
p.children.push_back(std::move(child));
|
||||
return p;
|
||||
}
|
||||
};
|
||||
|
||||
struct PolicyRule {
|
||||
std::string id{};
|
||||
Effect effect{Effect::Deny};
|
||||
std::string action{};
|
||||
Predicate condition{Predicate::always_false()};
|
||||
};
|
||||
|
||||
struct Decision {
|
||||
bool allowed{false};
|
||||
std::string matched_rule_id{};
|
||||
std::string reason{};
|
||||
std::uint64_t policy_generation{0};
|
||||
};
|
||||
|
||||
/// Immutable validated authorization policy snapshot.
|
||||
/// Enforces default-deny and deny-overrides-allow with bounded rules
|
||||
/// (<= 4096), roles (<= 64), and predicate nesting depth (<= 16).
|
||||
class PolicySnapshot
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<PolicySnapshot>
|
||||
create(std::uint64_t generation, std::vector<PolicyRule> rules);
|
||||
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept
|
||||
{
|
||||
return m_generation;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t rule_count() const noexcept
|
||||
{
|
||||
return m_rules.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] Decision
|
||||
authorize(const Principal& principal, std::string_view action,
|
||||
const ResourceAttributes& resource) const;
|
||||
|
||||
private:
|
||||
|
||||
PolicySnapshot(std::uint64_t generation,
|
||||
std::vector<PolicyRule> rules) noexcept
|
||||
: m_generation(generation), m_rules(std::move(rules))
|
||||
{
|
||||
}
|
||||
|
||||
std::uint64_t m_generation{0};
|
||||
std::vector<PolicyRule> m_rules{};
|
||||
};
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/SecureBuffer.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
inline constexpr std::uint8_t kEnvelopeVersionV1 = 1;
|
||||
inline constexpr std::uint8_t kEnvelopeAlgXChaCha20Poly1305Ietf = 1;
|
||||
inline constexpr std::size_t kEnvelopeKeyBytes = 32;
|
||||
inline constexpr std::size_t kEnvelopeNonceBytes = 24;
|
||||
inline constexpr std::size_t kEnvelopeTagBytes = 16;
|
||||
|
||||
struct EnvelopeHeader {
|
||||
std::uint8_t version{kEnvelopeVersionV1};
|
||||
std::uint8_t algorithm{kEnvelopeAlgXChaCha20Poly1305Ietf};
|
||||
std::string key_id{};
|
||||
std::uint32_t plaintext_size{0};
|
||||
};
|
||||
|
||||
/// Parse and validate a versioned VSEC envelope header without decrypting.
|
||||
/// Never falls back to legacy seal_secret framing.
|
||||
[[nodiscard]] Void::Result::Result<EnvelopeHeader>
|
||||
inspect_envelope(std::span<const unsigned char> envelope);
|
||||
|
||||
/// Versioned AEAD key ring supporting key rotation: writes use the single
|
||||
/// active key ID, reads resolve the key ID authenticated in the header, and
|
||||
/// retirement requires proving no ciphertext still depends on that key ID.
|
||||
class SecretKeyRing
|
||||
{
|
||||
public:
|
||||
|
||||
SecretKeyRing() = default;
|
||||
SecretKeyRing(SecretKeyRing&&) noexcept = default;
|
||||
SecretKeyRing& operator=(SecretKeyRing&&) noexcept = default;
|
||||
SecretKeyRing(const SecretKeyRing&) = delete;
|
||||
SecretKeyRing& operator=(const SecretKeyRing&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
add_key(std::string key_id,
|
||||
std::span<const unsigned char> raw_key,
|
||||
bool make_active = false,
|
||||
LockPolicy lock_policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> generate_and_add_key(
|
||||
std::string key_id, bool make_active = true,
|
||||
LockPolicy lock_policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
set_active_key(std::string_view key_id);
|
||||
|
||||
/// Retire a non-active key only after the caller supplies an
|
||||
/// inventory of remaining ciphertext key IDs proving none reference
|
||||
/// `key_id`.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
retire_key(std::string_view key_id,
|
||||
std::span<const std::string>
|
||||
remaining_ciphertext_key_ids);
|
||||
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
active_key_id() const;
|
||||
[[nodiscard]] bool has_key(std::string_view key_id) const;
|
||||
[[nodiscard]] std::vector<std::string> key_ids() const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
|
||||
seal(std::span<const unsigned char> plaintext,
|
||||
std::span<const unsigned char> aad = {}) const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<SecureBuffer>
|
||||
open(std::span<const unsigned char> envelope,
|
||||
std::span<const unsigned char> aad = {},
|
||||
LockPolicy out_policy = LockPolicy::StandardWiped) const;
|
||||
|
||||
private:
|
||||
|
||||
std::map<std::string, SecureBuffer, std::less<>> m_keys{};
|
||||
std::string m_active_key_id{};
|
||||
};
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
enum class LockPolicy : std::uint8_t {
|
||||
StandardWiped = 0,
|
||||
LockedOptional,
|
||||
LockedRequired
|
||||
};
|
||||
|
||||
/// Move-only secret byte buffer wiped with sodium_memzero on release.
|
||||
/// Supports optional or required libsodium locked allocation without
|
||||
/// silently downgrading a LockedRequired policy.
|
||||
class SecureBuffer
|
||||
{
|
||||
public:
|
||||
|
||||
SecureBuffer() noexcept = default;
|
||||
~SecureBuffer() noexcept;
|
||||
|
||||
SecureBuffer(SecureBuffer&& other) noexcept;
|
||||
SecureBuffer& operator=(SecureBuffer&& other) noexcept;
|
||||
|
||||
SecureBuffer(const SecureBuffer&) = delete;
|
||||
SecureBuffer& operator=(const SecureBuffer&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<SecureBuffer>
|
||||
allocate(std::size_t size,
|
||||
LockPolicy policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<SecureBuffer>
|
||||
from_bytes(std::span<const unsigned char> data,
|
||||
LockPolicy policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<SecureBuffer>
|
||||
from_string(std::string_view text,
|
||||
LockPolicy policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] std::span<const unsigned char> view() const noexcept
|
||||
{
|
||||
return m_data ? std::span<const unsigned char>{m_data, m_size}
|
||||
: std::span<const unsigned char>{};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::span<unsigned char> writable() noexcept
|
||||
{
|
||||
return m_data ? std::span<unsigned char>{m_data, m_size}
|
||||
: std::span<unsigned char>{};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view string_view() const noexcept
|
||||
{
|
||||
return m_data ? std::string_view{
|
||||
reinterpret_cast<const char*>(m_data),
|
||||
m_size}
|
||||
: std::string_view{};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept { return m_size; }
|
||||
[[nodiscard]] bool empty() const noexcept { return m_size == 0; }
|
||||
[[nodiscard]] bool is_locked() const noexcept { return m_locked; }
|
||||
|
||||
void clear() noexcept;
|
||||
|
||||
/// Total bytes wiped across SecureBuffer lifetimes (for
|
||||
/// sanitizer-safe wipe verification in tests).
|
||||
[[nodiscard]] static std::uint64_t total_wiped_bytes() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
unsigned char* m_data{nullptr};
|
||||
std::size_t m_size{0};
|
||||
bool m_locked{false};
|
||||
};
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
@@ -23,6 +24,14 @@ namespace Void::Security
|
||||
inline constexpr std::size_t secret_authentication_bytes = 16;
|
||||
using SecretKey = std::array<unsigned char, secret_key_bytes>;
|
||||
|
||||
/// Wipe a mutable byte buffer with sodium_memzero.
|
||||
void wipe_bytes(std::span<unsigned char> buffer) noexcept;
|
||||
|
||||
/// Constant-time comparison using sodium_memcmp.
|
||||
[[nodiscard]] bool
|
||||
constant_time_equal(std::span<const unsigned char> lhs,
|
||||
std::span<const unsigned char> rhs) noexcept;
|
||||
|
||||
/// Generate a URL-safe, unpadded token containing `entropy_bytes` of
|
||||
/// cryptographically secure randomness.
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
@@ -44,6 +53,18 @@ namespace Void::Security
|
||||
std::string_view password,
|
||||
PasswordHashStrength strength = PasswordHashStrength::Moderate);
|
||||
|
||||
/// Parse Argon2id cost parameters (`$argon2id$v=19$m=...,t=...,p=...$...`)
|
||||
/// without executing Argon2id or allocating memory.
|
||||
[[nodiscard]] Void::Result::Result<Argon2idCost>
|
||||
parse_argon2id_cost(std::string_view encoded_hash);
|
||||
|
||||
/// Verify a password against an encoded Argon2id hash after enforcing input
|
||||
/// caps and operator-approved memory/iteration/parallelism cost budgets.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
verify_password_budgeted(std::string_view password,
|
||||
std::string_view encoded_hash,
|
||||
const PasswordVerifyBudget& budget = {});
|
||||
|
||||
/// Verify a password against a libsodium Argon2id encoded hash.
|
||||
/// Malformed hashes are treated as a non-match.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
@@ -53,8 +74,8 @@ namespace Void::Security
|
||||
/// Generate a cryptographically random key for local secret encryption.
|
||||
[[nodiscard]] Void::Result::Result<SecretKey> random_secret_key();
|
||||
|
||||
/// Encrypt and authenticate bytes. The returned portable envelope is
|
||||
/// nonce || ciphertext || authentication tag.
|
||||
/// Encrypt and authenticate bytes using the legacy local secret format
|
||||
/// (24-byte nonce || crypto_secretbox_easy combined MAC + ciphertext).
|
||||
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
|
||||
seal_secret(std::span<const unsigned char> plaintext,
|
||||
const SecretKey& key);
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
struct SecurityLimits {
|
||||
static constexpr std::size_t kMaxPasswordBytes = 1024;
|
||||
static constexpr std::size_t kMaxEncodedHashBytes = 1024;
|
||||
static constexpr std::size_t kMaxTokenBytes = 512;
|
||||
static constexpr std::size_t kMaxSecretPlaintextBytes =
|
||||
16ULL * 1024ULL * 1024ULL;
|
||||
static constexpr std::size_t kMaxKeyIdBytes = 128;
|
||||
static constexpr std::size_t kMaxAadBytes = 64ULL * 1024ULL;
|
||||
static constexpr std::size_t kMaxRolesPerPrincipal = 64;
|
||||
static constexpr std::size_t kMaxPolicyRules = 4096;
|
||||
static constexpr std::size_t kMaxPredicateDepth = 16;
|
||||
static constexpr std::size_t kDefaultPasswordJobMemoryBudgetBytes =
|
||||
512ULL * 1024ULL * 1024ULL;
|
||||
static constexpr std::size_t kDefaultMaxConcurrentPasswordJobs = 2;
|
||||
static constexpr std::size_t kDefaultMaxWaitingPasswordJobs = 32;
|
||||
static constexpr std::size_t kDefaultMaxTotalSessions = 10000;
|
||||
static constexpr std::size_t kDefaultMaxSessionsPerSubject = 16;
|
||||
static constexpr std::chrono::seconds kDefaultSessionTtl{3600};
|
||||
static constexpr std::chrono::seconds
|
||||
kDefaultClockRollbackTolerance{60};
|
||||
static constexpr std::size_t kDefaultExpiryCleanupBatch = 256;
|
||||
};
|
||||
|
||||
enum class SecurityErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
input_too_large = 2,
|
||||
malformed_hash = 3,
|
||||
cost_budget_exceeded = 4,
|
||||
authentication_failed = 5,
|
||||
denied = 6,
|
||||
rate_limited = 7,
|
||||
session_expired = 8,
|
||||
session_revoked = 9,
|
||||
session_capacity_exceeded = 10,
|
||||
clock_rollback = 11,
|
||||
conflict = 12,
|
||||
key_not_found = 13,
|
||||
key_in_use = 14,
|
||||
unsupported_version = 15,
|
||||
policy_invalid = 16,
|
||||
audit_failed = 17,
|
||||
locked_memory_unavailable = 18,
|
||||
backend_error = 19,
|
||||
store_unavailable = 20,
|
||||
cancelled = 21,
|
||||
timeout = 22,
|
||||
overloaded = 23,
|
||||
closed = 24
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_security_error(SecurityErrorCode code, std::string message = {},
|
||||
std::error_code sys_err = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case SecurityErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SecurityErrorCode::invalid_argument:
|
||||
case SecurityErrorCode::input_too_large:
|
||||
case SecurityErrorCode::policy_invalid:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case SecurityErrorCode::malformed_hash:
|
||||
case SecurityErrorCode::authentication_failed:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case SecurityErrorCode::cost_budget_exceeded:
|
||||
case SecurityErrorCode::session_capacity_exceeded:
|
||||
case SecurityErrorCode::locked_memory_unavailable:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case SecurityErrorCode::denied:
|
||||
case SecurityErrorCode::session_expired:
|
||||
case SecurityErrorCode::session_revoked:
|
||||
case SecurityErrorCode::clock_rollback:
|
||||
case SecurityErrorCode::conflict:
|
||||
case SecurityErrorCode::key_in_use:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case SecurityErrorCode::rate_limited:
|
||||
case SecurityErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case SecurityErrorCode::key_not_found:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case SecurityErrorCode::unsupported_version:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case SecurityErrorCode::audit_failed:
|
||||
case SecurityErrorCode::backend_error:
|
||||
case SecurityErrorCode::store_unavailable:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SecurityErrorCode::cancelled:
|
||||
case SecurityErrorCode::closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case SecurityErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
}
|
||||
|
||||
const ErrorCode domain_code{Void::Result::kSecurityErrorDomain,
|
||||
static_cast<std::int32_t>(code)};
|
||||
return Error{kind, std::move(message), domain_code, sys_err};
|
||||
}
|
||||
|
||||
struct Argon2idCost {
|
||||
std::uint32_t version{19};
|
||||
std::uint64_t memory_kib{0};
|
||||
std::uint64_t iterations{0};
|
||||
std::uint32_t parallelism{0};
|
||||
|
||||
[[nodiscard]] std::optional<std::uint64_t>
|
||||
memory_bytes() const noexcept
|
||||
{
|
||||
if (memory_kib >
|
||||
std::numeric_limits<std::uint64_t>::max() / 1024ULL) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return memory_kib * 1024ULL;
|
||||
}
|
||||
};
|
||||
|
||||
struct PasswordVerifyBudget {
|
||||
std::uint64_t max_memory_bytes{256ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t max_iterations{16};
|
||||
std::uint32_t max_parallelism{4};
|
||||
};
|
||||
|
||||
enum class FaultOperation : std::uint8_t {
|
||||
none = 0,
|
||||
any,
|
||||
sodium_init,
|
||||
random_bytes,
|
||||
locked_alloc,
|
||||
password_hash,
|
||||
secret_seal,
|
||||
secret_open
|
||||
};
|
||||
|
||||
struct FaultConfig {
|
||||
FaultOperation op{FaultOperation::none};
|
||||
SecurityErrorCode code{SecurityErrorCode::backend_error};
|
||||
std::size_t fail_after{0};
|
||||
};
|
||||
|
||||
class ScopedFaultGuard
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ScopedFaultGuard(FaultConfig config) noexcept;
|
||||
~ScopedFaultGuard() noexcept;
|
||||
|
||||
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
|
||||
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
FaultConfig m_previous{};
|
||||
std::size_t m_previous_hits{0};
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
[[nodiscard]] std::optional<Void::Result::Error>
|
||||
maybe_inject_fault(FaultOperation op, std::string_view operation);
|
||||
} // namespace Detail
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -26,6 +26,60 @@ namespace Void::Service
|
||||
|
||||
inline constexpr const char* kServiceSymbol = "void_plugin_service";
|
||||
|
||||
/// Acquire an owning ServiceHandle<I> directly from a PluginManager entry,
|
||||
/// pinning the exact PluginHandle so the shared object stays mapped until
|
||||
/// every copy of the returned handle is destroyed.
|
||||
template <typename I>
|
||||
[[nodiscard]] Void::Result::Result<ServiceHandle<I>>
|
||||
acquire_plugin_service(Plugin::PluginManager& manager,
|
||||
std::string_view plugin_name,
|
||||
PublicationEpoch epoch = 0)
|
||||
{
|
||||
static_assert(std::is_base_of_v<IService, I>,
|
||||
"plugin service interface must derive IService");
|
||||
auto handle = manager.acquire(plugin_name);
|
||||
if (!handle) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
std::string{"ServicePlugin: plugin '"} +
|
||||
std::string{plugin_name} + "' is not loaded"));
|
||||
}
|
||||
auto* factory = reinterpret_cast<service_factory_fn>(
|
||||
handle.raw_symbol(kServiceSymbol));
|
||||
if (factory == nullptr) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
std::string{"ServicePlugin: plugin '"} +
|
||||
std::string{plugin_name} + "' does not export " +
|
||||
kServiceSymbol));
|
||||
}
|
||||
IService* base = nullptr;
|
||||
try {
|
||||
base = factory(handle.get());
|
||||
} catch (const std::exception& ex) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::internal, ex.what()));
|
||||
} catch (...) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::internal,
|
||||
"ServicePlugin: service factory threw"));
|
||||
}
|
||||
if (base == nullptr) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
"ServicePlugin: service factory returned null"));
|
||||
}
|
||||
I* iface = dynamic_cast<I*>(base);
|
||||
if (iface == nullptr) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::invalid_argument,
|
||||
"ServicePlugin: incompatible service interface"));
|
||||
}
|
||||
auto owner = std::make_shared<Plugin::PluginHandle>(std::move(handle));
|
||||
std::shared_ptr<void> pinned(std::move(owner), iface);
|
||||
return ServiceHandle<I>{iface, std::move(pinned), nullptr, epoch};
|
||||
}
|
||||
|
||||
/// Binds a plugin-provided service (interface I) into a ServiceRegistry
|
||||
/// and keeps it bound across hot reloads: after each reload the new
|
||||
/// instance's service (carrying state migrated by the plugin's v2 ABI)
|
||||
@@ -174,35 +228,14 @@ namespace Void::Service
|
||||
[[nodiscard]] bool bind_locked() noexcept
|
||||
{
|
||||
try {
|
||||
auto handle = m_manager->acquire(m_name);
|
||||
if (!handle) {
|
||||
auto svc_handle = acquire_plugin_service<I>(
|
||||
*m_manager, m_name);
|
||||
if (!svc_handle) {
|
||||
Void::Log::warn("Service.Plugin", "{}",
|
||||
svc_handle.error().message());
|
||||
return false;
|
||||
}
|
||||
auto* factory =
|
||||
reinterpret_cast<service_factory_fn>(
|
||||
handle.raw_symbol(kServiceSymbol));
|
||||
if (factory == nullptr) {
|
||||
return false;
|
||||
}
|
||||
IService* base = factory(handle.get());
|
||||
if (base == nullptr) {
|
||||
return false;
|
||||
}
|
||||
I* iface = dynamic_cast<I*>(base);
|
||||
if (iface == nullptr) {
|
||||
Void::Log::warn(
|
||||
"Service.Plugin",
|
||||
"plugin '{}' exported an incompatible "
|
||||
"service interface",
|
||||
m_name);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pin the exact instance and shared object that
|
||||
// supplied the factory and service subobject.
|
||||
auto owner = std::make_shared<Plugin::PluginHandle>(
|
||||
std::move(handle));
|
||||
std::shared_ptr<I> pinned(std::move(owner), iface);
|
||||
auto pinned = svc_handle->shared();
|
||||
if (m_validator && !m_validator(pinned)) {
|
||||
Void::Log::warn(
|
||||
"Service.Plugin",
|
||||
|
||||
+394
-109
@@ -1,16 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/Service/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Service
|
||||
@@ -25,92 +32,297 @@ namespace Void::Service
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Type-keyed service container: providers register an implementation
|
||||
/// against an interface type, consumers resolve by that interface and
|
||||
/// never name the concrete type — the core of the dependency-inversion
|
||||
/// the orchestrator and FSMs rely on.
|
||||
class ServiceRegistry;
|
||||
|
||||
namespace detail
|
||||
{
|
||||
struct RetentionEntry {
|
||||
PublicationEpoch epoch{0};
|
||||
std::weak_ptr<const void> token{};
|
||||
std::string label{};
|
||||
};
|
||||
|
||||
struct RetentionState;
|
||||
|
||||
struct LifecycleNode {
|
||||
std::string id{};
|
||||
const void* object_key{nullptr};
|
||||
std::shared_ptr<void> owner{};
|
||||
IService* service{nullptr};
|
||||
IManagedService* managed{nullptr};
|
||||
std::size_t seq{0};
|
||||
std::vector<std::size_t> dep_indices{};
|
||||
};
|
||||
|
||||
struct SnapshotEntry {
|
||||
std::shared_ptr<void> impl{}; // holds provider (+ optional pin)
|
||||
IService* service{nullptr};
|
||||
std::string id{};
|
||||
};
|
||||
|
||||
struct SnapshotData {
|
||||
PublicationEpoch epoch{0};
|
||||
std::shared_ptr<const void> gen_token{};
|
||||
std::unordered_map<std::type_index, SnapshotEntry> services{};
|
||||
std::vector<std::type_index> legacy_order{};
|
||||
std::vector<LifecycleNode> lifecycle_nodes{};
|
||||
std::shared_ptr<const SnapshotData> parent_snap{};
|
||||
const ServiceRegistry* live_parent{nullptr};
|
||||
};
|
||||
} // namespace detail
|
||||
|
||||
/// Immutable, self-retaining point-in-time view of a ServiceRegistry
|
||||
/// (and any snapshot-captured parent chain). Safe to hold after the source
|
||||
/// registry is modified or destroyed.
|
||||
class ServiceSnapshot
|
||||
{
|
||||
public:
|
||||
|
||||
ServiceSnapshot() = default;
|
||||
|
||||
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
||||
{
|
||||
const detail::SnapshotData* cur = m_data.get();
|
||||
std::size_t depth = 0;
|
||||
while (cur != nullptr && depth <= m_max_parent_levels) {
|
||||
const auto it =
|
||||
cur->services.find(std::type_index{typeid(I)});
|
||||
if (it != cur->services.end()) {
|
||||
return std::static_pointer_cast<I>(it->second.impl);
|
||||
}
|
||||
cur = cur->parent_snap.get();
|
||||
++depth;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template <typename I> [[nodiscard]] bool has() const
|
||||
{
|
||||
return get<I>() != nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] PublicationEpoch epoch() const noexcept
|
||||
{
|
||||
return m_data ? m_data->epoch : 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept
|
||||
{
|
||||
return m_data ? m_data->services.size() : 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_data != nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
friend class ServiceRegistry;
|
||||
explicit ServiceSnapshot(std::shared_ptr<const detail::SnapshotData> data,
|
||||
std::size_t max_parent_levels = 16) noexcept
|
||||
: m_data(std::move(data)),
|
||||
m_max_parent_levels(max_parent_levels)
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<const detail::SnapshotData> m_data{};
|
||||
std::size_t m_max_parent_levels{16};
|
||||
};
|
||||
|
||||
/// Staged description of a coherent batch of services and their dependency
|
||||
/// graph, ready to be validated by ServiceRegistry::prepare_batch().
|
||||
class ProviderSet
|
||||
{
|
||||
public:
|
||||
|
||||
struct StagedItem {
|
||||
std::type_index interface_type;
|
||||
std::string id{};
|
||||
std::shared_ptr<void> owner{};
|
||||
const void* object_key{nullptr};
|
||||
IService* service{nullptr};
|
||||
IManagedService* managed{nullptr};
|
||||
std::vector<std::type_index> required_deps{};
|
||||
std::vector<std::type_index> optional_deps{};
|
||||
};
|
||||
|
||||
template <typename I>
|
||||
ProviderSet& add(
|
||||
std::string id,
|
||||
std::shared_ptr<I> impl,
|
||||
std::vector<std::type_index> required_deps = {},
|
||||
std::vector<std::type_index> optional_deps = {},
|
||||
ServicePin pin = {})
|
||||
{
|
||||
StagedItem item{.interface_type = std::type_index{typeid(I)},
|
||||
.id = std::move(id),
|
||||
.owner = pack_owner(impl, std::move(pin)),
|
||||
.object_key = impl.get(),
|
||||
.service = extract_service(impl.get()),
|
||||
.managed = extract_managed(impl.get()),
|
||||
.required_deps = std::move(required_deps),
|
||||
.optional_deps = std::move(optional_deps)};
|
||||
m_items.push_back(std::move(item));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename AliasI>
|
||||
ProviderSet& add_alias(
|
||||
std::string id,
|
||||
std::shared_ptr<AliasI> impl,
|
||||
std::vector<std::type_index> required_deps = {},
|
||||
std::vector<std::type_index> optional_deps = {},
|
||||
ServicePin pin = {})
|
||||
{
|
||||
return add<AliasI>(std::move(id), std::move(impl),
|
||||
std::move(required_deps),
|
||||
std::move(optional_deps), std::move(pin));
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::vector<StagedItem>& items() const noexcept
|
||||
{
|
||||
return m_items;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
template <typename I>
|
||||
static std::shared_ptr<void> pack_owner(const std::shared_ptr<I>& impl,
|
||||
ServicePin pin)
|
||||
{
|
||||
if (!impl) {
|
||||
return nullptr;
|
||||
}
|
||||
if (!pin) {
|
||||
return std::shared_ptr<void>(impl, impl.get());
|
||||
}
|
||||
struct PinnedBox {
|
||||
std::shared_ptr<void> impl;
|
||||
ServicePin pin;
|
||||
};
|
||||
auto box = std::make_shared<PinnedBox>(
|
||||
PinnedBox{std::shared_ptr<void>(impl, impl.get()),
|
||||
std::move(pin)});
|
||||
return std::shared_ptr<void>(std::move(box), impl.get());
|
||||
}
|
||||
|
||||
template <typename I> static IService* extract_service(I* raw)
|
||||
{
|
||||
if (raw == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
if constexpr (std::is_base_of_v<IService, I>) {
|
||||
return static_cast<IService*>(raw);
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
return dynamic_cast<IService*>(raw);
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename I>
|
||||
static IManagedService* extract_managed(I* raw)
|
||||
{
|
||||
if (raw == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
if constexpr (std::is_base_of_v<IManagedService, I>) {
|
||||
return static_cast<IManagedService*>(raw);
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
return dynamic_cast<IManagedService*>(raw);
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<StagedItem> m_items{};
|
||||
};
|
||||
|
||||
/// Validated, topologically ordered candidate batch returned by
|
||||
/// ServiceRegistry::prepare_batch().
|
||||
struct PreparedPublication {
|
||||
ExpectedEpoch expected_epoch{};
|
||||
std::shared_ptr<detail::SnapshotData> snapshot{};
|
||||
bool valid{false};
|
||||
bool started{false};
|
||||
bool aborted{false};
|
||||
};
|
||||
|
||||
/// Thread-safe, snapshot-published service container supporting both
|
||||
/// legacy single-service mutations (`provide`/`get`/`require`) and
|
||||
/// transactional DAG lifecycle publication (`acquire`/`prepare_batch`/
|
||||
/// `start_staged`/`publish`/`close_and_join`).
|
||||
///
|
||||
/// registry.provide<IClock>(std::make_shared<SystemClock>());
|
||||
/// auto& clock = registry.require<IClock>(); // no SystemClock dep
|
||||
///
|
||||
/// Thread-safe. Reads (get/require/has) take a shared lock; they are
|
||||
/// the hot path for running FSMs resolving services per step.
|
||||
/// Note: `require<I>()` returns an unpinned reference after unlocking and is
|
||||
/// kept for legacy compatibility; new code and coroutines should use
|
||||
/// `acquire<I>()` and retain the returned `ServiceHandle<I>` across calls
|
||||
/// and `co_await` suspension points.
|
||||
class ServiceRegistry
|
||||
{
|
||||
public:
|
||||
|
||||
ServiceRegistry() = default;
|
||||
ServiceRegistry();
|
||||
explicit ServiceRegistry(const ServiceRegistry* parent);
|
||||
explicit ServiceRegistry(
|
||||
ServiceLimits limits,
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
~ServiceRegistry();
|
||||
|
||||
ServiceRegistry(const ServiceRegistry&) = delete;
|
||||
ServiceRegistry& operator=(const ServiceRegistry&) = delete;
|
||||
|
||||
/// Create a scoped child registry that overlays `parent`: lookups
|
||||
/// fall through to the parent when a key is not provided locally,
|
||||
/// and a local provide<I>() shadows the parent's entry. Lifecycle
|
||||
/// (start_all/stop_all) covers only locally-provided services. The
|
||||
/// parent must outlive this registry.
|
||||
explicit ServiceRegistry(const ServiceRegistry* parent)
|
||||
: m_parent{parent}
|
||||
{
|
||||
}
|
||||
/// Construct a child registry retaining an immutable parent
|
||||
/// snapshot so lookups survive destruction of the parent registry.
|
||||
[[nodiscard]] static Void::Result::Result<
|
||||
std::unique_ptr<ServiceRegistry>>
|
||||
from_parent_snapshot(
|
||||
ServiceSnapshot parent,
|
||||
ServiceLimits limits = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
|
||||
/// Explicitly refresh snapshot-based parent linkage from `parent`.
|
||||
void refresh_parent(const ServiceRegistry& parent);
|
||||
|
||||
/// Capture an immutable point-in-time snapshot.
|
||||
[[nodiscard]] ServiceSnapshot snapshot() const;
|
||||
|
||||
// ── Legacy compatible API ─────────────────────────────────────
|
||||
|
||||
/// Register (or replace) the implementation for interface I.
|
||||
/// If I derives IService, the instance joins the lifecycle.
|
||||
template <typename I> void provide(std::shared_ptr<I> impl)
|
||||
{
|
||||
Entry entry;
|
||||
entry.impl = std::shared_ptr<void>(impl, impl.get());
|
||||
if constexpr (std::is_base_of_v<IService, I>) {
|
||||
entry.service = static_cast<IService*>(impl.get());
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
// The interface I doesn't derive IService, but the
|
||||
// concrete implementation might — recover the lifecycle
|
||||
// aspect by cross-cast. (dynamic_cast requires a
|
||||
// polymorphic I.)
|
||||
entry.service = dynamic_cast<IService*>(impl.get());
|
||||
} else {
|
||||
// A plain, non-polymorphic service type: storable and
|
||||
// resolvable, but has no IService lifecycle aspect.
|
||||
entry.service = nullptr;
|
||||
}
|
||||
const std::type_index key{typeid(I)};
|
||||
std::unique_lock lock{m_mutex};
|
||||
if (!m_services.contains(key)) {
|
||||
m_order.push_back(key);
|
||||
}
|
||||
m_services.insert_or_assign(key, std::move(entry));
|
||||
}
|
||||
|
||||
/// Withdraw the implementation for interface I from this registry
|
||||
/// (a parent's entry is unaffected: later lookups fall through to
|
||||
/// it again). Consumers still holding the shared_ptr keep the
|
||||
/// instance alive; only new lookups miss. Returns true when an
|
||||
/// entry was removed.
|
||||
template <typename I> bool remove()
|
||||
{
|
||||
const std::type_index key{typeid(I)};
|
||||
std::unique_lock lock{m_mutex};
|
||||
if (m_services.erase(key) == 0) {
|
||||
return false;
|
||||
}
|
||||
std::erase(m_order, key);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Resolve I, or nullptr if not provided. Falls through to the
|
||||
/// parent registry (if any) on a local miss.
|
||||
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
|
||||
{
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
const auto it = m_services.find(std::type_index{typeid(I)});
|
||||
if (it != m_services.end()) {
|
||||
return std::static_pointer_cast<I>(it->second.impl);
|
||||
IService* svc = nullptr;
|
||||
if (impl) {
|
||||
if constexpr (std::is_base_of_v<IService, I>) {
|
||||
svc = static_cast<IService*>(impl.get());
|
||||
} else if constexpr (std::is_polymorphic_v<I>) {
|
||||
svc = dynamic_cast<IService*>(impl.get());
|
||||
}
|
||||
}
|
||||
return m_parent ? m_parent->get<I>() : nullptr;
|
||||
provide_erased(
|
||||
std::type_index{typeid(I)},
|
||||
impl ? std::shared_ptr<void>(impl, impl.get())
|
||||
: std::shared_ptr<void>{},
|
||||
impl.get(), svc);
|
||||
}
|
||||
|
||||
template <typename I> bool remove()
|
||||
{
|
||||
return remove_erased(std::type_index{typeid(I)});
|
||||
}
|
||||
|
||||
template <typename I>
|
||||
[[nodiscard]] std::shared_ptr<I> get() const
|
||||
{
|
||||
auto h = acquire<I>();
|
||||
if (!h) {
|
||||
return nullptr;
|
||||
}
|
||||
return h->shared();
|
||||
}
|
||||
|
||||
/// Resolve I; throws std::runtime_error if not provided.
|
||||
template <typename I> [[nodiscard]] I& require() const
|
||||
{
|
||||
auto p = get<I>();
|
||||
@@ -124,55 +336,128 @@ namespace Void::Service
|
||||
|
||||
template <typename I> [[nodiscard]] bool has() const
|
||||
{
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
if (m_services.contains(std::type_index{typeid(I)})) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return m_parent ? m_parent->has<I>() : false;
|
||||
return acquire<I>().has_value();
|
||||
}
|
||||
|
||||
/// Call on_start() on every lifecycle service, registration
|
||||
/// Run on_start() outside registry locks in registration/dependency
|
||||
/// order.
|
||||
void start_all()
|
||||
void start_all();
|
||||
|
||||
/// Run on_stop() outside registry locks in reverse order.
|
||||
void stop_all();
|
||||
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
|
||||
// ── Hardened owning & transactional lifecycle API ───────────────
|
||||
|
||||
template <typename I>
|
||||
[[nodiscard]] Void::Result::Result<ServiceHandle<I>> acquire() const
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
for (const auto& key : m_order) {
|
||||
if (auto* s = m_services.at(key).service) {
|
||||
s->on_start();
|
||||
}
|
||||
auto snap = acquire_snapshot();
|
||||
if (!snap) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry: registry is stopping"));
|
||||
}
|
||||
return acquire_from_snapshot<I>(*snap, 0);
|
||||
}
|
||||
|
||||
/// Call on_stop() on every lifecycle service, reverse order.
|
||||
void stop_all()
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
for (auto it = m_order.rbegin(); it != m_order.rend(); ++it) {
|
||||
if (auto* s = m_services.at(*it).service) {
|
||||
s->on_stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
[[nodiscard]] Void::Result::Result<PreparedPublication>
|
||||
prepare_batch(ProviderSet set,
|
||||
ExpectedEpoch expected = std::nullopt);
|
||||
|
||||
[[nodiscard]] std::size_t size() const
|
||||
{
|
||||
std::shared_lock lock{m_mutex};
|
||||
return m_services.size();
|
||||
}
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
start_staged(PreparedPublication& prepared,
|
||||
Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<PublicationEpoch>
|
||||
publish(PreparedPublication&& prepared);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<PublicationEpoch>
|
||||
start_and_publish(ProviderSet set,
|
||||
ExpectedEpoch expected = std::nullopt,
|
||||
Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
start(Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<ShutdownReport>
|
||||
close_and_join(Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] PublicationEpoch epoch() const noexcept;
|
||||
[[nodiscard]] std::size_t retained_generation_count() const;
|
||||
[[nodiscard]] bool is_stopping() const noexcept;
|
||||
|
||||
using ObserverCallback =
|
||||
std::function<void(const ServiceObservation&)>;
|
||||
std::size_t add_observer(ObserverCallback cb);
|
||||
void remove_observer(std::size_t id);
|
||||
|
||||
private:
|
||||
|
||||
struct Entry {
|
||||
std::shared_ptr<void> impl;
|
||||
IService* service = nullptr; // non-null iff I : IService
|
||||
};
|
||||
void provide_erased(std::type_index key, std::shared_ptr<void> impl,
|
||||
const void* object_key, IService* service);
|
||||
bool remove_erased(std::type_index key);
|
||||
std::shared_ptr<const detail::SnapshotData> acquire_snapshot() const;
|
||||
|
||||
const ServiceRegistry* m_parent = nullptr;
|
||||
mutable std::shared_mutex m_mutex;
|
||||
std::unordered_map<std::type_index, Entry> m_services;
|
||||
std::vector<std::type_index> m_order;
|
||||
template <typename I>
|
||||
[[nodiscard]] Void::Result::Result<ServiceHandle<I>>
|
||||
acquire_from_snapshot(const detail::SnapshotData& snap,
|
||||
std::size_t depth) const
|
||||
{
|
||||
if (depth > m_limits.max_parent_levels) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::overloaded,
|
||||
"ServiceRegistry: parent depth limit exceeded"));
|
||||
}
|
||||
const auto it =
|
||||
snap.services.find(std::type_index{typeid(I)});
|
||||
if (it != snap.services.end()) {
|
||||
auto* raw = static_cast<I*>(it->second.impl.get());
|
||||
return ServiceHandle<I>{raw, it->second.impl,
|
||||
snap.gen_token, snap.epoch};
|
||||
}
|
||||
if (snap.parent_snap) {
|
||||
return acquire_from_snapshot<I>(*snap.parent_snap,
|
||||
depth + 1);
|
||||
}
|
||||
if (snap.live_parent != nullptr) {
|
||||
auto parent_snap = snap.live_parent->acquire_snapshot();
|
||||
if (!parent_snap) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::service_stopping,
|
||||
"ServiceRegistry: parent registry is stopping"));
|
||||
}
|
||||
return acquire_from_snapshot<I>(*parent_snap, depth + 1);
|
||||
}
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::missing_service,
|
||||
std::string{"ServiceRegistry: no service for '"} +
|
||||
typeid(I).name() + "'"));
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> rollback_started_nodes(
|
||||
const std::vector<detail::LifecycleNode>& nodes,
|
||||
std::size_t count, const Void::Result::Error& primary_error);
|
||||
|
||||
void notify_observers(const ServiceObservation& obs);
|
||||
[[nodiscard]] std::size_t prune_and_count_retained_locked();
|
||||
|
||||
ServiceLimits m_limits{};
|
||||
const Void::Time::MonotonicClock* m_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
std::shared_ptr<detail::RetentionState> m_retention_state;
|
||||
|
||||
mutable std::mutex m_write_mu{};
|
||||
mutable std::mutex m_snapshot_mu{};
|
||||
std::shared_ptr<const detail::SnapshotData> m_active_snapshot{};
|
||||
PublicationEpoch m_epoch{0};
|
||||
bool m_stopping{false};
|
||||
bool m_started{false};
|
||||
|
||||
mutable std::mutex m_observer_mu{};
|
||||
std::vector<std::pair<std::size_t, ObserverCallback>> m_observers{};
|
||||
std::size_t m_next_observer_id{1};
|
||||
};
|
||||
|
||||
} // namespace Void::Service
|
||||
@@ -0,0 +1,227 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Service
|
||||
{
|
||||
enum class ServiceErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
missing_service = 2,
|
||||
conflict = 3,
|
||||
duplicate_interface = 4,
|
||||
cycle_detected = 5,
|
||||
missing_dependency = 6,
|
||||
start_failed = 7,
|
||||
not_ready = 8,
|
||||
stop_failed = 9,
|
||||
service_stopping = 10,
|
||||
cancelled = 11,
|
||||
timeout = 12,
|
||||
overloaded = 13,
|
||||
retention_limit = 14,
|
||||
internal = 15,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_service_error(ServiceErrorCode code, std::string message = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case ServiceErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case ServiceErrorCode::invalid_argument:
|
||||
case ServiceErrorCode::cycle_detected:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case ServiceErrorCode::missing_service:
|
||||
case ServiceErrorCode::missing_dependency:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case ServiceErrorCode::conflict:
|
||||
case ServiceErrorCode::duplicate_interface:
|
||||
case ServiceErrorCode::service_stopping:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case ServiceErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case ServiceErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case ServiceErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case ServiceErrorCode::retention_limit:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case ServiceErrorCode::start_failed:
|
||||
case ServiceErrorCode::not_ready:
|
||||
case ServiceErrorCode::stop_failed:
|
||||
case ServiceErrorCode::internal:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
}
|
||||
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kServiceErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct ServiceLimits {
|
||||
std::size_t max_providers{256};
|
||||
std::size_t max_parent_levels{16};
|
||||
std::size_t max_dependency_edges{1024};
|
||||
std::size_t max_staged_changes{64};
|
||||
std::size_t max_lifecycle_requests{128};
|
||||
std::size_t max_retained_generations{4};
|
||||
};
|
||||
|
||||
using PublicationEpoch = std::uint64_t;
|
||||
using ExpectedEpoch = std::optional<PublicationEpoch>;
|
||||
using ServicePin = std::shared_ptr<const void>;
|
||||
|
||||
enum class LifecyclePhase : std::uint8_t {
|
||||
Constructed = 0,
|
||||
Starting,
|
||||
Ready,
|
||||
Stopping,
|
||||
Stopped,
|
||||
Failed,
|
||||
};
|
||||
|
||||
enum class ServiceHealthStatus : std::uint8_t {
|
||||
Unknown = 0,
|
||||
Healthy,
|
||||
Degraded,
|
||||
Unhealthy,
|
||||
};
|
||||
|
||||
struct ServiceHealth {
|
||||
ServiceHealthStatus status{ServiceHealthStatus::Unknown};
|
||||
std::string detail{};
|
||||
};
|
||||
|
||||
struct ServiceObservation {
|
||||
PublicationEpoch epoch{0};
|
||||
std::size_t provider_count{0};
|
||||
std::size_t retained_generations{0};
|
||||
std::uint64_t duration_ns{0};
|
||||
bool rollback{false};
|
||||
std::string detail{};
|
||||
};
|
||||
|
||||
struct ShutdownReport {
|
||||
std::vector<std::string> stopped_services{};
|
||||
std::vector<std::string> incomplete_owners{};
|
||||
std::vector<Void::Result::Error> stop_errors{};
|
||||
|
||||
[[nodiscard]] bool clean() const noexcept
|
||||
{
|
||||
return incomplete_owners.empty() && stop_errors.empty();
|
||||
}
|
||||
};
|
||||
|
||||
/// Extended lifecycle contract with checked failure/readiness reporting and
|
||||
/// abort cleanup on partial startup failure.
|
||||
class IManagedService : public IService
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void> start_checked()
|
||||
{
|
||||
try {
|
||||
on_start();
|
||||
return {};
|
||||
} catch (const std::exception& ex) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::start_failed, ex.what()));
|
||||
} catch (...) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::start_failed,
|
||||
"service start threw unknown exception"));
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
check_readiness() const
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
virtual void abort_start() noexcept {}
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void> stop_checked()
|
||||
{
|
||||
try {
|
||||
on_stop();
|
||||
return {};
|
||||
} catch (const std::exception& ex) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::stop_failed, ex.what()));
|
||||
} catch (...) {
|
||||
return Void::Result::fail(make_service_error(
|
||||
ServiceErrorCode::stop_failed,
|
||||
"service stop threw unknown exception"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/// Owning lease to a resolved provider record: keeps the provider object,
|
||||
/// any external code/resource pin, and its publication generation token alive
|
||||
/// across removal, replacement, parent destruction, and coroutine suspension.
|
||||
template <typename I> class ServiceHandle
|
||||
{
|
||||
public:
|
||||
|
||||
ServiceHandle() noexcept = default;
|
||||
|
||||
ServiceHandle(I* ptr, std::shared_ptr<void> owner,
|
||||
std::shared_ptr<const void> gen_token,
|
||||
PublicationEpoch epoch) noexcept
|
||||
: m_ptr(ptr), m_owner(std::move(owner)),
|
||||
m_gen_token(std::move(gen_token)), m_epoch(epoch)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] I* operator->() const noexcept { return m_ptr; }
|
||||
[[nodiscard]] I& operator*() const noexcept { return *m_ptr; }
|
||||
[[nodiscard]] I* get() const noexcept { return m_ptr; }
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return m_ptr != nullptr;
|
||||
}
|
||||
[[nodiscard]] PublicationEpoch generation() const noexcept
|
||||
{
|
||||
return m_epoch;
|
||||
}
|
||||
[[nodiscard]] std::shared_ptr<I> shared() const noexcept
|
||||
{
|
||||
return std::shared_ptr<I>(m_owner, m_ptr);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
I* m_ptr{nullptr};
|
||||
std::shared_ptr<void> m_owner{};
|
||||
std::shared_ptr<const void> m_gen_token{};
|
||||
PublicationEpoch m_epoch{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Service
|
||||
@@ -0,0 +1,895 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::ShortUrl::V2
|
||||
{
|
||||
inline constexpr std::uint32_t kServiceVersionV2{2};
|
||||
inline constexpr std::uint32_t kRecordSchemaVersion{1};
|
||||
|
||||
enum class V2ErrorCode : std::int32_t {
|
||||
None = 0,
|
||||
InvalidRequest = 1,
|
||||
InvalidUrl = 2,
|
||||
InvalidKey = 3,
|
||||
InvalidExpiry = 4,
|
||||
Conflict = 5,
|
||||
NotFound = 6,
|
||||
Expired = 7,
|
||||
Revoked = 8,
|
||||
Unsupported = 9,
|
||||
Unauthorized = 10,
|
||||
RateLimited = 11,
|
||||
QuotaExceeded = 12,
|
||||
IdentityExpired = 13,
|
||||
StorageError = 14,
|
||||
UnknownOutcome = 15,
|
||||
ProviderError = 16,
|
||||
Timeout = 17,
|
||||
Unavailable = 18,
|
||||
ResponseTooLarge = 19,
|
||||
Internal = 20,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_shorturl_error(V2ErrorCode code, std::string message)
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case V2ErrorCode::None:
|
||||
case V2ErrorCode::Internal:
|
||||
case V2ErrorCode::ProviderError:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case V2ErrorCode::InvalidRequest:
|
||||
case V2ErrorCode::InvalidUrl:
|
||||
case V2ErrorCode::InvalidKey:
|
||||
case V2ErrorCode::InvalidExpiry:
|
||||
case V2ErrorCode::Unauthorized:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case V2ErrorCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case V2ErrorCode::Conflict:
|
||||
case V2ErrorCode::Expired:
|
||||
case V2ErrorCode::Revoked:
|
||||
case V2ErrorCode::IdentityExpired:
|
||||
case V2ErrorCode::UnknownOutcome:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case V2ErrorCode::Unsupported:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case V2ErrorCode::RateLimited:
|
||||
case V2ErrorCode::Unavailable:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case V2ErrorCode::QuotaExceeded:
|
||||
case V2ErrorCode::ResponseTooLarge:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case V2ErrorCode::StorageError:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case V2ErrorCode::Timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kShortUrlErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
[[nodiscard]] inline V2ErrorCode
|
||||
v2_error_code_from(const Void::Result::Error& err) noexcept
|
||||
{
|
||||
if (err.code().domain == Void::Result::kShortUrlErrorDomain) {
|
||||
return static_cast<V2ErrorCode>(err.code().value);
|
||||
}
|
||||
switch (err.kind()) {
|
||||
case Void::Result::ErrorKind::invalid_argument:
|
||||
return V2ErrorCode::InvalidRequest;
|
||||
case Void::Result::ErrorKind::not_found:
|
||||
return V2ErrorCode::NotFound;
|
||||
case Void::Result::ErrorKind::conflict:
|
||||
return V2ErrorCode::Conflict;
|
||||
case Void::Result::ErrorKind::timeout:
|
||||
return V2ErrorCode::Timeout;
|
||||
case Void::Result::ErrorKind::overloaded:
|
||||
return V2ErrorCode::Unavailable;
|
||||
case Void::Result::ErrorKind::unsupported:
|
||||
return V2ErrorCode::Unsupported;
|
||||
case Void::Result::ErrorKind::exhausted:
|
||||
return V2ErrorCode::QuotaExceeded;
|
||||
case Void::Result::ErrorKind::io:
|
||||
return V2ErrorCode::StorageError;
|
||||
default:
|
||||
return V2ErrorCode::Internal;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] inline V1::ErrorCode
|
||||
to_v1_error_code(V2ErrorCode code) noexcept
|
||||
{
|
||||
switch (code) {
|
||||
case V2ErrorCode::None: return V1::ErrorCode::none;
|
||||
case V2ErrorCode::InvalidRequest:
|
||||
case V2ErrorCode::InvalidKey:
|
||||
case V2ErrorCode::InvalidExpiry:
|
||||
case V2ErrorCode::IdentityExpired:
|
||||
return V1::ErrorCode::invalid_request;
|
||||
case V2ErrorCode::InvalidUrl: return V1::ErrorCode::invalid_url;
|
||||
case V2ErrorCode::Unsupported: return V1::ErrorCode::unsupported;
|
||||
case V2ErrorCode::NotFound: return V1::ErrorCode::not_found;
|
||||
case V2ErrorCode::Expired: return V1::ErrorCode::expired;
|
||||
case V2ErrorCode::Revoked: return V1::ErrorCode::revoked;
|
||||
case V2ErrorCode::Conflict: return V1::ErrorCode::conflict;
|
||||
case V2ErrorCode::Unauthorized: return V1::ErrorCode::unauthorized;
|
||||
case V2ErrorCode::RateLimited: return V1::ErrorCode::rate_limited;
|
||||
case V2ErrorCode::Timeout: return V1::ErrorCode::timeout;
|
||||
case V2ErrorCode::Unavailable:
|
||||
case V2ErrorCode::QuotaExceeded:
|
||||
return V1::ErrorCode::unavailable;
|
||||
case V2ErrorCode::StorageError: return V1::ErrorCode::storage;
|
||||
case V2ErrorCode::ResponseTooLarge:
|
||||
return V1::ErrorCode::response_too_large;
|
||||
case V2ErrorCode::ProviderError:
|
||||
case V2ErrorCode::UnknownOutcome:
|
||||
return V1::ErrorCode::provider_error;
|
||||
case V2ErrorCode::Internal: return V1::ErrorCode::internal_error;
|
||||
}
|
||||
return V1::ErrorCode::internal_error;
|
||||
}
|
||||
|
||||
enum class LinkState : std::uint8_t {
|
||||
Active = 1,
|
||||
Revoked = 2,
|
||||
};
|
||||
|
||||
struct LinkRecord {
|
||||
std::string key{};
|
||||
std::string target_url{};
|
||||
std::int64_t created_at_unix_seconds{0};
|
||||
std::int64_t expires_at_unix_seconds{0}; // 0 = permanent
|
||||
LinkState state{LinkState::Active};
|
||||
std::string operation_id{};
|
||||
std::uint32_t schema_version{kRecordSchemaVersion};
|
||||
};
|
||||
|
||||
struct IdempotencyRecord {
|
||||
std::string operation_id{};
|
||||
std::string key{};
|
||||
std::string target_url{};
|
||||
std::int64_t created_at_unix_seconds{0};
|
||||
std::int64_t retain_until_unix_seconds{0};
|
||||
};
|
||||
|
||||
struct Link {
|
||||
std::string key{};
|
||||
std::string short_url{};
|
||||
std::string target_url{};
|
||||
std::int64_t expires_at_unix_seconds{0};
|
||||
std::uint32_t retry_after_seconds{0};
|
||||
};
|
||||
|
||||
struct CreateLink {
|
||||
std::string target_url{};
|
||||
std::string custom_key{};
|
||||
std::int64_t expires_at_unix_seconds{0};
|
||||
};
|
||||
|
||||
struct ShortenOptions {
|
||||
std::string operation_id{};
|
||||
std::chrono::seconds idempotency_retention{std::chrono::hours{24}};
|
||||
};
|
||||
|
||||
struct LocalProviderLimits {
|
||||
std::size_t max_url_bytes{8192};
|
||||
std::size_t max_key_bytes{64};
|
||||
std::size_t generated_key_length{16};
|
||||
std::size_t max_collision_retries{8};
|
||||
std::size_t max_entries{100'000};
|
||||
std::size_t max_retained_identities{10'000};
|
||||
std::size_t max_concurrent_ops{128};
|
||||
};
|
||||
|
||||
using HostPolicy = std::function<bool(std::string_view host)>;
|
||||
|
||||
/// Validate target URL: absolute http/https, non-empty host, no userinfo,
|
||||
/// no control chars, bounded length, and optional host policy check.
|
||||
[[nodiscard]] inline Void::Result::Result<void>
|
||||
validate_target_url(std::string_view url,
|
||||
std::size_t max_url_bytes = 8192,
|
||||
const HostPolicy& host_policy = {})
|
||||
{
|
||||
if (url.empty() || url.size() > max_url_bytes) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: target URL empty or exceeds length limit")};
|
||||
}
|
||||
for (const unsigned char ch : url) {
|
||||
if (ch <= 0x20 || ch >= 0x7F) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: target URL contains control or whitespace "
|
||||
"character")};
|
||||
}
|
||||
}
|
||||
std::size_t rest_pos = 0;
|
||||
if (url.starts_with("https://")) {
|
||||
rest_pos = 8U;
|
||||
} else if (url.starts_with("http://")) {
|
||||
rest_pos = 7U;
|
||||
} else {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: target URL scheme must be http or https")};
|
||||
}
|
||||
const std::string_view after_scheme = url.substr(rest_pos);
|
||||
const std::size_t auth_end = after_scheme.find_first_of("/?#");
|
||||
const std::string_view authority = after_scheme.substr(0, auth_end);
|
||||
if (authority.empty()) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl, "ShortUrl: missing URL authority")};
|
||||
}
|
||||
if (authority.find('@') != std::string_view::npos) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: userinfo in target URL is forbidden")};
|
||||
}
|
||||
std::string_view host = authority;
|
||||
if (host.front() == '[') {
|
||||
const std::size_t close_b = host.find(']');
|
||||
if (close_b == std::string_view::npos || close_b == 1U) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: malformed IPv6 host in target URL")};
|
||||
}
|
||||
host = host.substr(1U, close_b - 1U);
|
||||
} else if (const std::size_t colon = host.find(':');
|
||||
colon != std::string_view::npos) {
|
||||
const std::string_view port_sv = host.substr(colon + 1U);
|
||||
if (port_sv.empty()) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: empty port in target URL")};
|
||||
}
|
||||
for (const char c : port_sv) {
|
||||
if (c < '0' || c > '9') {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: non-numeric port in target URL")};
|
||||
}
|
||||
}
|
||||
host = host.substr(0, colon);
|
||||
}
|
||||
if (host.empty()) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl, "ShortUrl: empty host")};
|
||||
}
|
||||
if (host_policy && !host_policy(host)) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidUrl,
|
||||
"ShortUrl: target host rejected by policy")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/// Validate custom key: 1..max_key_bytes ASCII [A-Za-z0-9_-], rejecting
|
||||
/// reserved route names.
|
||||
[[nodiscard]] inline Void::Result::Result<void>
|
||||
validate_custom_key(std::string_view key,
|
||||
std::size_t max_key_bytes = 64)
|
||||
{
|
||||
if (key.empty() || key.size() > max_key_bytes) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidKey,
|
||||
"ShortUrl: custom key length must be 1..64")};
|
||||
}
|
||||
for (const unsigned char ch : key) {
|
||||
const bool ok = (ch >= 'a' && ch <= 'z') ||
|
||||
(ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9') || ch == '-' || ch == '_';
|
||||
if (!ok) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidKey,
|
||||
"ShortUrl: custom key contains invalid character")};
|
||||
}
|
||||
}
|
||||
static const std::set<std::string_view> kReserved{
|
||||
"health", "metrics", "admin", "api", "shorten",
|
||||
"resolve", "revoke", "v1", "v2", "static",
|
||||
"assets", "status", "robots", "favicon"};
|
||||
std::string lower;
|
||||
lower.reserve(key.size());
|
||||
for (const char ch : key) {
|
||||
lower.push_back(static_cast<char>(
|
||||
ch >= 'A' && ch <= 'Z' ? (ch - 'A' + 'a') : ch));
|
||||
}
|
||||
if (kReserved.contains(lower)) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidKey,
|
||||
"ShortUrl: custom key matches reserved route name")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
class RandomBytesPort
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~RandomBytesPort() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
fill(std::span<std::byte> out) = 0;
|
||||
};
|
||||
|
||||
class SystemRandomBytesPort final : public RandomBytesPort
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
fill(std::span<std::byte> out) override
|
||||
{
|
||||
std::random_device rd;
|
||||
std::size_t i = 0;
|
||||
while (i < out.size()) {
|
||||
const unsigned int v = rd();
|
||||
for (int b = 0; b < 4 && i < out.size(); ++b, ++i) {
|
||||
out[i] = static_cast<std::byte>((v >> (b * 8)) & 0xFFU);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
enum class InsertStatus : std::uint8_t {
|
||||
Inserted,
|
||||
IdempotentReplay,
|
||||
Conflict,
|
||||
IdentityExpired,
|
||||
QuotaExceeded,
|
||||
};
|
||||
|
||||
struct InsertOutcome {
|
||||
InsertStatus status{InsertStatus::Inserted};
|
||||
LinkRecord record{};
|
||||
};
|
||||
|
||||
class LinkRepositoryPort
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~LinkRepositoryPort() = default;
|
||||
[[nodiscard]] virtual bool is_durable() const noexcept = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<InsertOutcome>
|
||||
insert_conditional(const LinkRecord& record,
|
||||
const std::optional<IdempotencyRecord>& idem,
|
||||
std::int64_t now_unix_seconds,
|
||||
std::size_t max_entries,
|
||||
std::size_t max_retained_identities) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<std::optional<LinkRecord>>
|
||||
get(std::string_view key) const = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
revoke(std::string_view key,
|
||||
std::int64_t now_unix_seconds) = 0;
|
||||
};
|
||||
|
||||
/// Explicitly nondurable in-memory repository for unit tests and semantic
|
||||
/// verification. Preserves conditional insert, tombstones, and idempotency.
|
||||
class InMemoryLinkRepository final : public LinkRepositoryPort
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] bool is_durable() const noexcept override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<InsertOutcome>
|
||||
insert_conditional(const LinkRecord& record,
|
||||
const std::optional<IdempotencyRecord>& idem,
|
||||
std::int64_t now_unix_seconds,
|
||||
std::size_t max_entries,
|
||||
std::size_t max_retained_identities) override
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (idem.has_value() && !idem->operation_id.empty()) {
|
||||
if (const auto iit = m_idempotency.find(idem->operation_id);
|
||||
iit != m_idempotency.end()) {
|
||||
if (iit->second.retain_until_unix_seconds <=
|
||||
now_unix_seconds) {
|
||||
return InsertOutcome{InsertStatus::IdentityExpired,
|
||||
{}};
|
||||
}
|
||||
if (const auto lit = m_links.find(iit->second.key);
|
||||
lit != m_links.end()) {
|
||||
return InsertOutcome{
|
||||
InsertStatus::IdempotentReplay, lit->second};
|
||||
}
|
||||
return InsertOutcome{InsertStatus::Conflict, {}};
|
||||
}
|
||||
if (m_idempotency.size() >= max_retained_identities) {
|
||||
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
|
||||
}
|
||||
}
|
||||
if (m_links.contains(record.key)) {
|
||||
return InsertOutcome{InsertStatus::Conflict, {}};
|
||||
}
|
||||
if (m_links.size() >= max_entries) {
|
||||
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
|
||||
}
|
||||
m_links.emplace(record.key, record);
|
||||
if (idem.has_value() && !idem->operation_id.empty()) {
|
||||
m_idempotency.emplace(idem->operation_id, *idem);
|
||||
}
|
||||
return InsertOutcome{InsertStatus::Inserted, record};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
|
||||
get(std::string_view key) const override
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (const auto it = m_links.find(key); it != m_links.end()) {
|
||||
return std::optional<LinkRecord>{it->second};
|
||||
}
|
||||
return std::optional<LinkRecord>{};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
revoke(std::string_view key, std::int64_t) override
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
const auto it = m_links.find(key);
|
||||
if (it == m_links.end()) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::NotFound,
|
||||
"ShortUrl: cannot revoke unknown key")};
|
||||
}
|
||||
it->second.state = LinkState::Revoked;
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::map<std::string, LinkRecord, std::less<>> m_links;
|
||||
std::map<std::string, IdempotencyRecord, std::less<>> m_idempotency;
|
||||
};
|
||||
|
||||
/// Abstract V2 provider interface outside the frozen V1 ABI.
|
||||
class Provider
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~Provider() = default;
|
||||
[[nodiscard]] virtual std::string_view
|
||||
provider_id() const noexcept = 0;
|
||||
[[nodiscard]] virtual V1::Health health() const = 0;
|
||||
[[nodiscard]] virtual bool supports_resolve() const noexcept = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<Link>
|
||||
shorten(const CreateLink& request,
|
||||
const ShortenOptions& options = {}) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<Link>
|
||||
resolve(std::string_view key) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
revoke(std::string_view key) = 0;
|
||||
};
|
||||
|
||||
struct LocalProviderOptions {
|
||||
std::string public_base_url{"https://sho.rt"};
|
||||
std::string provider_id{"void.local"};
|
||||
LocalProviderLimits limits{};
|
||||
HostPolicy host_policy{};
|
||||
};
|
||||
|
||||
/// Native local ShortUrl V2 provider composing LinkRepositoryPort,
|
||||
/// CivilClock, and RandomBytesPort with rejection-sampled base62 keys.
|
||||
class LocalProvider final : public Provider
|
||||
{
|
||||
public:
|
||||
|
||||
using Options = LocalProviderOptions;
|
||||
|
||||
LocalProvider(std::shared_ptr<LinkRepositoryPort> repository,
|
||||
Options options = Options{},
|
||||
const Void::Time::CivilClock& clock =
|
||||
Void::Time::SystemCivilClock::instance(),
|
||||
std::shared_ptr<RandomBytesPort> rng =
|
||||
std::make_shared<SystemRandomBytesPort>())
|
||||
: m_repo(std::move(repository)), m_options(std::move(options)),
|
||||
m_clock(&clock), m_rng(std::move(rng))
|
||||
{
|
||||
while (m_options.public_base_url.size() > 1U &&
|
||||
m_options.public_base_url.back() == '/') {
|
||||
m_options.public_base_url.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
provider_id() const noexcept override
|
||||
{
|
||||
return m_options.provider_id;
|
||||
}
|
||||
|
||||
[[nodiscard]] V1::Health health() const override
|
||||
{
|
||||
if (m_stopping.load(std::memory_order_acquire) || !m_repo) {
|
||||
return {V1::HealthStatus::unhealthy,
|
||||
"provider unavailable"};
|
||||
}
|
||||
return {V1::HealthStatus::healthy,
|
||||
m_repo->is_durable() ? "durable local provider"
|
||||
: "nondurable memory provider"};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool supports_resolve() const noexcept override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
void shutdown() noexcept
|
||||
{
|
||||
m_stopping.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Link>
|
||||
shorten(const CreateLink& request,
|
||||
const ShortenOptions& options = {}) override
|
||||
{
|
||||
auto slot = try_admit();
|
||||
if (!slot.has_value()) {
|
||||
return std::unexpected{std::move(slot.error())};
|
||||
}
|
||||
if (auto u = validate_target_url(request.target_url,
|
||||
m_options.limits.max_url_bytes,
|
||||
m_options.host_policy);
|
||||
!u.has_value()) {
|
||||
return std::unexpected{std::move(u.error())};
|
||||
}
|
||||
|
||||
const std::int64_t now_s =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
m_clock->now().time_since_epoch())
|
||||
.count();
|
||||
if (request.expires_at_unix_seconds < 0 ||
|
||||
(request.expires_at_unix_seconds > 0 &&
|
||||
request.expires_at_unix_seconds <= now_s)) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidExpiry,
|
||||
"ShortUrl: expiry must be 0 (permanent) or in the "
|
||||
"future")};
|
||||
}
|
||||
|
||||
const bool custom = !request.custom_key.empty();
|
||||
if (custom) {
|
||||
if (auto k = validate_custom_key(
|
||||
request.custom_key, m_options.limits.max_key_bytes);
|
||||
!k.has_value()) {
|
||||
return std::unexpected{std::move(k.error())};
|
||||
}
|
||||
}
|
||||
|
||||
const std::size_t attempts =
|
||||
custom ? 1U : m_options.limits.max_collision_retries;
|
||||
for (std::size_t attempt = 0; attempt < attempts; ++attempt) {
|
||||
std::string key;
|
||||
if (custom) {
|
||||
key = request.custom_key;
|
||||
} else {
|
||||
auto gen = generate_base62_key(
|
||||
m_options.limits.generated_key_length);
|
||||
if (!gen.has_value()) {
|
||||
return std::unexpected{std::move(gen.error())};
|
||||
}
|
||||
key = std::move(*gen);
|
||||
}
|
||||
|
||||
LinkRecord rec;
|
||||
rec.key = key;
|
||||
rec.target_url = request.target_url;
|
||||
rec.created_at_unix_seconds = now_s;
|
||||
rec.expires_at_unix_seconds =
|
||||
request.expires_at_unix_seconds;
|
||||
rec.state = LinkState::Active;
|
||||
rec.operation_id = options.operation_id;
|
||||
rec.schema_version = kRecordSchemaVersion;
|
||||
|
||||
std::optional<IdempotencyRecord> idem;
|
||||
if (!options.operation_id.empty()) {
|
||||
idem = IdempotencyRecord{
|
||||
.operation_id = options.operation_id,
|
||||
.key = key,
|
||||
.target_url = request.target_url,
|
||||
.created_at_unix_seconds = now_s,
|
||||
.retain_until_unix_seconds =
|
||||
now_s + options.idempotency_retention.count(),
|
||||
};
|
||||
}
|
||||
|
||||
auto ins = m_repo->insert_conditional(
|
||||
rec, idem, now_s, m_options.limits.max_entries,
|
||||
m_options.limits.max_retained_identities);
|
||||
if (!ins.has_value()) {
|
||||
return std::unexpected{std::move(ins.error())};
|
||||
}
|
||||
switch (ins->status) {
|
||||
case InsertStatus::Inserted:
|
||||
case InsertStatus::IdempotentReplay:
|
||||
return make_link(ins->record);
|
||||
case InsertStatus::Conflict:
|
||||
if (custom) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::Conflict,
|
||||
"ShortUrl: custom key already exists")};
|
||||
}
|
||||
continue; // retry random key
|
||||
case InsertStatus::IdentityExpired:
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::IdentityExpired,
|
||||
"ShortUrl: operation_id retention expired")};
|
||||
case InsertStatus::QuotaExceeded:
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::QuotaExceeded,
|
||||
"ShortUrl: repository quota or retention "
|
||||
"exhausted")};
|
||||
}
|
||||
}
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::Conflict,
|
||||
"ShortUrl: exhausted random key collision retries")};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Link>
|
||||
resolve(std::string_view key) override
|
||||
{
|
||||
auto slot = try_admit();
|
||||
if (!slot.has_value()) {
|
||||
return std::unexpected{std::move(slot.error())};
|
||||
}
|
||||
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
|
||||
}
|
||||
auto rec = m_repo->get(key);
|
||||
if (!rec.has_value()) {
|
||||
return std::unexpected{std::move(rec.error())};
|
||||
}
|
||||
if (!rec->has_value()) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::NotFound, "ShortUrl: key not found")};
|
||||
}
|
||||
const LinkRecord& r = **rec;
|
||||
if (r.state == LinkState::Revoked) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::Revoked, "ShortUrl: link revoked")};
|
||||
}
|
||||
const std::int64_t now_s =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
m_clock->now().time_since_epoch())
|
||||
.count();
|
||||
if (r.expires_at_unix_seconds > 0 &&
|
||||
r.expires_at_unix_seconds <= now_s) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::Expired, "ShortUrl: link expired")};
|
||||
}
|
||||
return make_link(r);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
revoke(std::string_view key) override
|
||||
{
|
||||
auto slot = try_admit();
|
||||
if (!slot.has_value()) {
|
||||
return std::unexpected{std::move(slot.error())};
|
||||
}
|
||||
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
|
||||
}
|
||||
const std::int64_t now_s =
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
m_clock->now().time_since_epoch())
|
||||
.count();
|
||||
return m_repo->revoke(key, now_s);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
struct OpSlot {
|
||||
std::atomic<std::size_t>* active{nullptr};
|
||||
~OpSlot() noexcept
|
||||
{
|
||||
if (active != nullptr) {
|
||||
active->fetch_sub(1, std::memory_order_acq_rel);
|
||||
}
|
||||
}
|
||||
OpSlot(std::atomic<std::size_t>* a) noexcept : active(a) {}
|
||||
OpSlot(OpSlot&& o) noexcept
|
||||
: active(std::exchange(o.active, nullptr))
|
||||
{
|
||||
}
|
||||
OpSlot(const OpSlot&) = delete;
|
||||
OpSlot& operator=(const OpSlot&) = delete;
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<OpSlot> try_admit()
|
||||
{
|
||||
if (m_stopping.load(std::memory_order_acquire) || !m_repo ||
|
||||
!m_rng) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::Unavailable,
|
||||
"ShortUrl: provider shut down or unconfigured")};
|
||||
}
|
||||
std::size_t cur = m_active_ops.load(std::memory_order_relaxed);
|
||||
for (;;) {
|
||||
if (cur >= m_options.limits.max_concurrent_ops) {
|
||||
return std::unexpected{make_shorturl_error(
|
||||
V2ErrorCode::RateLimited,
|
||||
"ShortUrl: max concurrent operations reached")};
|
||||
}
|
||||
if (m_active_ops.compare_exchange_weak(
|
||||
cur, cur + 1U, std::memory_order_acq_rel,
|
||||
std::memory_order_relaxed)) {
|
||||
return OpSlot{&m_active_ops};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
generate_base62_key(std::size_t len) const
|
||||
{
|
||||
static constexpr char kAlphabet[63] =
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"
|
||||
"wxyz";
|
||||
constexpr unsigned char kCutoff = 62U * 4U; // 248 (uniform)
|
||||
|
||||
std::string out;
|
||||
out.reserve(len);
|
||||
std::array<std::byte, 64> buf{};
|
||||
while (out.size() < len) {
|
||||
auto r = m_rng->fill(buf);
|
||||
if (!r.has_value()) {
|
||||
return std::unexpected{std::move(r.error())};
|
||||
}
|
||||
for (const std::byte b : buf) {
|
||||
const auto u = static_cast<unsigned char>(b);
|
||||
if (u < kCutoff) {
|
||||
out.push_back(kAlphabet[u % 62U]);
|
||||
if (out.size() == len) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] Link make_link(const LinkRecord& r) const
|
||||
{
|
||||
return Link{
|
||||
.key = r.key,
|
||||
.short_url =
|
||||
std::format("{}/{}", m_options.public_base_url, r.key),
|
||||
.target_url = r.target_url,
|
||||
.expires_at_unix_seconds = r.expires_at_unix_seconds,
|
||||
};
|
||||
}
|
||||
|
||||
std::shared_ptr<LinkRepositoryPort> m_repo;
|
||||
Options m_options;
|
||||
const Void::Time::CivilClock* m_clock;
|
||||
std::shared_ptr<RandomBytesPort> m_rng;
|
||||
std::atomic<bool> m_stopping{false};
|
||||
std::atomic<std::size_t> m_active_ops{0};
|
||||
};
|
||||
|
||||
/// Adapter implementing frozen `Void::ShortUrl::V1::IShortener` on top of
|
||||
/// any V2 `Provider` without changing V1 layout or virtual table order.
|
||||
class V1Adapter final : public V1::IShortener
|
||||
{
|
||||
public:
|
||||
|
||||
explicit V1Adapter(std::shared_ptr<Provider> provider)
|
||||
: m_provider(std::move(provider))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
provider_id() const noexcept override
|
||||
{
|
||||
return m_provider ? m_provider->provider_id()
|
||||
: std::string_view{"unconfigured"};
|
||||
}
|
||||
|
||||
[[nodiscard]] V1::Health health() const override
|
||||
{
|
||||
return m_provider ? m_provider->health()
|
||||
: V1::Health{V1::HealthStatus::unhealthy,
|
||||
"null provider"};
|
||||
}
|
||||
|
||||
[[nodiscard]] V1::ShortenResult
|
||||
shorten(const V1::ShortenRequest& request) override
|
||||
{
|
||||
if (!m_provider) {
|
||||
return {.error = {V1::ErrorCode::unavailable,
|
||||
"null provider"}};
|
||||
}
|
||||
auto res = m_provider->shorten(CreateLink{
|
||||
.target_url = request.target_url,
|
||||
.custom_key = request.custom_key,
|
||||
.expires_at_unix_seconds = request.expires_at_unix_seconds,
|
||||
});
|
||||
if (!res.has_value()) {
|
||||
const auto code = v2_error_code_from(res.error());
|
||||
return {.error = {to_v1_error_code(code),
|
||||
std::string{res.error().message()}}};
|
||||
}
|
||||
return {
|
||||
.short_url = std::move(res->short_url),
|
||||
.key = std::move(res->key),
|
||||
.expires_at_unix_seconds = res->expires_at_unix_seconds,
|
||||
.error = {},
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool supports_resolve() const noexcept override
|
||||
{
|
||||
return m_provider != nullptr && m_provider->supports_resolve();
|
||||
}
|
||||
|
||||
[[nodiscard]] V1::ResolveResult
|
||||
resolve(const V1::ResolveRequest& request) override
|
||||
{
|
||||
if (!m_provider) {
|
||||
return {.error = {V1::ErrorCode::unavailable,
|
||||
"null provider"}};
|
||||
}
|
||||
auto res = m_provider->resolve(request.key);
|
||||
if (!res.has_value()) {
|
||||
const auto code = v2_error_code_from(res.error());
|
||||
return {.error = {to_v1_error_code(code),
|
||||
std::string{res.error().message()}}};
|
||||
}
|
||||
return {
|
||||
.target_url = std::move(res->target_url),
|
||||
.expires_at_unix_seconds = res->expires_at_unix_seconds,
|
||||
.error = {},
|
||||
};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<Provider> m_provider;
|
||||
};
|
||||
|
||||
} // namespace Void::ShortUrl::V2
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/ShortUrl/V2.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::ShortUrl::V2
|
||||
{
|
||||
struct RemoteCapabilities {
|
||||
bool supports_custom_key{true};
|
||||
bool supports_expiry{true};
|
||||
bool supports_resolve{true};
|
||||
bool supports_revoke{true};
|
||||
};
|
||||
|
||||
struct RemoteProviderOptions {
|
||||
std::string base_url{};
|
||||
std::string provider_id{"void.remote"};
|
||||
RemoteCapabilities capabilities{};
|
||||
Void::Net::HttpClientOptions http_options{
|
||||
.verify_tls = true,
|
||||
.max_body_size = 1024ULL * 1024,
|
||||
};
|
||||
std::chrono::seconds timeout{std::chrono::seconds{10}};
|
||||
std::uint64_t max_response_bytes{1024ULL * 1024};
|
||||
std::vector<Void::Net::Header> headers{};
|
||||
};
|
||||
|
||||
/// Generic remote ShortUrl V2 provider over `Void::Net::HttpClient`.
|
||||
/// Checks capability flags before network mutation, enforces response size
|
||||
/// and deadline bounds, preserves Retry-After, and maps lost-reply
|
||||
/// transport failures after send to `V2ErrorCode::UnknownOutcome`.
|
||||
class RemoteProvider final : public Provider
|
||||
{
|
||||
public:
|
||||
|
||||
explicit RemoteProvider(RemoteProviderOptions options);
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
provider_id() const noexcept override;
|
||||
[[nodiscard]] V1::Health health() const override;
|
||||
[[nodiscard]] bool supports_resolve() const noexcept override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Link>
|
||||
shorten(const CreateLink& request,
|
||||
const ShortenOptions& options = {}) override;
|
||||
[[nodiscard]] Void::Result::Result<Link>
|
||||
resolve(std::string_view key) override;
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
revoke(std::string_view key) override;
|
||||
|
||||
/// Retry-After seconds from the most recent rate-limited/unavailable
|
||||
/// remote response (0 if absent).
|
||||
[[nodiscard]] std::uint32_t last_retry_after_seconds() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
RemoteProviderOptions m_options;
|
||||
Void::Net::HttpClient m_client;
|
||||
std::atomic<std::uint32_t> m_last_retry_after{0};
|
||||
};
|
||||
|
||||
} // namespace Void::ShortUrl::V2
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/ShortUrl/V2.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace Void::ShortUrl::V2
|
||||
{
|
||||
/// CSPRNG byte source backed by `Void::Security` (libsodium).
|
||||
class SecurityRandomBytesPort final : public RandomBytesPort
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
fill(std::span<std::byte> out) override;
|
||||
};
|
||||
|
||||
/// Durable `LinkRepositoryPort` backed by `Void::Storage::Engine`
|
||||
/// conditional `Batch` writes, preserving tombstones, V2 idempotency
|
||||
/// records, and quotas across crash/restart boundaries.
|
||||
class StorageLinkRepository final : public LinkRepositoryPort
|
||||
{
|
||||
public:
|
||||
|
||||
explicit StorageLinkRepository(
|
||||
std::shared_ptr<Void::Storage::Engine> engine,
|
||||
std::uint64_t disk_quota_bytes = 1024ULL * 1024 * 1024);
|
||||
|
||||
[[nodiscard]] bool is_durable() const noexcept override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<InsertOutcome>
|
||||
insert_conditional(const LinkRecord& record,
|
||||
const std::optional<IdempotencyRecord>& idem,
|
||||
std::int64_t now_unix_seconds,
|
||||
std::size_t max_entries,
|
||||
std::size_t max_retained_identities) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
|
||||
get(std::string_view key) const override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
revoke(std::string_view key,
|
||||
std::int64_t now_unix_seconds) override;
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_write_mutex;
|
||||
std::shared_ptr<Void::Storage::Engine> m_engine;
|
||||
std::uint64_t m_disk_quota_bytes;
|
||||
};
|
||||
|
||||
} // namespace Void::ShortUrl::V2
|
||||
@@ -0,0 +1,179 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Sqlite/Sqlite.hpp>
|
||||
#include <Void/Sqlite/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
namespace Void::Sqlite
|
||||
{
|
||||
struct AsyncPoolOptions {
|
||||
std::filesystem::path path{};
|
||||
OpenOptions open_options{};
|
||||
/// Default 4 reader connections alongside 1 dedicated writer lane.
|
||||
std::size_t reader_connections{4};
|
||||
std::size_t max_queued_jobs{1024};
|
||||
std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
int progress_handler_steps{64};
|
||||
const Void::Time::MonotonicClock* clock{nullptr};
|
||||
};
|
||||
|
||||
struct AsyncPoolStats {
|
||||
std::size_t reader_connections{0};
|
||||
std::size_t queued_read_jobs{0};
|
||||
std::size_t queued_write_jobs{0};
|
||||
std::size_t active_read_jobs{0};
|
||||
std::size_t active_write_jobs{0};
|
||||
std::size_t pending_input_bytes{0};
|
||||
std::uint64_t completed_jobs{0};
|
||||
std::uint64_t rejected_jobs{0};
|
||||
std::uint64_t cancelled_jobs{0};
|
||||
};
|
||||
|
||||
/// Bounded blocking SQLite connection pool (1 writer lane + N reader lanes).
|
||||
/// Leases one connection exclusively for the entire callback/transaction
|
||||
/// without ever running SQLite calls on an IO event-loop thread or leaking
|
||||
/// interrupts across subsequent borrowers.
|
||||
class AsyncPool
|
||||
{
|
||||
public:
|
||||
~AsyncPool();
|
||||
AsyncPool(AsyncPool&&) noexcept;
|
||||
AsyncPool& operator=(AsyncPool&&) noexcept;
|
||||
AsyncPool(const AsyncPool&) = delete;
|
||||
AsyncPool& operator=(const AsyncPool&) = delete;
|
||||
|
||||
[[nodiscard]] static Result<AsyncPool> open(
|
||||
AsyncPoolOptions options,
|
||||
Void::Async::Executor* completion_executor = nullptr);
|
||||
|
||||
/// Execute a read-only unit of work on a leased reader connection.
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Coro::Task<Result<T>> run_read(
|
||||
std::function<Result<T>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0)
|
||||
{
|
||||
auto box = std::make_shared<std::optional<Result<T>>>();
|
||||
auto r = co_await submit_erased(
|
||||
false,
|
||||
[box, f = std::move(fn)](Database& db) -> Result<void> {
|
||||
*box = f(db);
|
||||
return {};
|
||||
},
|
||||
std::move(op),
|
||||
input_bytes);
|
||||
if (!r) {
|
||||
co_return Void::Result::fail(std::move(r).error());
|
||||
}
|
||||
if (!box->has_value()) {
|
||||
co_return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::sqlite_error,
|
||||
"AsyncPool read callback produced no result"));
|
||||
}
|
||||
co_return std::move(**box);
|
||||
}
|
||||
|
||||
/// Execute a write unit of work on the serialized writer lane.
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Coro::Task<Result<T>> run_write(
|
||||
std::function<Result<T>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0)
|
||||
{
|
||||
auto box = std::make_shared<std::optional<Result<T>>>();
|
||||
auto r = co_await submit_erased(
|
||||
true,
|
||||
[box, f = std::move(fn)](Database& db) -> Result<void> {
|
||||
*box = f(db);
|
||||
return {};
|
||||
},
|
||||
std::move(op),
|
||||
input_bytes);
|
||||
if (!r) {
|
||||
co_return Void::Result::fail(std::move(r).error());
|
||||
}
|
||||
if (!box->has_value()) {
|
||||
co_return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::sqlite_error,
|
||||
"AsyncPool write callback produced no result"));
|
||||
}
|
||||
co_return std::move(**box);
|
||||
}
|
||||
|
||||
/// Execute a full transaction on the leased writer connection.
|
||||
/// Commits if `fn` returns ok; rolls back on error. Never releases
|
||||
/// the writer lease mid-transaction.
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Coro::Task<Result<T>> run_write_transaction(
|
||||
BeginMode mode,
|
||||
std::function<Result<T>(Database&, Transaction&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0)
|
||||
{
|
||||
return run_write<T>(
|
||||
[mode, f = std::move(fn)](Database& db) -> Result<T> {
|
||||
auto tx = db.begin(mode);
|
||||
if (!tx) {
|
||||
return Void::Result::fail(std::move(tx).error());
|
||||
}
|
||||
auto res = f(db, *tx);
|
||||
if (!res) {
|
||||
(void)tx->rollback_checked();
|
||||
return res;
|
||||
}
|
||||
if (tx->is_active()) {
|
||||
auto c = tx->commit();
|
||||
if (!c) {
|
||||
if (tx->is_active()) {
|
||||
(void)tx->rollback_checked();
|
||||
}
|
||||
return Void::Result::fail(std::move(c).error());
|
||||
}
|
||||
}
|
||||
return res;
|
||||
},
|
||||
std::move(op),
|
||||
input_bytes);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<void>> run_read_void(
|
||||
std::function<Result<void>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0);
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<void>> run_write_void(
|
||||
std::function<Result<void>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0);
|
||||
|
||||
[[nodiscard]] AsyncPoolStats stats() const noexcept;
|
||||
|
||||
/// Stop new admission, drain all admitted jobs, join worker threads,
|
||||
/// and close all pooled SQLite connections.
|
||||
[[nodiscard]] Result<void> close_and_join();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
explicit AsyncPool(std::shared_ptr<Impl> impl) noexcept;
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<void>> submit_erased(
|
||||
bool is_write,
|
||||
std::function<Result<void>(Database&)> fn,
|
||||
Void::Async::OperationOptions op,
|
||||
std::size_t input_bytes);
|
||||
|
||||
std::shared_ptr<Impl> m_impl{};
|
||||
};
|
||||
|
||||
} // namespace Void::Sqlite
|
||||
+253
-33
@@ -2,36 +2,79 @@
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Sqlite/Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
struct sqlite3;
|
||||
struct sqlite3_stmt;
|
||||
|
||||
// A thin, RAII, Result-based wrapper over the SQLite C API. Generic — no
|
||||
// application schema baggage. Open a Database, prepare Statements, bind by
|
||||
// 1-based index, step over result rows, read columns by 0-based index. Schema
|
||||
// versioning is handled via PRAGMA user_version (migrate()).
|
||||
// A hardened RAII, Result-based wrapper over the SQLite C API. Generic — no
|
||||
// application schema baggage. Open a Database (or open_database with explicit
|
||||
// OpenOptions), prepare Statements, bind by 1-based index or parameter name,
|
||||
// step over result rows, and read typed columns by 0-based index.
|
||||
namespace Void::Sqlite
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class OpenMode { ReadOnly, ReadWrite, ReadWriteCreate };
|
||||
namespace detail
|
||||
{
|
||||
struct ConnectionState;
|
||||
} // namespace detail
|
||||
|
||||
class Database;
|
||||
class Statement;
|
||||
class Transaction;
|
||||
class Savepoint;
|
||||
|
||||
/// A prepared statement. Move-only; finalizes on destruction.
|
||||
/// Non-owning view of the current row of a Statement. Expires on the next
|
||||
/// step(), reset(), reset_checked(), finalize_checked(), or destruction.
|
||||
/// Must never cross an await or outlive the Statement step that produced it.
|
||||
class RowView
|
||||
{
|
||||
public:
|
||||
RowView() noexcept = default;
|
||||
|
||||
[[nodiscard]] bool is_valid() const noexcept;
|
||||
[[nodiscard]] int column_count() const noexcept;
|
||||
[[nodiscard]] Result<ColumnType> column_type(int col) const;
|
||||
[[nodiscard]] Result<bool> is_null(int col) const;
|
||||
[[nodiscard]] Result<std::int64_t> get_int(int col) const;
|
||||
[[nodiscard]] Result<double> get_double(int col) const;
|
||||
[[nodiscard]] Result<std::string_view> get_text_view(int col) const;
|
||||
[[nodiscard]] Result<std::string> get_text(int col) const;
|
||||
[[nodiscard]] Result<std::span<const std::byte>> get_blob_view(int col) const;
|
||||
[[nodiscard]] Result<std::vector<std::byte>> get_blob(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::int64_t>> get_optional_int(int col) const;
|
||||
[[nodiscard]] Result<std::optional<double>> get_optional_double(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::string>> get_optional_text(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::vector<std::byte>>> get_optional_blob(int col) const;
|
||||
[[nodiscard]] Result<OwnedValue> get_value(int col) const;
|
||||
[[nodiscard]] Result<OwnedRow> copy() const;
|
||||
|
||||
private:
|
||||
friend class Statement;
|
||||
RowView(const Statement* stmt, std::uint64_t generation) noexcept
|
||||
: m_stmt(stmt), m_generation(generation)
|
||||
{
|
||||
}
|
||||
|
||||
const Statement* m_stmt{nullptr};
|
||||
std::uint64_t m_generation{0};
|
||||
};
|
||||
|
||||
/// A prepared statement. Move-only; retains shared ConnectionState so moving
|
||||
/// or destroying Database cannot dangle this statement.
|
||||
class Statement
|
||||
{
|
||||
public:
|
||||
|
||||
Statement() = default;
|
||||
~Statement();
|
||||
Statement(Statement&&) noexcept;
|
||||
@@ -39,7 +82,7 @@ namespace Void::Sqlite
|
||||
Statement(const Statement&) = delete;
|
||||
Statement& operator=(const Statement&) = delete;
|
||||
|
||||
// Bind parameters (1-based, matching SQLite). Chainable.
|
||||
// ── Legacy 1.x chainable bind methods (1-based) ──────────────────
|
||||
Statement& bind(int index, std::int64_t value);
|
||||
Statement& bind(int index, int value)
|
||||
{
|
||||
@@ -56,48 +99,143 @@ namespace Void::Sqlite
|
||||
Statement& bind(int index, std::nullptr_t);
|
||||
Statement& bind(int index, const std::optional<std::string>& value);
|
||||
|
||||
/// Error captured by the most recent legacy unchecked bind() call, if any.
|
||||
[[nodiscard]] const std::optional<Error>& last_bind_error() const noexcept
|
||||
{
|
||||
return m_last_bind_error;
|
||||
}
|
||||
|
||||
// ── Checked bind / parameter metadata ────────────────────────────
|
||||
[[nodiscard]] int bind_parameter_count() const noexcept;
|
||||
[[nodiscard]] Result<int> bind_parameter_index(std::string_view name) const;
|
||||
|
||||
[[nodiscard]] Result<void> bind_checked(int index, ValueView value);
|
||||
[[nodiscard]] Result<void> bind_checked(std::string_view name, ValueView value);
|
||||
|
||||
/// Zero-copy borrowed text/blob binding keeping `owner` alive until
|
||||
/// reset(), clear_bindings(), rebind, finalize, or destruction.
|
||||
[[nodiscard]] Result<void> bind_borrowed_text(
|
||||
int index, std::string_view value, std::shared_ptr<const void> owner);
|
||||
[[nodiscard]] Result<void> bind_borrowed_blob(
|
||||
int index, std::span<const std::byte> value, std::shared_ptr<const void> owner);
|
||||
|
||||
/// Advance to the next row. Returns true with a row available,
|
||||
/// false when the statement is done, or an Error on failure.
|
||||
[[nodiscard]] Result<bool> step();
|
||||
|
||||
/// Reset for re-execution (keeps bindings unless clear_bindings).
|
||||
void reset() noexcept;
|
||||
void clear_bindings() noexcept;
|
||||
[[nodiscard]] Result<void> reset_checked();
|
||||
|
||||
// Column accessors (0-based), valid after step() yields a row.
|
||||
void clear_bindings() noexcept;
|
||||
[[nodiscard]] Result<void> clear_bindings_checked();
|
||||
|
||||
/// Explicitly finalize the statement and report any native error.
|
||||
[[nodiscard]] Result<void> finalize_checked();
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept { return m_stmt != nullptr; }
|
||||
[[nodiscard]] bool has_row() const noexcept { return m_has_row; }
|
||||
[[nodiscard]] std::uint64_t row_generation() const noexcept
|
||||
{
|
||||
return m_row_generation;
|
||||
}
|
||||
|
||||
// ── Legacy 1.x column accessors (0-based) ────────────────────────
|
||||
[[nodiscard]] int column_count() const noexcept;
|
||||
[[nodiscard]] bool is_null(int col) const noexcept;
|
||||
[[nodiscard]] std::int64_t column_int(int col) const noexcept;
|
||||
[[nodiscard]] double column_double(int col) const noexcept;
|
||||
[[nodiscard]] std::string column_text(int col) const;
|
||||
|
||||
private:
|
||||
// ── Strict typed column accessors & row views ────────────────────
|
||||
[[nodiscard]] Result<RowView> current_row() const;
|
||||
[[nodiscard]] Result<OwnedRow> copy_row() const;
|
||||
[[nodiscard]] Result<ColumnType> column_type(int col) const;
|
||||
[[nodiscard]] Result<std::int64_t> try_column_int(int col) const;
|
||||
[[nodiscard]] Result<double> try_column_double(int col) const;
|
||||
[[nodiscard]] Result<std::string_view> try_column_text_view(int col) const;
|
||||
[[nodiscard]] Result<std::string> try_column_text(int col) const;
|
||||
[[nodiscard]] Result<std::span<const std::byte>> try_column_blob_view(int col) const;
|
||||
[[nodiscard]] Result<std::vector<std::byte>> try_column_blob(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::int64_t>> try_column_optional_int(int col) const;
|
||||
[[nodiscard]] Result<std::optional<double>> try_column_optional_double(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::string>> try_column_optional_text(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::vector<std::byte>>> try_column_optional_blob(int col) const;
|
||||
[[nodiscard]] Result<OwnedValue> try_column_value(int col) const;
|
||||
|
||||
private:
|
||||
friend class Database;
|
||||
explicit Statement(sqlite3_stmt* stmt) : m_stmt(stmt) {}
|
||||
sqlite3_stmt* m_stmt = nullptr;
|
||||
friend class RowView;
|
||||
|
||||
Statement(std::shared_ptr<detail::ConnectionState> conn,
|
||||
sqlite3_stmt* stmt) noexcept;
|
||||
void release_handle() noexcept;
|
||||
[[nodiscard]] Result<void> validate_column_access(int col) const;
|
||||
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
sqlite3_stmt* m_stmt{nullptr};
|
||||
bool m_has_row{false};
|
||||
std::uint64_t m_row_generation{0};
|
||||
std::vector<std::shared_ptr<const void>> m_borrowed_owners{};
|
||||
std::optional<Error> m_last_bind_error{};
|
||||
};
|
||||
|
||||
/// RAII transaction. Rolls back on destruction unless commit() was called.
|
||||
/// RAII transaction retaining shared ConnectionState. Never marks Committed
|
||||
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error.
|
||||
class Transaction
|
||||
{
|
||||
public:
|
||||
|
||||
Transaction() noexcept = default;
|
||||
~Transaction();
|
||||
Transaction(Transaction&&) noexcept;
|
||||
Transaction& operator=(Transaction&&) noexcept;
|
||||
Transaction(const Transaction&) = delete;
|
||||
Transaction& operator=(const Transaction&) = delete;
|
||||
|
||||
[[nodiscard]] TransactionState state() const noexcept { return m_state; }
|
||||
[[nodiscard]] bool is_active() const noexcept
|
||||
{
|
||||
return m_state == TransactionState::Active;
|
||||
}
|
||||
|
||||
Result<void> commit();
|
||||
[[nodiscard]] Result<void> rollback_checked();
|
||||
void rollback() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class Database;
|
||||
explicit Transaction(Database* db) : m_db(db) {}
|
||||
Database* m_db = nullptr;
|
||||
bool m_done = false;
|
||||
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept;
|
||||
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
TransactionState m_state{TransactionState::RolledBack};
|
||||
};
|
||||
|
||||
/// Separately owned nested savepoint scope.
|
||||
class Savepoint
|
||||
{
|
||||
public:
|
||||
Savepoint() noexcept = default;
|
||||
~Savepoint();
|
||||
Savepoint(Savepoint&&) noexcept;
|
||||
Savepoint& operator=(Savepoint&&) noexcept;
|
||||
Savepoint(const Savepoint&) = delete;
|
||||
Savepoint& operator=(const Savepoint&) = delete;
|
||||
|
||||
[[nodiscard]] bool is_active() const noexcept { return m_active; }
|
||||
[[nodiscard]] std::string_view name() const noexcept { return m_name; }
|
||||
|
||||
[[nodiscard]] Result<void> release();
|
||||
[[nodiscard]] Result<void> rollback_to();
|
||||
[[nodiscard]] Result<void> rollback_and_release();
|
||||
|
||||
private:
|
||||
friend class Database;
|
||||
Savepoint(std::shared_ptr<detail::ConnectionState> conn,
|
||||
std::string name) noexcept;
|
||||
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
std::string m_name{};
|
||||
bool m_active{false};
|
||||
};
|
||||
|
||||
/// A single forward schema migration applied when the database's
|
||||
@@ -107,10 +245,18 @@ namespace Void::Sqlite
|
||||
std::string_view sql; ///< DDL/DML to reach this version
|
||||
};
|
||||
|
||||
using ScalarFunction =
|
||||
std::function<Result<OwnedValue>(std::span<const ValueView>)>;
|
||||
using AuthorizerCallback = std::function<AuthorizerDecision(
|
||||
int action_code,
|
||||
std::string_view arg1,
|
||||
std::string_view arg2,
|
||||
std::string_view db_name,
|
||||
std::string_view trigger_or_view)>;
|
||||
|
||||
class Database
|
||||
{
|
||||
public:
|
||||
|
||||
Database() = default;
|
||||
~Database();
|
||||
Database(Database&&) noexcept;
|
||||
@@ -119,19 +265,46 @@ namespace Void::Sqlite
|
||||
Database& operator=(const Database&) = delete;
|
||||
|
||||
/// Open (or create) a database file. Use ":memory:" for an
|
||||
/// in-memory db. Enables WAL + a busy timeout for ReadWrite modes.
|
||||
/// in-memory db. Enables checked WAL + FULL + foreign_keys for
|
||||
/// writable file databases.
|
||||
[[nodiscard]] static Result<Database>
|
||||
open(const std::filesystem::path& path,
|
||||
OpenMode mode = OpenMode::ReadWriteCreate);
|
||||
|
||||
/// Open with explicit checked options, limits, and diagnostics.
|
||||
[[nodiscard]] static Result<Database>
|
||||
open_with_options(const std::filesystem::path& path,
|
||||
OpenOptions options);
|
||||
|
||||
/// Execute one or more semicolon-separated statements (no results).
|
||||
Result<void> exec(std::string_view sql);
|
||||
|
||||
/// Prepare a single statement for binding/stepping.
|
||||
/// Prepare a single statement for binding/stepping. Rejects
|
||||
/// non-whitespace trailing SQL and enforces statement/SQL limits.
|
||||
[[nodiscard]] Result<Statement> prepare(std::string_view sql);
|
||||
|
||||
/// Begin a transaction (BEGIN; commit/rollback via the handle).
|
||||
[[nodiscard]] Result<Transaction> begin();
|
||||
/// Begin a transaction. Rejects nested begin() while a transaction
|
||||
/// is already active (use savepoint() for nesting).
|
||||
[[nodiscard]] Result<Transaction> begin(BeginMode mode = BeginMode::Deferred);
|
||||
|
||||
/// Create a named nested savepoint (ASCII identifier only).
|
||||
[[nodiscard]] Result<Savepoint> savepoint(std::string_view name);
|
||||
|
||||
/// Stream all rows from a prepared statement with row & byte caps.
|
||||
[[nodiscard]] Result<std::vector<OwnedRow>> query_all(
|
||||
Statement& stmt,
|
||||
std::size_t max_rows = 0,
|
||||
std::size_t max_bytes = 0);
|
||||
|
||||
/// Explicitly close the connection. Stops admission and returns
|
||||
/// SqliteErrorCode::busy while live statements/transactions/savepoints
|
||||
/// remain open.
|
||||
[[nodiscard]] Result<void> close();
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept;
|
||||
[[nodiscard]] EffectiveCapabilities capabilities() const;
|
||||
[[nodiscard]] ConnectionHealth health() const;
|
||||
[[nodiscard]] const SqliteLimits& limits() const noexcept;
|
||||
|
||||
[[nodiscard]] std::int64_t last_insert_rowid() const noexcept;
|
||||
[[nodiscard]] int changes() const noexcept;
|
||||
@@ -139,16 +312,63 @@ namespace Void::Sqlite
|
||||
/// Current schema version (PRAGMA user_version).
|
||||
[[nodiscard]] Result<int> user_version();
|
||||
|
||||
/// Apply, in order, any migrations whose version exceeds the
|
||||
/// current user_version, each inside a transaction, then bump
|
||||
/// user_version. Idempotent and safe to call on every startup.
|
||||
/// Validate strictly increasing unique versions before mutation,
|
||||
/// reject unexpected newer schemas, and apply pending migrations.
|
||||
Result<void> migrate(std::span<const Migration> migrations);
|
||||
|
||||
[[nodiscard]] sqlite3* handle() const noexcept { return m_db; }
|
||||
/// Validate migrations, record immutable id & checksum in
|
||||
/// `_void_schema_migrations` in the same transaction as user_version,
|
||||
/// and reject checksum drift or unexpected newer schemas.
|
||||
[[nodiscard]] Result<void>
|
||||
migrate_checked(std::span<const CheckedMigration> migrations);
|
||||
|
||||
/// Run a WAL checkpoint and report completed/remaining frames and busy state.
|
||||
[[nodiscard]] Result<CheckpointReport>
|
||||
checkpoint(CheckpointMode mode = CheckpointMode::Passive);
|
||||
|
||||
/// Copy this database consistently to `destination` via SQLite's backup API.
|
||||
[[nodiscard]] Result<BackupReport>
|
||||
backup_to(const std::filesystem::path& destination,
|
||||
BackupOptions options = {});
|
||||
|
||||
/// Restore this database consistently from `source` via SQLite's backup API.
|
||||
[[nodiscard]] Result<BackupReport>
|
||||
restore_from(const std::filesystem::path& source,
|
||||
BackupOptions options = {});
|
||||
|
||||
/// Register an exception-safe custom scalar SQL function owned by
|
||||
/// this connection's ConnectionState.
|
||||
[[nodiscard]] Result<void> create_scalar_function(
|
||||
std::string name,
|
||||
int num_args,
|
||||
ScalarFunction fn,
|
||||
bool deterministic = true);
|
||||
|
||||
/// Register (or clear when empty) an exception-safe SQLite authorizer.
|
||||
[[nodiscard]] Result<void> set_authorizer(AuthorizerCallback cb);
|
||||
|
||||
/// Expert native handle borrow under caller's execution lease.
|
||||
[[nodiscard]] sqlite3* handle() const noexcept;
|
||||
|
||||
/// Operation-scoped interrupt/progress hooks for leased async execution
|
||||
/// (serialized with end_operation so interrupts never leak across queries).
|
||||
void begin_leased_operation(std::uint64_t generation,
|
||||
int progress_steps,
|
||||
std::function<bool()> should_interrupt);
|
||||
void interrupt_leased_operation(std::uint64_t generation) noexcept;
|
||||
void end_leased_operation(std::uint64_t generation) noexcept;
|
||||
|
||||
private:
|
||||
|
||||
sqlite3* m_db = nullptr;
|
||||
explicit Database(std::shared_ptr<detail::ConnectionState> conn) noexcept;
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
};
|
||||
|
||||
/// Free-function helper matching roadmap `open_database(path, OpenOptions)`.
|
||||
[[nodiscard]] inline Result<Database> open_database(
|
||||
const std::filesystem::path& path,
|
||||
OpenOptions options = {})
|
||||
{
|
||||
return Database::open_with_options(path, std::move(options));
|
||||
}
|
||||
|
||||
} // namespace Void::Sqlite
|
||||
@@ -0,0 +1,405 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Sqlite
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class OpenMode : std::uint8_t {
|
||||
ReadOnly,
|
||||
ReadWrite,
|
||||
ReadWriteCreate
|
||||
};
|
||||
|
||||
enum class JournalMode : std::uint8_t {
|
||||
Wal,
|
||||
Rollback
|
||||
};
|
||||
|
||||
enum class SyncMode : std::uint8_t {
|
||||
Full,
|
||||
Normal
|
||||
};
|
||||
|
||||
enum class BeginMode : std::uint8_t {
|
||||
Deferred,
|
||||
Immediate,
|
||||
Exclusive
|
||||
};
|
||||
|
||||
enum class CheckpointMode : std::uint8_t {
|
||||
Passive,
|
||||
Full,
|
||||
Restart,
|
||||
Truncate
|
||||
};
|
||||
|
||||
enum class TransactionState : std::uint8_t {
|
||||
Active,
|
||||
Committed,
|
||||
RolledBack,
|
||||
RecoveryRequired
|
||||
};
|
||||
|
||||
enum class ColumnType : std::uint8_t {
|
||||
Null = 0,
|
||||
Integer = 1,
|
||||
Real = 2,
|
||||
Text = 3,
|
||||
Blob = 4
|
||||
};
|
||||
|
||||
enum class SqliteErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
busy = 2,
|
||||
locked = 3,
|
||||
constraint = 4,
|
||||
corrupt = 5,
|
||||
io = 6,
|
||||
readonly = 7,
|
||||
full = 8,
|
||||
misuse = 9,
|
||||
not_found = 10,
|
||||
range = 11,
|
||||
type_mismatch = 12,
|
||||
trailing_sql = 13,
|
||||
statement_limit = 14,
|
||||
size_limit = 15,
|
||||
unsupported_pragma = 16,
|
||||
recovery_required = 17,
|
||||
closed = 18,
|
||||
cancelled = 19,
|
||||
timeout = 20,
|
||||
overloaded = 21,
|
||||
migration_error = 22,
|
||||
backup_error = 23,
|
||||
sqlite_error = 24
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_sqlite_error(
|
||||
SqliteErrorCode code,
|
||||
std::string message,
|
||||
int primary_code = 0,
|
||||
int extended_code = 0)
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case SqliteErrorCode::none:
|
||||
case SqliteErrorCode::sqlite_error:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SqliteErrorCode::invalid_argument:
|
||||
case SqliteErrorCode::misuse:
|
||||
case SqliteErrorCode::range:
|
||||
case SqliteErrorCode::type_mismatch:
|
||||
case SqliteErrorCode::trailing_sql:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case SqliteErrorCode::busy:
|
||||
case SqliteErrorCode::locked:
|
||||
case SqliteErrorCode::constraint:
|
||||
case SqliteErrorCode::recovery_required:
|
||||
case SqliteErrorCode::migration_error:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case SqliteErrorCode::corrupt:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case SqliteErrorCode::io:
|
||||
case SqliteErrorCode::readonly:
|
||||
case SqliteErrorCode::backup_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case SqliteErrorCode::full:
|
||||
case SqliteErrorCode::statement_limit:
|
||||
case SqliteErrorCode::size_limit:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case SqliteErrorCode::not_found:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case SqliteErrorCode::unsupported_pragma:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case SqliteErrorCode::closed:
|
||||
case SqliteErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case SqliteErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case SqliteErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
}
|
||||
|
||||
if (primary_code != 0 || extended_code != 0) {
|
||||
message += " (sqlite rc=";
|
||||
message += std::to_string(primary_code);
|
||||
if (extended_code != 0 && extended_code != primary_code) {
|
||||
message += ", extended=";
|
||||
message += std::to_string(extended_code);
|
||||
}
|
||||
message += ")";
|
||||
}
|
||||
|
||||
return Error{
|
||||
kind,
|
||||
std::move(message),
|
||||
ErrorCode{Void::Result::kSqliteErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct SqliteLimits {
|
||||
std::size_t max_live_statements{128};
|
||||
std::size_t max_sql_bytes{1024ULL * 1024ULL};
|
||||
std::size_t max_value_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_query_all_rows{10000};
|
||||
std::size_t max_query_all_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_cached_statements{64};
|
||||
std::size_t max_cache_bytes{8ULL * 1024ULL * 1024ULL};
|
||||
std::chrono::milliseconds busy_timeout{5000};
|
||||
std::uint64_t wal_checkpoint_threshold_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t wal_warn_threshold_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t wal_stop_writes_threshold_bytes{256ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_queued_jobs{1024};
|
||||
std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Result<void> validate_limits(const SqliteLimits& limits)
|
||||
{
|
||||
if (limits.max_live_statements == 0 ||
|
||||
limits.max_sql_bytes == 0 ||
|
||||
limits.max_value_bytes == 0 ||
|
||||
limits.max_query_all_rows == 0 ||
|
||||
limits.max_query_all_bytes == 0 ||
|
||||
limits.max_cached_statements == 0 ||
|
||||
limits.max_cache_bytes == 0 ||
|
||||
limits.busy_timeout.count() < 0 ||
|
||||
limits.wal_checkpoint_threshold_bytes == 0 ||
|
||||
limits.wal_warn_threshold_bytes == 0 ||
|
||||
limits.wal_stop_writes_threshold_bytes == 0 ||
|
||||
limits.max_queued_jobs == 0 ||
|
||||
limits.max_pending_input_bytes == 0) {
|
||||
return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::invalid_argument,
|
||||
"SqliteLimits must specify positive finite bounds"));
|
||||
}
|
||||
if (limits.wal_checkpoint_threshold_bytes > limits.wal_warn_threshold_bytes ||
|
||||
limits.wal_warn_threshold_bytes > limits.wal_stop_writes_threshold_bytes) {
|
||||
return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::invalid_argument,
|
||||
"SqliteLimits WAL thresholds must be non-decreasing"));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
struct OpenOptions {
|
||||
OpenMode mode{OpenMode::ReadWriteCreate};
|
||||
JournalMode journal_mode{JournalMode::Wal};
|
||||
SyncMode sync_mode{SyncMode::Full};
|
||||
bool foreign_keys{true};
|
||||
bool allow_extension_loading{false};
|
||||
SqliteLimits limits{};
|
||||
std::function<void(std::string_view)> diagnostic_hook{};
|
||||
};
|
||||
|
||||
struct EffectiveCapabilities {
|
||||
std::string sqlite_version{};
|
||||
int sqlite_version_number{0};
|
||||
int threadsafe_mode{0};
|
||||
bool in_memory{false};
|
||||
bool read_only{false};
|
||||
std::string journal_mode{};
|
||||
int synchronous_mode{0};
|
||||
bool foreign_keys{false};
|
||||
bool extension_loading_enabled{false};
|
||||
};
|
||||
|
||||
struct ValueView {
|
||||
using Storage = std::variant<
|
||||
std::nullptr_t,
|
||||
std::int64_t,
|
||||
double,
|
||||
std::string_view,
|
||||
std::span<const std::byte>>;
|
||||
|
||||
Storage value{nullptr};
|
||||
|
||||
constexpr ValueView() noexcept = default;
|
||||
constexpr ValueView(std::nullptr_t) noexcept : value(nullptr) {}
|
||||
constexpr ValueView(std::int64_t v) noexcept : value(v) {}
|
||||
constexpr ValueView(int v) noexcept : value(static_cast<std::int64_t>(v)) {}
|
||||
constexpr ValueView(double v) noexcept : value(v) {}
|
||||
constexpr ValueView(std::string_view v) noexcept : value(v) {}
|
||||
ValueView(const std::string& v) noexcept : value(std::string_view{v}) {}
|
||||
constexpr ValueView(const char* v) noexcept
|
||||
: value(v ? Storage{std::string_view{v}} : Storage{nullptr}) {}
|
||||
constexpr ValueView(std::span<const std::byte> v) noexcept : value(v) {}
|
||||
|
||||
[[nodiscard]] constexpr ColumnType type() const noexcept
|
||||
{
|
||||
switch (value.index()) {
|
||||
case 0: return ColumnType::Null;
|
||||
case 1: return ColumnType::Integer;
|
||||
case 2: return ColumnType::Real;
|
||||
case 3: return ColumnType::Text;
|
||||
case 4: return ColumnType::Blob;
|
||||
default: return ColumnType::Null;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool is_null() const noexcept
|
||||
{
|
||||
return std::holds_alternative<std::nullptr_t>(value);
|
||||
}
|
||||
};
|
||||
|
||||
struct OwnedValue {
|
||||
using Storage = std::variant<
|
||||
std::nullptr_t,
|
||||
std::int64_t,
|
||||
double,
|
||||
std::string,
|
||||
std::vector<std::byte>>;
|
||||
|
||||
Storage value{nullptr};
|
||||
|
||||
OwnedValue() noexcept = default;
|
||||
OwnedValue(std::nullptr_t) noexcept : value(nullptr) {}
|
||||
OwnedValue(std::int64_t v) noexcept : value(v) {}
|
||||
OwnedValue(double v) noexcept : value(v) {}
|
||||
OwnedValue(std::string v) noexcept : value(std::move(v)) {}
|
||||
OwnedValue(std::vector<std::byte> v) noexcept : value(std::move(v)) {}
|
||||
|
||||
[[nodiscard]] ColumnType type() const noexcept
|
||||
{
|
||||
switch (value.index()) {
|
||||
case 0: return ColumnType::Null;
|
||||
case 1: return ColumnType::Integer;
|
||||
case 2: return ColumnType::Real;
|
||||
case 3: return ColumnType::Text;
|
||||
case 4: return ColumnType::Blob;
|
||||
default: return ColumnType::Null;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_null() const noexcept
|
||||
{
|
||||
return std::holds_alternative<std::nullptr_t>(value);
|
||||
}
|
||||
|
||||
[[nodiscard]] ValueView as_view() const noexcept
|
||||
{
|
||||
if (const auto* i = std::get_if<std::int64_t>(&value)) return ValueView{*i};
|
||||
if (const auto* d = std::get_if<double>(&value)) return ValueView{*d};
|
||||
if (const auto* s = std::get_if<std::string>(&value)) return ValueView{std::string_view{*s}};
|
||||
if (const auto* b = std::get_if<std::vector<std::byte>>(&value)) {
|
||||
return ValueView{std::span<const std::byte>{b->data(), b->size()}};
|
||||
}
|
||||
return ValueView{nullptr};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool operator==(const OwnedValue&) const = default;
|
||||
};
|
||||
|
||||
struct OwnedRow {
|
||||
std::vector<OwnedValue> columns{};
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept { return columns.size(); }
|
||||
[[nodiscard]] bool empty() const noexcept { return columns.empty(); }
|
||||
[[nodiscard]] const OwnedValue& operator[](std::size_t idx) const noexcept
|
||||
{
|
||||
return columns[idx];
|
||||
}
|
||||
};
|
||||
|
||||
struct CheckpointReport {
|
||||
int log_frames{0};
|
||||
int checkpointed_frames{0};
|
||||
bool busy{false};
|
||||
std::uint64_t wal_size_bytes{0};
|
||||
};
|
||||
|
||||
struct BackupOptions {
|
||||
int pages_per_step{64};
|
||||
int max_steps{1000000};
|
||||
std::chrono::milliseconds step_sleep{0};
|
||||
};
|
||||
|
||||
struct BackupReport {
|
||||
int total_pages{0};
|
||||
int remaining_pages{0};
|
||||
int steps{0};
|
||||
};
|
||||
|
||||
/// Immutable schema migration with explicit identity & checksum verification.
|
||||
struct CheckedMigration {
|
||||
int version{0};
|
||||
std::string_view id{};
|
||||
std::string_view checksum{};
|
||||
std::string_view sql{};
|
||||
};
|
||||
|
||||
struct ConnectionHealth {
|
||||
std::size_t live_statements{0};
|
||||
bool active_transaction{false};
|
||||
std::size_t open_savepoints{0};
|
||||
std::uint64_t wal_size_bytes{0};
|
||||
bool wal_checkpoint_recommended{false};
|
||||
bool wal_warn_exceeded{false};
|
||||
bool wal_write_admission_blocked{false};
|
||||
};
|
||||
|
||||
enum class AuthorizerDecision : std::uint8_t {
|
||||
Allow,
|
||||
Deny,
|
||||
Ignore
|
||||
};
|
||||
|
||||
struct FaultConfig {
|
||||
/// If non-zero, next COMMIT returns this SQLite error code without
|
||||
/// calling SQLite COMMIT (leaving transaction active so autocommit==0).
|
||||
int fail_next_commit_rc{0};
|
||||
/// If true along with fail_next_commit_rc, simulates SQLite
|
||||
/// auto-rollback before returning the error.
|
||||
bool auto_rollback_on_faulted_commit{false};
|
||||
/// If non-zero, next explicit close() returns this SQLite error code.
|
||||
int fail_next_close_rc{0};
|
||||
};
|
||||
|
||||
/// Process-local RAII guard for deterministic fault injection in tests.
|
||||
class ScopedFaultGuard
|
||||
{
|
||||
public:
|
||||
explicit ScopedFaultGuard(FaultConfig cfg) noexcept;
|
||||
~ScopedFaultGuard();
|
||||
|
||||
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
|
||||
|
||||
[[nodiscard]] static FaultConfig current() noexcept;
|
||||
|
||||
private:
|
||||
FaultConfig prev_{};
|
||||
};
|
||||
|
||||
} // namespace Void::Sqlite
|
||||
@@ -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
|
||||
Loaded 100 of 325 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user