Author SHA1 Message Date
faumaray bb0b2e1701 docs(workflow): record VL-001..VL-013 verification and completion state 2026-11-26 22:01:33 +03:00
faumaray 9920bfdaac fix(net): scope GCC -Wno-tsan to Http.cpp and fix StallServer race 2026-11-26 22:00:17 +03:00
faumaray 66baae74a0 feat(net): implement VL-004 HttpServer and VL-005 streaming HttpClient with secure TLS 2026-11-26 21:47:15 +03:00
faumaray 22c8538754 feat(crypto,archive): implement VL-007 built-in hashes and VL-006 archive creation/gzip/tar fallback 2026-11-26 20:55:45 +03:00
faumaray b50131f52e feat(system,config,sqlite): implement VL-001, VL-003, VL-010, VL-011 2026-11-26 20:45:52 +03:00
faumaray adfc8548dc feat(data,text,testing): implement VL-002 TOML, VL-008 StrictJson UTF-8, VL-009 native tests, and VL-013 Semver shorthands 2026-11-26 20:27:42 +03:00
faumaray 53d42bda42 merge: Wave 8 P2 Service, Plugin, Configuration, and Fsm lifecycle hardening 2026-11-26 20:19:09 +03:00
faumaray 9be51134e8 docs(workflow): record Wave 8 Service, Plugin, Configuration, and Fsm verification 2026-11-26 20:19:09 +03:00
faumaray cb988fa985 fix(test): hold owning ServiceHandle across hot-reload calls in FsmServiceHotReload 2026-11-26 17:10:54 +03:00
faumaray 1a54f3857e fix(plugin): use POSIX pthreads in C11 test fixture for TSan compatibility 2026-11-26 17:10:54 +03:00
faumaray 40b579d683 fix(fsm): publish terminal status after exit hooks and join worker before derived teardown 2026-11-26 17:10:54 +03:00
faumaray ef5312c4b3 feat(fsm): structured scopes, race-loser join, boundary checkpoints, and bounded supervision 2026-11-26 16:51:35 +03:00
faumaray 1dc51d5c43 feat(configuration): bounded schemas, provenance/redaction, and async transactional ReloadController 2026-11-26 16:30:30 +03:00
faumaray a24e086e47 feat(plugin): add CAbi.h v1, CModuleHost quiesce/reload/pins, and unlocked PluginManager staging 2026-11-26 16:16:29 +03:00
faumaray 1474a69ab1 feat(service): immutable snapshots, owning ServiceHandle, DAG lifecycle, and ServicePlugin split 2026-11-26 16:03:31 +03:00
faumaray 6b3dededac chore(wave8): reserve lifecycle error domains, support .h headers, add task specs 2026-11-26 15:57:01 +03:00
faumaray d83d0f4533 merge: Wave 7 P2 Sqlite, SqliteAsync, and Storage engine 2026-11-26 15:48:13 +03:00
faumaray 76ad7d1b39 docs(workflow): record Wave 7 verification evidence and tasks 2026-11-26 15:48:13 +03:00
faumaray 84e6fe81ed fix(sqlite): eliminate lock-order inversion between progress trampoline and interrupt_mu 2026-11-26 15:43:02 +03:00
faumaray fdf0da5ca8 feat(storage): implement original V1 durable Storage engine, tools, and async adapter 2026-11-26 15:32:43 +03:00
faumaray 427cc9a843 feat(sqlite): harden Sqlite lifecycle/transactions/migrations/ops and add SqliteAsync pool 2026-11-26 15:17:59 +03:00
faumaray 9925ea1764 docs(workflow): add Wave 7 task specs for Sqlite, SqliteAsync, and Storage 2026-11-25 21:15:10 +03:00
faumaray 43922d1ad4 merge: Wave 6B P2 Crypto, Security, Archive, and Update hardening 2026-11-25 21:12:30 +03:00
faumaray 9ef425c36c docs(workflow): record Wave 6B verification evidence and tasks 2026-11-25 21:12:30 +03:00
faumaray 47736cb6ce feat(update): fix schema-3 verify-before-parse and add replay floor, TrustStore, pin pruning, and InstallCoordinator 2026-11-25 21:04:52 +03:00
faumaray 00d7478335 feat(archive): add streaming Reader, atomic StagedTree publication, reproducible creation, and isolated worker 2026-11-25 20:54:10 +03:00
faumaray 713d2dc656 feat(security): add SecureBuffer, VSEC envelopes, authorization, and SecurityAsync Authenticator 2026-11-25 20:44:31 +03:00
faumaray eb42228604 feat(crypto): harden Crypto primitives and add optional CryptoAsync adapter 2026-11-25 06:28:50 +03:00
faumaray 8a1c15f9c0 docs(workflow): add Wave 6B task specs for Crypto, Security, Archive, Update 2026-11-25 06:03:36 +03:00
faumaray acd77ee67a feat(data): support RFC 8259 decimal numbers in StrictJson 2026-11-25 05:59:21 +03:00
faumaray 9931c5ffc4 Merge feat/roadmap-p2-wave6a: P2 System, SystemAsync, and IPC 2026-11-24 15:37:17 +03:00
faumaray e43eee738c docs(workflow): record Wave 6A verification evidence and tasks 2026-11-24 15:36:45 +03:00
faumaray 39a48d5c0a feat(IPC): add V1 VDIP framed codec, quota reservations, local UDS/pipe transport, full-duplex Session, and IPCOnly consumer (S-IPC-01..03) 2026-11-24 15:27:40 +03:00
faumaray 9a3c5d86ef feat(SystemAsync): add async IO ProcessManager/communicate and shared WatcherService with WatchSubscription (M-SYSTEM-03, M-SYSTEM-04) 2026-11-24 14:46:46 +03:00
faumaray fcdbc063b2 feat(System): harden OwnedFd/Child process spawn, full-duplex bounds, durable replace_file, safe TempFile/TempDir, and SystemOnly consumer (M-SYSTEM-01, M-SYSTEM-02, M-SYSTEM-05) 2026-11-24 14:32:05 +03:00
faumaray 3f67b1ecb7 chore(wave6a): reserve P2 error domains, guard IO pipe SIGPIPE, extend ProcessHelper, and add Wave 6A specs 2026-11-24 10:56:39 +03:00
faumaray 44799602c9 Merge feat/roadmap-p2-wave5: P2 Observability, Resilience, Log, and Stacktrace 2026-11-24 10:39:26 +03:00
225 changed files with 61386 additions and 2353 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 4.0.0) 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) if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON) option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
elseif(NOT DEFINED BUILD_SHARED_LIBS) elseif(NOT DEFINED BUILD_SHARED_LIBS)
+82 -2
View File
@@ -158,9 +158,89 @@ function(void_fetch_dependency DEP_NAME)
endif() endif()
if(DEP_NAME STREQUAL "SQLite3") if(DEP_NAME STREQUAL "SQLite3")
if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3) if(TARGET SQLite3::SQLite3)
find_package(SQLite3 REQUIRED) return()
endif() 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) if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3) add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif() endif()
+3 -1
View File
@@ -12,7 +12,9 @@ function(void_add_module MODULE_NAME)
set(ALIAS ${PROJECT_NAME}::${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 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) foreach(_excl IN LISTS ARG_EXCLUDE_HEADERS)
list(REMOVE_ITEM HDR "${CMAKE_CURRENT_SOURCE_DIR}/include/${_excl}") list(REMOVE_ITEM HDR "${CMAKE_CURRENT_SOURCE_DIR}/include/${_excl}")
endforeach() endforeach()
+133 -6
View File
@@ -1,8 +1,8 @@
# Workflow state # Workflow state
Updated: 2026-11-24. Updated: 2026-11-26.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave5` (from `main` Repository: VoidLibrary; active branch `feat/upstream-vbs-requests` (from `main`
at `1e901ce`, merged Waves 1–4B and pushed to `origin/main`). at `53d42bd`, merged Waves 1–8 and pushed to `origin/main`).
## Completed objective ## Completed objective
@@ -215,8 +215,135 @@ while leaving local untracked files untouched.
`binary_reader_u64_be` 2.24 ns, `data_json_parse_small_object` 576.81 ns, `binary_reader_u64_be` 2.24 ns, `data_json_parse_small_object` 576.81 ns,
`data_json_serialize_small_object` 284.87 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.
## Ownership and next step ## Ownership and next step
Waves 1–5 (`P0`, `P1`, and `P2` Operations Foundations: `Observability`, `Resilience`, Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`,
`Log`, `Stacktrace`) are complete and verified on `feat/roadmap-p2-wave5`, ready to merge `Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`,
into `main`, push to `origin`, and proceed continuously to **P2 Wave 6**. `Sqlite`/`SqliteAsync`/`Storage` `G-STORE`,
`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`)
and the VoidBuildSystem upstream feature wave (`VL-001`..`VL-013`) are complete,
verified, and merged to `main` via `--no-ff`.
+49
View File
@@ -70,6 +70,55 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| 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 | | 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) | | 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) |
All workers share the checkout and have disjoint file ownership defined in their 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 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 changes. No worker owns application code, build files, existing docs/short-url.md, or Git
+61
View File
@@ -230,3 +230,64 @@ Branch: `feat/roadmap-p2-wave5` (branched from `main` at `1e901ce`, which was pu
| 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 | | 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 | | 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 | | 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 |
@@ -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'
```
+24
View File
@@ -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,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,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,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 @@
# 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 @@
# 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'
```
+27
View File
@@ -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,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.
+191 -4
View File
@@ -1,11 +1,19 @@
#pragma once #pragma once
#include <Void/Archive/Types.hpp>
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <filesystem> #include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string_view>
#include <vector>
namespace Void::Archive namespace Void::Archive
{ {
@@ -21,12 +29,191 @@ namespace Void::Archive
std::uint64_t bytes{0}; std::uint64_t bytes{0};
}; };
/// Extract a tar/tar.zst archive without invoking an external process. /// Returns true if Void::Archive was built with LibArchive support (required
/// Only regular files and directories are accepted. Absolute/traversal /// for .tar.zst and .tar.gz compression/decompression; uncompressed USTAR/PAX
/// paths, links, special files, duplicates and configured size/count /// .tar reading and writing work with zero external dependencies).
/// overages fail the whole operation. [[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> [[nodiscard]] Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path& archivePath, extract(const std::filesystem::path& archivePath,
const std::filesystem::path& destination, const std::filesystem::path& destination,
const ExtractionOptions& options = {}); 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 } // namespace Void::Archive
+347
View File
@@ -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
+85 -5
View File
@@ -2,7 +2,10 @@
#include <Void/Core/Meta.hpp> #include <Void/Core/Meta.hpp>
#include <cstdint>
#include <expected> #include <expected>
#include <functional>
#include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view> #include <string_view>
@@ -11,23 +14,56 @@
namespace Void::Argparse 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 // ── Parser
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// Fluent command-line argument parser. // Fluent command-line argument parser.
// //
// Supports: // Supports:
// --flag, -f boolean flag (default false, set to true by // --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 (= or space separator)
// --key value option with value // --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 // positional args collected in declaration order
// --help / -h auto-generated help text // --help / -h auto-generated help text (ParseOutcome::Help)
class Parser class Parser
{ {
public: public:
explicit Parser(std::string program, std::string description = {}); 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. // Add a boolean flag.
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name // long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name
@@ -43,6 +79,12 @@ namespace Void::Argparse
std::string_view description, std::string_view description,
std::optional<std::string>& out); 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 // Add an option with a default value. out is always set after
// parse(). // parse().
Parser& option_default(std::string_view long_name, Parser& option_default(std::string_view long_name,
@@ -55,7 +97,28 @@ namespace Void::Argparse
Parser& positional(std::string_view name, Parser& positional(std::string_view name,
std::string_view description, std::string& out); 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> [[nodiscard]] std::expected<void, std::string>
parse(int argc, const char* const* argv) const; parse(int argc, const char* const* argv) const;
@@ -70,18 +133,33 @@ namespace Void::Argparse
}; };
struct OptionEntry { struct OptionEntry {
std::string lng, sht, desc, def; std::string lng, sht, desc, def;
std::optional<std::string>* out_opt; std::optional<std::string>* out_opt{nullptr};
std::string* out_str; std::string* out_str{nullptr};
std::vector<std::string>* out_many{nullptr};
}; };
struct PosEntry { struct PosEntry {
std::string name, desc; std::string name, desc;
std::string* out; 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::string program_, description_;
std::vector<FlagEntry> flags_; std::vector<FlagEntry> flags_;
std::vector<OptionEntry> options_; std::vector<OptionEntry> options_;
std::vector<PosEntry> positionals_; 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 // ── reflective options struct
@@ -147,6 +225,8 @@ namespace Void::Argparse
parser.flag(lng, sht, desc, out.[:m:]); parser.flag(lng, sht, desc, out.[:m:]);
} else if constexpr (Void::Meta::is_optional_v<MT>) { } else if constexpr (Void::Meta::is_optional_v<MT>) {
parser.option(lng, sht, desc, out.[:m:]); 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>) { } else if constexpr (std::same_as<MT, std::string>) {
const std::string def = out.[:m:]; const std::string def = out.[:m:];
parser.option_default(lng, sht, desc, out.[:m:], def); parser.option_default(lng, sht, desc, out.[:m:], def);
+15
View File
@@ -51,6 +51,21 @@ namespace Void::Configuration
}; };
struct Required { 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 #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
+90
View File
@@ -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
+120 -6
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <Void/Crypto/Types.hpp>
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
@@ -12,27 +13,37 @@
namespace Void::Crypto namespace Void::Crypto
{ {
enum class HashAlgorithm { Sha1, Sha256, Sha512 }; enum class HashAlgorithm { Sha1, Sha256, Sha512, Blake2b256, Blake2b512 };
using Digest = std::vector<std::byte>; 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 class Hasher
{ {
public: public:
[[nodiscard]] static Void::Result::Result<Hasher> [[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm); create(HashAlgorithm algorithm);
[[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm,
const ProviderOptions& provider);
~Hasher(); ~Hasher();
Hasher(Hasher&&) noexcept; Hasher(Hasher&&) noexcept;
Hasher& operator=(Hasher&&) noexcept; Hasher& operator=(Hasher&&) noexcept;
Hasher(const Hasher&) = delete; Hasher(const Hasher&) = delete;
Hasher& operator=(const Hasher&) = delete; Hasher& operator=(const Hasher&) = delete;
[[nodiscard]] HasherState state() const noexcept;
[[nodiscard]] Void::Result::Result<void> [[nodiscard]] Void::Result::Result<void>
update(std::span<const std::byte> data); update(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void> [[nodiscard]] Void::Result::Result<void>
update(std::string_view data); update(std::string_view data);
/// Finalize this hash. Calling finalize or update again is an /// 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(); [[nodiscard]] Void::Result::Result<Digest> finalize();
private: private:
@@ -44,10 +55,21 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
hash(HashAlgorithm algorithm, std::span<const std::byte> data); 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, [[nodiscard]] Void::Result::Result<Digest> hash(HashAlgorithm algorithm,
std::string_view data); std::string_view data);
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path); 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> [[nodiscard]] Void::Result::Result<Digest>
sha1(std::span<const std::byte> data); sha1(std::span<const std::byte> data);
@@ -58,21 +80,113 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha512(std::span<const std::byte> data); sha512(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view 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> [[nodiscard]] Void::Result::Result<Digest>
sha1File(const std::filesystem::path& path); sha1File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha256File(const std::filesystem::path& path); sha256File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest> [[nodiscard]] Void::Result::Result<Digest>
sha512File(const std::filesystem::path& path); 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; /// Move-only owning Ed25519 private key handle. Has no implicit copy,
inline constexpr std::size_t Ed25519SignatureSize = 64; /// 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. /// Verify an Ed25519 detached signature over the exact message bytes.
/// Invalid key/signature sizes are errors; a well-formed but invalid /// Invalid key/signature sizes or oversized messages are errors; a
/// signature returns false. /// well-formed but invalid signature returns false.
[[nodiscard]] Void::Result::Result<bool> [[nodiscard]] Void::Result::Result<bool>
verifyEd25519(std::span<const std::byte> message, verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte> signature, std::span<const std::byte> signature,
std::span<const std::byte> publicKey); 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 } // namespace Void::Crypto
+288
View File
@@ -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
+321 -16
View File
@@ -1,6 +1,8 @@
#pragma once #pragma once
#include <array>
#include <charconv> #include <charconv>
#include <cmath>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
@@ -16,6 +18,11 @@ namespace Void::Json::Strict
{ {
inline constexpr std::size_t default_maximum_depth{64U}; inline constexpr std::size_t default_maximum_depth{64U};
struct ParseOptions {
std::size_t maximumDepth{default_maximum_depth};
bool allowDecimals{true};
};
struct ParseError { struct ParseError {
std::size_t offset{}; std::size_t offset{};
std::string message; std::string message;
@@ -24,8 +31,8 @@ namespace Void::Json::Strict
struct Value { struct Value {
using Array = std::vector<Value>; using Array = std::vector<Value>;
using Object = std::map<std::string, Value, std::less<>>; using Object = std::map<std::string, Value, std::less<>>;
std::variant<std::nullptr_t, bool, std::int64_t, std::string, Array, std::variant<std::nullptr_t, bool, std::int64_t, double,
Object> std::string, Array, Object>
value; value;
}; };
@@ -35,13 +42,79 @@ namespace Void::Json::Strict
ParseError error; 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 class Parser final
{ {
public: public:
explicit Parser(const std::string_view input, explicit Parser(const std::string_view input,
const std::size_t maximumDepth) const ParseOptions options)
: input_{input}, maximumDepth_{maximumDepth} : input_{input}, options_{options}
{ {
} }
@@ -173,6 +246,18 @@ namespace Void::Json::Strict
fail("control character in string"); fail("control character in string");
} }
if (value != '\\') { 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)); output.push_back(static_cast<char>(value));
continue; 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() [[nodiscard]] Value parseNumber()
{ {
const std::size_t start = position_; const std::size_t start = position_;
@@ -242,21 +342,52 @@ namespace Void::Json::Strict
} }
if (input_[position_] == '0') { if (input_[position_] == '0') {
++position_; ++position_;
if (position_ < input_.size() &&
isDigit(input_[position_])) {
fail("leading zero in number");
}
} else { } else {
if (input_[position_] < '1' || if (input_[position_] < '1' ||
input_[position_] > '9') { input_[position_] > '9') {
fail("invalid number"); fail("invalid number");
} }
while (position_ < input_.size() && static_cast<void>(consumeDigits());
input_[position_] >= '0' && }
input_[position_] <= '9') { bool isDecimal = false;
++position_; if (position_ < input_.size() && input_[position_] == '.') {
isDecimal = true;
++position_;
if (consumeDigits() == 0U) {
fail("incomplete fractional part");
} }
} }
if (position_ < input_.size() && if (position_ < input_.size() &&
(input_[position_] == '.' || input_[position_] == 'e' || (input_[position_] == 'e' || input_[position_] == 'E')) {
input_[position_] == 'E')) { isDecimal = true;
fail("floating-point numbers are not supported"); ++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{}; std::int64_t value{};
const auto result = const auto result =
@@ -330,7 +461,8 @@ namespace Void::Json::Strict
[[nodiscard]] Value parseValue(const std::size_t depth) [[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"); fail("nesting limit or unexpected end of input");
} }
switch (input_[position_]) { switch (input_[position_]) {
@@ -351,8 +483,7 @@ namespace Void::Json::Strict
return Value{nullptr}; return Value{nullptr};
default: default:
if (input_[position_] == '-' || if (input_[position_] == '-' ||
(input_[position_] >= '0' && isDigit(input_[position_])) {
input_[position_] <= '9')) {
return parseNumber(); return parseNumber();
} }
fail("invalid value"); fail("invalid value");
@@ -360,17 +491,191 @@ namespace Void::Json::Strict
} }
std::string_view input_; std::string_view input_;
std::size_t maximumDepth_; ParseOptions options_;
std::size_t position_{}; std::size_t position_{};
}; };
} // namespace Detail } // 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> [[nodiscard]] inline std::expected<Value, ParseError>
parse(const std::string_view input, parse(const std::string_view input,
const std::size_t maximumDepth = default_maximum_depth) 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 { try {
return Detail::Parser{input, maximumDepth}.parse(); std::string out;
Detail::serialize_value(out, value, 0U, maximumDepth);
return out;
} catch (const Detail::ParseFailure& failure) { } catch (const Detail::ParseFailure& failure) {
return std::unexpected{failure.error}; return std::unexpected{failure.error};
} }
File diff suppressed because it is too large. Load diff
+81 -18
View File
@@ -1,41 +1,90 @@
#pragma once #pragma once
#include <Void/Fsm/Detail/Engine.hpp> #include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono> #include <chrono>
#include <coroutine> #include <coroutine>
#include <optional> #include <optional>
#include <span> #include <span>
#include <stop_token>
#include <typeinfo> #include <typeinfo>
#include <utility> #include <utility>
namespace Void::Fsm::Detail namespace Void::Fsm::Detail
{ {
/// One awaiter for every "wait for an event (optionally with a deadline)" struct WaiterCancelFn {
/// operation on a machine. `Storage` is the type-list container (a ExecutionContext* ctx{nullptr};
/// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is ExecutionContext::WaiterId waiter_id{0};
/// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the
/// awaited value (the matched event, an optional on timeout, a variant, void operator()() const
/// …). Built on ExecutionContext::{try_take_any,set_waiter}. {
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 { template <typename Storage, typename Resume> struct EventAwaiter {
ExecutionContext* ctx; ExecutionContext* ctx{nullptr};
Storage types; Storage types{};
EventEnvelope env; EventEnvelope env{};
bool timed_out{false}; bool timed_out{false};
std::optional<std::chrono::steady_clock::time_point> deadline; bool cancelled{false};
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{};
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() [[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) 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: private:
@@ -49,10 +98,24 @@ namespace Void::Fsm::Detail
template <typename Storage, typename Resume> template <typename Storage, typename Resume>
[[nodiscard]] auto make_event_awaiter( [[nodiscard]] auto make_event_awaiter(
ExecutionContext* ctx, Storage types, ExecutionContext* ctx, Storage types,
std::optional<std::chrono::steady_clock::time_point> deadline, std::optional<Time::MonotonicClock::time_point> deadline,
Resume resume) Resume resume,
ExecutionContext::ScopeId scope = ExecutionContext::kNoScope,
std::stop_token scope_stop = {}, std::stop_token user_stop = {})
{ {
return EventAwaiter<Storage, Resume>{ 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 } // namespace Void::Fsm::Detail
+141 -54
View File
@@ -4,6 +4,8 @@
#include <Void/Async/MpscQueue.hpp> #include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp> #include <Void/Async/Task.hpp>
#include <Void/Fsm/StateKey.hpp> #include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <any> #include <any>
#include <atomic> #include <atomic>
@@ -14,6 +16,7 @@
#include <deque> #include <deque>
#include <functional> #include <functional>
#include <map> #include <map>
#include <memory>
#include <mutex> #include <mutex>
#include <optional> #include <optional>
#include <semaphore> #include <semaphore>
@@ -28,17 +31,14 @@ namespace Void::Fsm::Detail
{ {
/// Type-erased state. Concrete states derive the single Machine<Derived>:: /// Type-erased state. Concrete states derive the single Machine<Derived>::
/// State base; the engine drives each via a signature-inferred per-state /// State base; the engine drives each via a signature-inferred per-state
/// thunk (entry / reactive table / continuation handlers). /// thunk (entry / continuation handlers).
class StateBase class StateBase
{ {
public: public:
virtual ~StateBase() = default; virtual ~StateBase() = default;
/// Optional entry/exit lifecycle hooks (default no-ops). The /// Optional entry/exit lifecycle hooks (default no-ops).
/// state's behaviour (entry / reactive table / continuation
/// handlers) is discovered by signature via a per-state driver
/// thunk — there is no virtual run().
virtual Coro::Task<void> on_enter(); virtual Coro::Task<void> on_enter();
virtual Coro::Task<void> on_exit(); virtual Coro::Task<void> on_exit();
}; };
@@ -46,18 +46,28 @@ namespace Void::Fsm::Detail
struct EventEnvelope { struct EventEnvelope {
const std::type_info* type{nullptr}; const std::type_info* type{nullptr};
std::any value; std::any value;
std::size_t bytes{0};
}; };
/// Shared execution substrate for a machine and any machines it nests: /// Shared execution substrate for a machine and any machines it nests:
/// one executor + one worker thread + one typed event mailbox. A single /// one logical strand (owned worker, embedder pump(), or borrowed external
/// consumer (the worker, or the embedder via pump()) touches all /// executor) + bounded event mailbox + reserved control lane + Clock-driven
/// mailbox state, so state code runs lock-free and single-threaded; /// timers. Cross-thread posts enqueue owned envelopes; only the active
/// cross-thread post() only enqueues. /// consumer strand touches waiter/timer/buffer tables.
class ExecutionContext class ExecutionContext
: public std::enable_shared_from_this<ExecutionContext>
{ {
public: 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();
ExecutionContext(const ExecutionContext&) = delete; ExecutionContext(const ExecutionContext&) = delete;
@@ -67,14 +77,61 @@ namespace Void::Fsm::Detail
{ {
return m_executor; 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); 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 // ── strand-only scope/waiter/timer APIs ──────────────────────
// run on the executor, and from the worker drain). [[nodiscard]] ScopeId allocate_scope() noexcept
{
using TimerId = std::uint64_t; return m_next_scope.fetch_add(1, std::memory_order_relaxed);
}
/// Pop the oldest buffered event whose type is in `types`. /// Pop the oldest buffered event whose type is in `types`.
[[nodiscard]] bool [[nodiscard]] bool
@@ -82,68 +139,66 @@ namespace Void::Fsm::Detail
EventEnvelope& out); EventEnvelope& out);
/// Suspend until an event of one of `types` arrives, or (if /// Suspend until an event of one of `types` arrives, or (if
/// `deadline` is set) the deadline passes. `slot` receives the /// `deadline` is set) the deadline passes, or the waiter/scope is
/// matched event; `*timed_out` is set true on timeout. /// cancelled.
void set_waiter( WaiterId set_waiter(
std::span<const std::type_info* const> types, std::span<const std::type_info* const> types,
std::coroutine_handle<> cont, EventEnvelope* slot, std::coroutine_handle<> cont, EventEnvelope* slot,
bool* timed_out, 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 void cancel_waiter(WaiterId id);
/// cancel_timer. void cancel_scope(ScopeId scope);
TimerId add_timer(std::chrono::steady_clock::time_point deadline, void purge_scope(ScopeId scope);
std::function<void()> void drain_control_queue();
on_fire);
/// 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); void cancel_timer(TimerId id);
// ── worker lifecycle ───────────────────────────────────────── // ── worker / pump lifecycle ──────────────────────────────────
/// Spawn the worker thread (idempotent).
void start_worker(); void start_worker();
/// Mark finished and wake the worker so it can exit.
void finish(); void finish();
/// Stop and join the worker.
void stop(); void stop();
/// Join the worker without forcing finish (waits for the
/// driver to finish() on its own).
void join(); void join();
[[nodiscard]] bool finished() const noexcept [[nodiscard]] bool finished() const noexcept
{ {
return m_done.load(std::memory_order_acquire); return m_done.load(std::memory_order_acquire);
} }
/// Embedder-driven step: deliver queued events + run ready /// Embedder-driven step: drain control lane, fire due timers on
/// coroutines. Returns work done count. Single consumer only. /// injected clock, deliver up to max_events_per_turn /
/// A no-op (returns 0) while paused. /// max_turn_duration user events, and drain internal executor.
std::size_t pump(); std::size_t pump();
/// Pause / resume event processing. While paused the worker stops /// Called on external executor threads via scheduled task.
/// draining (and pump() is a no-op); posted events buffer. void run_external_pump_step();
void set_paused(bool paused);
/// Wake the consumer (e.g. to re-check an external jump request). void set_paused(bool paused);
void nudge() { wake(); } void nudge() { wake(); }
private: private:
void deliver(EventEnvelope& env); struct BufferedEvent {
void run_loop(); std::any value;
void wake() noexcept; std::size_t bytes{0};
void fire_due_timers(); };
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
next_deadline() const;
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 { struct Waiter {
WaiterId id{0}; WaiterId id{0};
ScopeId scope{kNoScope};
std::vector<const std::type_info*> types; std::vector<const std::type_info*> types;
std::coroutine_handle<> cont{}; std::coroutine_handle<> cont{};
EventEnvelope* slot{nullptr}; EventEnvelope* slot{nullptr};
bool* timed_out{nullptr}; bool* timed_out{nullptr};
bool* cancelled{nullptr};
TimerId timer{0}; TimerId timer{0};
[[nodiscard]] bool wants(const std::type_info& t) const [[nodiscard]] bool wants(const std::type_info& t) const
@@ -156,20 +211,52 @@ namespace Void::Fsm::Detail
return false; 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; std::vector<Waiter> m_waiters;
WaiterId m_next_waiter{1}; 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; std::map<TimerId, Timer> m_timers;
TimerId m_next_timer{1}; 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::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false}; std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_pump_scheduled{false};
std::atomic<bool> m_done{false}; std::atomic<bool> m_done{false};
std::atomic<bool> m_paused{false}; std::atomic<bool> m_paused{false};
std::atomic<bool> m_worker_started{false}; std::atomic<bool> m_worker_started{false};
+1511 -397
View File
File diff suppressed because it is too large. Load diff
+407 -41
View File
@@ -1,27 +1,73 @@
#pragma once #pragma once
#include <Void/Fsm/StateKey.hpp> #include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Service/Registry.hpp> #include <Void/Service/Registry.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef> #include <cstddef>
#include <cstdint>
#include <functional>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <optional>
#include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
namespace Void::Fsm 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 namespace Detail
{ {
// Type-erased supervised FSM. Models wrap a concrete Machine<R> // 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 class FsmConcept
{ {
public: public:
virtual ~FsmConcept() = default; virtual ~FsmConcept() = default;
virtual void stop() = 0; virtual void stop() = 0;
virtual void restart() = 0;
[[nodiscard]] virtual Status status() const = 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 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 stop() override { m_fsm->stop(); }
void restart() override { m_fsm->restart(); }
[[nodiscard]] Status status() const override [[nodiscard]] Status status() const override
{ {
return m_fsm->status(); 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; } [[nodiscard]] F& get() noexcept { return *m_fsm; }
@@ -45,10 +109,27 @@ namespace Void::Fsm
std::unique_ptr<F> m_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 } // namespace Detail
/// A non-owning supervision handle to a launched FSM: query status and /// Owning handle to a supervised FSM instance: holds a shared_ptr so
/// stop it. The Orchestrator owns the FSM's lifetime. /// immutable termination evidence and any still-required cleanup ownership
/// survive even after the Orchestrator releases a finished entry from
/// active supervision.
class FsmHandle class FsmHandle
{ {
public: public:
@@ -57,48 +138,92 @@ namespace Void::Fsm
void stop() const void stop() const
{ {
if (m_impl) { if (m_entry && m_entry->model) {
m_impl->stop(); m_entry->model->stop();
} }
} }
[[nodiscard]] Status status() const [[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(); if (!m_entry) {
return s == Status::Succeeded || s == Status::Failed; 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 [[nodiscard]] explicit operator bool() const noexcept
{ {
return m_impl != nullptr; return m_entry != nullptr && m_entry->model != nullptr;
} }
private: private:
friend class Orchestrator; friend class Orchestrator;
explicit FsmHandle(std::shared_ptr<Detail::FsmConcept> impl) explicit FsmHandle(std::shared_ptr<Detail::SupervisedEntry> entry)
: m_impl(std::move(impl)) : m_entry(std::move(entry))
{ {
} }
std::shared_ptr<Detail::FsmConcept> m_impl; std::shared_ptr<Detail::SupervisedEntry> m_entry;
}; };
// ── Orchestrator ────────────────────────────────────────────────────── // ── 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 class Orchestrator
{ {
public: 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() { stop_all(); }
Orchestrator(const Orchestrator&) = delete; Orchestrator(const Orchestrator&) = delete;
@@ -109,8 +234,6 @@ namespace Void::Fsm
return m_registry; return m_registry;
} }
/// Call on_start() on lifecycle services. Call before launching
/// FSMs that expect started services.
void start_services() void start_services()
{ {
m_registry.start_all(); m_registry.start_all();
@@ -118,36 +241,177 @@ namespace Void::Fsm
m_services_stopped = false; m_services_stopped = false;
} }
/// Construct F, inject the registry, start it, and supervise. template <typename F, typename... Args>
/// F must derive Fsm::Machine<...> (provides set_services / [[nodiscard]] Void::Result::Result<FsmHandle>
/// start / stop / status). 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> template <typename F, typename... Args>
FsmHandle launch(Args&&... args) FsmHandle launch(Args&&... args)
{ {
auto fsm = std::make_unique<F>(std::forward<Args>(args)...); auto r = try_launch<F>(SupervisionPolicy{},
fsm->set_services(m_registry); std::forward<Args>(args)...);
fsm->start(); return r ? *r : FsmHandle{};
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};
} }
/// Stop and release every supervised FSM, then stop services. /// Drive supervision rules (bounded restarts with injected Time
void stop_all() /// 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}; 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(); running.clear();
// Balance start_services() exactly once (stop_all may run
// explicitly and again from the destructor).
if (m_services_started && !m_services_stopped) { if (m_services_started && !m_services_stopped) {
m_registry.stop_all(); m_registry.stop_all();
m_services_stopped = true; m_services_stopped = true;
@@ -157,16 +421,118 @@ namespace Void::Fsm
[[nodiscard]] std::size_t running_count() const [[nodiscard]] std::size_t running_count() const
{ {
std::lock_guard lock{m_mutex}; 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: 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; Service::ServiceRegistry m_registry;
mutable std::mutex m_mutex; 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_started{false};
bool m_services_stopped{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 } // namespace Void::Fsm
+159
View File
@@ -1,10 +1,22 @@
#pragma once #pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.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 <any>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional> #include <functional>
#include <string> #include <string>
#include <string_view>
#include <type_traits>
#include <typeinfo> #include <typeinfo>
#include <utility> #include <utility>
@@ -33,6 +45,153 @@ namespace Void::Fsm
Faulted // stopped by a system fault (see system_error()) 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>(): /// The outcome of a sub-machine launched via startMachine<Sub, Next>():
/// a typed Success value, a typed Failure value, or a system fault. /// a typed Success value, a typed Failure value, or a system fault.
struct LaunchResult { struct LaunchResult {
+11
View File
@@ -65,6 +65,17 @@ namespace Void::Result
inline constexpr std::uint32_t kStacktraceErrorDomain = 13; inline constexpr std::uint32_t kStacktraceErrorDomain = 13;
inline constexpr std::uint32_t kObservabilityErrorDomain = 14; inline constexpr std::uint32_t kObservabilityErrorDomain = 14;
inline constexpr std::uint32_t kResilienceErrorDomain = 15; 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;
struct ErrorCode { struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain}; std::uint32_t domain{kGenericErrorDomain};
+189
View File
@@ -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
+6
View File
@@ -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>
+81
View File
@@ -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
+118
View File
@@ -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
+181
View File
@@ -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
+182 -2
View File
@@ -4,13 +4,79 @@
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <chrono> #include <chrono>
#include <cstddef>
#include <cstdint> #include <cstdint>
#include <filesystem>
#include <functional>
#include <optional> #include <optional>
#include <span>
#include <stop_token>
#include <string> #include <string>
#include <string_view>
#include <system_error>
#include <vector> #include <vector>
namespace Void::Net 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 }; 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. /// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL.
/// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS. /// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS.
/// Generic: no application-specific defaults beyond a configurable /// Generic: no application-specific defaults beyond a configurable
@@ -73,6 +187,12 @@ namespace Void::Net
HttpClient() = default; HttpClient() = default;
explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {} 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); } void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); }
[[nodiscard]] const ProxyConfig& proxy() const noexcept [[nodiscard]] const ProxyConfig& proxy() const noexcept
@@ -83,9 +203,33 @@ namespace Void::Net
/// Default User-Agent applied when a request sets none. /// Default User-Agent applied when a request sets none.
void set_user_agent(std::string ua) { m_user_agent = std::move(ua); } void set_user_agent(std::string ua) { m_user_agent = std::move(ua); }
/// Verify TLS peer certificates (default: false, matching common /// Verify TLS peer certificates (default constructor keeps `false`
/// scraping/proxy use; enable for security-sensitive callers). /// for 1.x compatibility; `HttpClient::secure()` defaults `true`).
void set_verify_tls(bool on) noexcept { m_verify_tls = on; } 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 /// 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 /// 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. /// header). Opt-in so callers that inspect redirects keep working.
void set_max_redirects(int n) noexcept { m_max_redirects = n; } 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; /// Execute a request. A per-request `Request::proxy` is not modelled;
/// the client-level proxy applies. Returns an Error only on transport /// the client-level proxy applies. Returns an Error only on transport
/// failure — a non-2xx HTTP response is a successful Result. /// failure — a non-2xx HTTP response is a successful Result.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error> [[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
send(const Request& req) const; 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. // Convenience wrappers.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error> [[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
get(std::string_view url, get(std::string_view url,
@@ -113,14 +279,28 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error> [[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post(std::string_view url, std::string body, post(std::string_view url, std::string body,
std::vector<Header> headers = {}) const; 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: private:
ProxyConfig m_proxy{}; ProxyConfig m_proxy{};
std::string m_user_agent = "Void.Net/1.0"; std::string m_user_agent = "Void.Net/1.0";
bool m_verify_tls = false; bool m_verify_tls = false;
std::string m_ca_file{};
std::uint64_t m_max_body = 64ull * 1024 * 1024; std::uint64_t m_max_body = 64ull * 1024 * 1024;
int m_max_redirects = 0; int m_max_redirects = 0;
bool m_allow_insecure_redirects = false;
}; };
} // namespace Void::Net } // namespace Void::Net
+108
View File
@@ -0,0 +1,108 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.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);
[[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
+10
View File
@@ -30,6 +30,7 @@ namespace Void::Net
std::vector<Header> headers; std::vector<Header> headers;
std::string body; std::string body;
RouteParameters parameters; RouteParameters parameters;
std::string query{};
[[nodiscard]] std::optional<std::string_view> [[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept; header(std::string_view name) const noexcept;
@@ -39,6 +40,12 @@ namespace Void::Net
std::uint16_t status{200}; std::uint16_t status{200};
std::vector<Header> headers; std::vector<Header> headers;
std::string body; 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> [[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept; header(std::string_view name) const noexcept;
@@ -67,6 +74,9 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>> [[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
dispatch(ServerRequest request) const; dispatch(ServerRequest request) const;
[[nodiscard]] std::vector<Method>
allowed_methods(std::string_view path) const;
[[nodiscard]] std::size_t size() const; [[nodiscard]] std::size_t size() const;
private: private:
+184
View File
@@ -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 */
+165
View File
@@ -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
+350
View File
@@ -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
+7 -5
View File
@@ -215,18 +215,20 @@ namespace Void::Plugin
std::filesystem::path path; std::filesystem::path path;
std::atomic<std::shared_ptr<detail::Instance>> current; std::atomic<std::shared_ptr<detail::Instance>> current;
bool watched{false}; bool watched{false};
std::mutex reload_mutex;
}; };
Entry* find(std::string_view name) const; Entry* find(std::string_view name) const;
std::expected<void, LoadError> std::shared_ptr<Entry> find_shared(std::string_view name) const;
reload_locked(Entry& entry, std::string_view name, std::expected<void, LoadError> reload_entry_unlocked(
const std::filesystem::path& sourcePath); 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)>> std::vector<std::function<void(std::string_view)>>
reload_callbacks_locked() const; reload_callbacks_locked() const;
Options m_options; Options m_options;
mutable std::mutex m_mutex; // guards the registry map + reloads mutable std::mutex m_mutex; // guards the registry map & observer list
std::unordered_map<std::string, std::unique_ptr<Entry>> m_plugins; std::unordered_map<std::string, std::shared_ptr<Entry>> m_plugins;
std::vector<std::pair<ReloadCallbackId, std::vector<std::pair<ReloadCallbackId,
std::function<void(std::string_view)>>> std::function<void(std::string_view)>>>
m_on_reloaded; m_on_reloaded;
+353
View File
@@ -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
+170
View File
@@ -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
+90
View File
@@ -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
+84
View File
@@ -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
+23 -2
View File
@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Security/Types.hpp>
#include <array> #include <array>
#include <cstddef> #include <cstddef>
@@ -23,6 +24,14 @@ namespace Void::Security
inline constexpr std::size_t secret_authentication_bytes = 16; inline constexpr std::size_t secret_authentication_bytes = 16;
using SecretKey = std::array<unsigned char, secret_key_bytes>; 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 /// Generate a URL-safe, unpadded token containing `entropy_bytes` of
/// cryptographically secure randomness. /// cryptographically secure randomness.
[[nodiscard]] Void::Result::Result<std::string> [[nodiscard]] Void::Result::Result<std::string>
@@ -44,6 +53,18 @@ namespace Void::Security
std::string_view password, std::string_view password,
PasswordHashStrength strength = PasswordHashStrength::Moderate); 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. /// Verify a password against a libsodium Argon2id encoded hash.
/// Malformed hashes are treated as a non-match. /// Malformed hashes are treated as a non-match.
[[nodiscard]] Void::Result::Result<bool> [[nodiscard]] Void::Result::Result<bool>
@@ -53,8 +74,8 @@ namespace Void::Security
/// Generate a cryptographically random key for local secret encryption. /// Generate a cryptographically random key for local secret encryption.
[[nodiscard]] Void::Result::Result<SecretKey> random_secret_key(); [[nodiscard]] Void::Result::Result<SecretKey> random_secret_key();
/// Encrypt and authenticate bytes. The returned portable envelope is /// Encrypt and authenticate bytes using the legacy local secret format
/// nonce || ciphertext || authentication tag. /// (24-byte nonce || crypto_secretbox_easy combined MAC + ciphertext).
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>> [[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
seal_secret(std::span<const unsigned char> plaintext, seal_secret(std::span<const unsigned char> plaintext,
const SecretKey& key); const SecretKey& key);
+197
View File
@@ -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
+60 -27
View File
@@ -26,6 +26,60 @@ namespace Void::Service
inline constexpr const char* kServiceSymbol = "void_plugin_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 /// Binds a plugin-provided service (interface I) into a ServiceRegistry
/// and keeps it bound across hot reloads: after each reload the new /// and keeps it bound across hot reloads: after each reload the new
/// instance's service (carrying state migrated by the plugin's v2 ABI) /// instance's service (carrying state migrated by the plugin's v2 ABI)
@@ -174,35 +228,14 @@ namespace Void::Service
[[nodiscard]] bool bind_locked() noexcept [[nodiscard]] bool bind_locked() noexcept
{ {
try { try {
auto handle = m_manager->acquire(m_name); auto svc_handle = acquire_plugin_service<I>(
if (!handle) { *m_manager, m_name);
if (!svc_handle) {
Void::Log::warn("Service.Plugin", "{}",
svc_handle.error().message());
return false; return false;
} }
auto* factory = auto pinned = svc_handle->shared();
reinterpret_cast<service_factory_fn>(
handle.raw_symbol(kServiceSymbol));
if (factory == nullptr) {
return false;
}
IService* base = factory(handle.get());
if (base == nullptr) {
return false;
}
I* iface = dynamic_cast<I*>(base);
if (iface == nullptr) {
Void::Log::warn(
"Service.Plugin",
"plugin '{}' exported an incompatible "
"service interface",
m_name);
return false;
}
// Pin the exact instance and shared object that
// supplied the factory and service subobject.
auto owner = std::make_shared<Plugin::PluginHandle>(
std::move(handle));
std::shared_ptr<I> pinned(std::move(owner), iface);
if (m_validator && !m_validator(pinned)) { if (m_validator && !m_validator(pinned)) {
Void::Log::warn( Void::Log::warn(
"Service.Plugin", "Service.Plugin",
+394 -109
View File
@@ -1,16 +1,23 @@
#pragma once #pragma once
#include <Void/Async/Operation.hpp>
#include <Void/Core/Meta.hpp> #include <Void/Core/Meta.hpp>
#include <Void/Service/Service.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 <memory>
#include <mutex> #include <mutex>
#include <shared_mutex> #include <optional>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <typeindex> #include <typeindex>
#include <unordered_map> #include <unordered_map>
#include <utility>
#include <vector> #include <vector>
namespace Void::Service namespace Void::Service
@@ -25,92 +32,297 @@ namespace Void::Service
} }
#endif #endif
/// Type-keyed service container: providers register an implementation class ServiceRegistry;
/// against an interface type, consumers resolve by that interface and
/// never name the concrete type — the core of the dependency-inversion namespace detail
/// the orchestrator and FSMs rely on. {
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>()); /// Note: `require<I>()` returns an unpinned reference after unlocking and is
/// auto& clock = registry.require<IClock>(); // no SystemClock dep /// kept for legacy compatibility; new code and coroutines should use
/// /// `acquire<I>()` and retain the returned `ServiceHandle<I>` across calls
/// Thread-safe. Reads (get/require/has) take a shared lock; they are /// and `co_await` suspension points.
/// the hot path for running FSMs resolving services per step.
class ServiceRegistry class ServiceRegistry
{ {
public: 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(const ServiceRegistry&) = delete;
ServiceRegistry& operator=(const ServiceRegistry&) = delete; ServiceRegistry& operator=(const ServiceRegistry&) = delete;
/// Create a scoped child registry that overlays `parent`: lookups /// Construct a child registry retaining an immutable parent
/// fall through to the parent when a key is not provided locally, /// snapshot so lookups survive destruction of the parent registry.
/// and a local provide<I>() shadows the parent's entry. Lifecycle [[nodiscard]] static Void::Result::Result<
/// (start_all/stop_all) covers only locally-provided services. The std::unique_ptr<ServiceRegistry>>
/// parent must outlive this registry. from_parent_snapshot(
explicit ServiceRegistry(const ServiceRegistry* parent) ServiceSnapshot parent,
: m_parent{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) template <typename I> void provide(std::shared_ptr<I> impl)
{ {
Entry entry; IService* svc = nullptr;
entry.impl = std::shared_ptr<void>(impl, impl.get()); if (impl) {
if constexpr (std::is_base_of_v<IService, I>) { if constexpr (std::is_base_of_v<IService, I>) {
entry.service = static_cast<IService*>(impl.get()); svc = static_cast<IService*>(impl.get());
} else if constexpr (std::is_polymorphic_v<I>) { } else if constexpr (std::is_polymorphic_v<I>) {
// The interface I doesn't derive IService, but the svc = dynamic_cast<IService*>(impl.get());
// 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);
} }
} }
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 template <typename I> [[nodiscard]] I& require() const
{ {
auto p = get<I>(); auto p = get<I>();
@@ -124,55 +336,128 @@ namespace Void::Service
template <typename I> [[nodiscard]] bool has() const template <typename I> [[nodiscard]] bool has() const
{ {
{ return acquire<I>().has_value();
std::shared_lock lock{m_mutex};
if (m_services.contains(std::type_index{typeid(I)})) {
return true;
}
}
return m_parent ? m_parent->has<I>() : false;
} }
/// Call on_start() on every lifecycle service, registration /// Run on_start() outside registry locks in registration/dependency
/// order. /// 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}; auto snap = acquire_snapshot();
for (const auto& key : m_order) { if (!snap) {
if (auto* s = m_services.at(key).service) { return Void::Result::fail(make_service_error(
s->on_start(); ServiceErrorCode::service_stopping,
} "ServiceRegistry: registry is stopping"));
} }
return acquire_from_snapshot<I>(*snap, 0);
} }
/// Call on_stop() on every lifecycle service, reverse order. [[nodiscard]] Void::Result::Result<PreparedPublication>
void stop_all() prepare_batch(ProviderSet set,
{ ExpectedEpoch expected = std::nullopt);
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]] std::size_t size() const [[nodiscard]] Void::Result::Result<void>
{ start_staged(PreparedPublication& prepared,
std::shared_lock lock{m_mutex}; Async::OperationOptions options = {});
return m_services.size();
} [[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: private:
struct Entry { void provide_erased(std::type_index key, std::shared_ptr<void> impl,
std::shared_ptr<void> impl; const void* object_key, IService* service);
IService* service = nullptr; // non-null iff I : IService bool remove_erased(std::type_index key);
}; std::shared_ptr<const detail::SnapshotData> acquire_snapshot() const;
const ServiceRegistry* m_parent = nullptr; template <typename I>
mutable std::shared_mutex m_mutex; [[nodiscard]] Void::Result::Result<ServiceHandle<I>>
std::unordered_map<std::type_index, Entry> m_services; acquire_from_snapshot(const detail::SnapshotData& snap,
std::vector<std::type_index> m_order; 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 } // namespace Void::Service
+227
View File
@@ -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
+179
View File
@@ -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
View File
@@ -2,36 +2,79 @@
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Sqlite/Types.hpp>
#include <cstdint> #include <cstdint>
#include <filesystem> #include <filesystem>
#include <functional>
#include <memory>
#include <optional> #include <optional>
#include <span> #include <span>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <utility> #include <utility>
#include <vector>
struct sqlite3; struct sqlite3;
struct sqlite3_stmt; struct sqlite3_stmt;
// A thin, RAII, Result-based wrapper over the SQLite C API. Generic — no // A hardened RAII, Result-based wrapper over the SQLite C API. Generic — no
// application schema baggage. Open a Database, prepare Statements, bind by // application schema baggage. Open a Database (or open_database with explicit
// 1-based index, step over result rows, read columns by 0-based index. Schema // OpenOptions), prepare Statements, bind by 1-based index or parameter name,
// versioning is handled via PRAGMA user_version (migrate()). // step over result rows, and read typed columns by 0-based index.
namespace Void::Sqlite namespace Void::Sqlite
{ {
using Void::Result::Error; namespace detail
template <typename T> using Result = Void::Result::Result<T, Error>; {
struct ConnectionState;
enum class OpenMode { ReadOnly, ReadWrite, ReadWriteCreate }; } // namespace detail
class Database; 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 class Statement
{ {
public: public:
Statement() = default; Statement() = default;
~Statement(); ~Statement();
Statement(Statement&&) noexcept; Statement(Statement&&) noexcept;
@@ -39,7 +82,7 @@ namespace Void::Sqlite
Statement(const Statement&) = delete; Statement(const Statement&) = delete;
Statement& operator=(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, std::int64_t value);
Statement& bind(int index, int 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, std::nullptr_t);
Statement& bind(int index, const std::optional<std::string>& value); 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, /// Advance to the next row. Returns true with a row available,
/// false when the statement is done, or an Error on failure. /// false when the statement is done, or an Error on failure.
[[nodiscard]] Result<bool> step(); [[nodiscard]] Result<bool> step();
/// Reset for re-execution (keeps bindings unless clear_bindings). /// Reset for re-execution (keeps bindings unless clear_bindings).
void reset() noexcept; 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]] int column_count() const noexcept;
[[nodiscard]] bool is_null(int col) const noexcept; [[nodiscard]] bool is_null(int col) const noexcept;
[[nodiscard]] std::int64_t column_int(int col) const noexcept; [[nodiscard]] std::int64_t column_int(int col) const noexcept;
[[nodiscard]] double column_double(int col) const noexcept; [[nodiscard]] double column_double(int col) const noexcept;
[[nodiscard]] std::string column_text(int col) const; [[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; friend class Database;
explicit Statement(sqlite3_stmt* stmt) : m_stmt(stmt) {} friend class RowView;
sqlite3_stmt* m_stmt = nullptr;
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 class Transaction
{ {
public: public:
Transaction() noexcept = default;
~Transaction(); ~Transaction();
Transaction(Transaction&&) noexcept; Transaction(Transaction&&) noexcept;
Transaction& operator=(Transaction&&) noexcept; Transaction& operator=(Transaction&&) noexcept;
Transaction(const Transaction&) = delete; Transaction(const Transaction&) = delete;
Transaction& operator=(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(); Result<void> commit();
[[nodiscard]] Result<void> rollback_checked();
void rollback() noexcept; void rollback() noexcept;
private: private:
friend class Database; friend class Database;
explicit Transaction(Database* db) : m_db(db) {} explicit Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept;
Database* m_db = nullptr;
bool m_done = false; 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 /// 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 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 class Database
{ {
public: public:
Database() = default; Database() = default;
~Database(); ~Database();
Database(Database&&) noexcept; Database(Database&&) noexcept;
@@ -119,19 +265,46 @@ namespace Void::Sqlite
Database& operator=(const Database&) = delete; Database& operator=(const Database&) = delete;
/// Open (or create) a database file. Use ":memory:" for an /// 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> [[nodiscard]] static Result<Database>
open(const std::filesystem::path& path, open(const std::filesystem::path& path,
OpenMode mode = OpenMode::ReadWriteCreate); 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). /// Execute one or more semicolon-separated statements (no results).
Result<void> exec(std::string_view sql); 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); [[nodiscard]] Result<Statement> prepare(std::string_view sql);
/// Begin a transaction (BEGIN; commit/rollback via the handle). /// Begin a transaction. Rejects nested begin() while a transaction
[[nodiscard]] Result<Transaction> begin(); /// 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]] std::int64_t last_insert_rowid() const noexcept;
[[nodiscard]] int changes() const noexcept; [[nodiscard]] int changes() const noexcept;
@@ -139,16 +312,63 @@ namespace Void::Sqlite
/// Current schema version (PRAGMA user_version). /// Current schema version (PRAGMA user_version).
[[nodiscard]] Result<int> user_version(); [[nodiscard]] Result<int> user_version();
/// Apply, in order, any migrations whose version exceeds the /// Validate strictly increasing unique versions before mutation,
/// current user_version, each inside a transaction, then bump /// reject unexpected newer schemas, and apply pending migrations.
/// user_version. Idempotent and safe to call on every startup.
Result<void> migrate(std::span<const Migration> 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: private:
explicit Database(std::shared_ptr<detail::ConnectionState> conn) noexcept;
sqlite3* m_db = nullptr; 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 } // namespace Void::Sqlite
+405
View File
@@ -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
+72
View File
@@ -0,0 +1,72 @@
#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/Storage/Engine.hpp>
#include <Void/Storage/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
namespace Void::Storage
{
struct AsyncAdapterOptions {
std::size_t max_pending_batches{64};
std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL};
const Void::Time::MonotonicClock* clock{nullptr};
};
struct AsyncAdapterStats {
std::size_t queued_writes{0};
std::size_t pending_bytes{0};
std::uint64_t completed_writes{0};
std::uint64_t rejected_writes{0};
std::uint64_t unknown_outcomes{0};
std::uint64_t cancelled_before_append{0};
};
/// Bounded blocking async adapter over Storage::Engine following C-03
/// domain-result classification (never steals a persisted commit outcome with
/// a synthetic timeout/cancel once WAL append begins; single delivery only).
class AsyncStorageAdapter
{
public:
explicit AsyncStorageAdapter(
Engine& engine,
AsyncAdapterOptions options = {},
Void::Async::Executor* completion_executor = nullptr);
~AsyncStorageAdapter();
AsyncStorageAdapter(const AsyncStorageAdapter&) = delete;
AsyncStorageAdapter& operator=(const AsyncStorageAdapter&) = delete;
AsyncStorageAdapter(AsyncStorageAdapter&&) = delete;
AsyncStorageAdapter& operator=(AsyncStorageAdapter&&) = delete;
[[nodiscard]] Void::Coro::Task<std::expected<CommitReceipt, WriteFailure>>
write_async(
Batch batch,
Durability durability,
Void::Async::OperationOptions op = {});
[[nodiscard]] Void::Coro::Task<Result<OwnedValue>>
get_async(
ByteView key,
Void::Async::OperationOptions op = {});
[[nodiscard]] Void::Coro::Task<Result<void>>
checkpoint_async(Void::Async::OperationOptions op = {});
[[nodiscard]] AsyncAdapterStats stats() const noexcept;
void close_and_join();
private:
struct Impl;
std::shared_ptr<Impl> m_impl{};
};
} // namespace Void::Storage
+93
View File
@@ -0,0 +1,93 @@
#pragma once
#include <Void/Storage/Types.hpp>
#include <cstdint>
#include <optional>
#include <string_view>
#include <vector>
namespace Void::Storage
{
enum class MutationKind : std::uint8_t {
Put = 1,
Erase = 2
};
enum class PreconditionKind : std::uint8_t {
Absent = 1,
VersionEquals = 2,
ValueEquals = 3
};
struct Mutation {
MutationKind kind{MutationKind::Put};
OwnedBytes key{};
OwnedBytes value{};
};
struct Precondition {
PreconditionKind kind{PreconditionKind::Absent};
OwnedBytes key{};
Sequence expected_version{0};
OwnedBytes expected_value{};
};
/// Atomic conditional write batch owning all key and value bytes.
/// Rejects duplicate mutation keys and duplicate preconditions per key.
class Batch
{
public:
Batch() = default;
Batch& put(ByteView key, ByteView value);
Batch& put(std::string_view key, std::string_view value)
{
return put(to_byte_view(key), to_byte_view(value));
}
Batch& erase(ByteView key);
Batch& erase(std::string_view key)
{
return erase(to_byte_view(key));
}
Batch& require_absent(ByteView key);
Batch& require_absent(std::string_view key)
{
return require_absent(to_byte_view(key));
}
Batch& require_version(ByteView key, Sequence expected_version);
Batch& require_version(std::string_view key, Sequence expected_version)
{
return require_version(to_byte_view(key), expected_version);
}
Batch& require_value(ByteView key, ByteView expected_value);
Batch& require_value(std::string_view key, std::string_view expected_value)
{
return require_value(to_byte_view(key), to_byte_view(expected_value));
}
[[nodiscard]] const std::vector<Mutation>& mutations() const noexcept
{
return m_mutations;
}
[[nodiscard]] const std::vector<Precondition>& preconditions() const noexcept
{
return m_preconditions;
}
[[nodiscard]] bool empty() const noexcept
{
return m_mutations.empty() && m_preconditions.empty();
}
[[nodiscard]] Result<void> validate(const Limits& limits) const;
private:
std::vector<Mutation> m_mutations{};
std::vector<Precondition> m_preconditions{};
};
} // namespace Void::Storage
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string_view>
namespace Void::Storage
{
namespace detail
{
[[nodiscard]] constexpr std::array<std::uint32_t, 256>
make_crc32c_table() noexcept
{
// Reflected Castagnoli polynomial (normal 0x1EDC6F41, reflected 0x82F63B78).
constexpr std::uint32_t kPoly = 0x82F63B78u;
std::array<std::uint32_t, 256> table{};
for (std::uint32_t i = 0; i < 256; ++i) {
std::uint32_t c = i;
for (int k = 0; k < 8; ++k) {
c = (c & 1u) ? (kPoly ^ (c >> 1)) : (c >> 1);
}
table[i] = c;
}
return table;
}
inline constexpr auto kCrc32cTable = make_crc32c_table();
} // namespace detail
inline constexpr std::uint32_t kCrc32cInitial = 0xFFFFFFFFu;
[[nodiscard]] constexpr std::uint32_t crc32c_init() noexcept
{
return kCrc32cInitial;
}
[[nodiscard]] constexpr std::uint32_t crc32c_update(
std::uint32_t state,
std::span<const std::byte> data) noexcept
{
for (const auto b : data) {
const auto idx =
(state ^ static_cast<std::uint32_t>(std::to_integer<unsigned char>(b))) &
0xFFu;
state = detail::kCrc32cTable[idx] ^ (state >> 8);
}
return state;
}
[[nodiscard]] constexpr std::uint32_t crc32c_update(
std::uint32_t state,
std::string_view text) noexcept
{
for (const unsigned char c : text) {
state = detail::kCrc32cTable[(state ^ c) & 0xFFu] ^ (state >> 8);
}
return state;
}
[[nodiscard]] constexpr std::uint32_t crc32c_finalize(std::uint32_t state) noexcept
{
return state ^ 0xFFFFFFFFu;
}
[[nodiscard]] constexpr std::uint32_t crc32c(
std::span<const std::byte> data) noexcept
{
return crc32c_finalize(crc32c_update(crc32c_init(), data));
}
[[nodiscard]] constexpr std::uint32_t crc32c(std::string_view text) noexcept
{
return crc32c_finalize(crc32c_update(crc32c_init(), text));
}
static_assert(crc32c(std::string_view{"123456789"}) == 0xE3069283u,
"CRC32C golden vector mismatch");
static_assert(crc32c(std::string_view{""}) == 0u,
"CRC32C empty vector mismatch");
} // namespace Void::Storage
+147
View File
@@ -0,0 +1,147 @@
#pragma once
#include <Void/Storage/Batch.hpp>
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Types.hpp>
#include <expected>
#include <filesystem>
#include <memory>
namespace Void::Storage
{
namespace detail
{
class EngineControl;
struct SourceView;
} // namespace detail
class Engine;
class Cursor;
/// Move-only reader pin of a committed sequence and immutable source set.
class Snapshot
{
public:
Snapshot() noexcept = default;
~Snapshot();
Snapshot(Snapshot&&) noexcept;
Snapshot& operator=(Snapshot&&) noexcept;
Snapshot(const Snapshot&) = delete;
Snapshot& operator=(const Snapshot&) = delete;
[[nodiscard]] Sequence sequence() const noexcept { return m_sequence; }
[[nodiscard]] bool valid() const noexcept { return static_cast<bool>(m_control); }
void reset() noexcept;
private:
friend class Engine;
friend class Cursor;
friend class detail::EngineControl;
Snapshot(std::shared_ptr<detail::EngineControl> control,
std::shared_ptr<const detail::SourceView> view,
Sequence seq,
std::uint64_t pin_id) noexcept;
std::shared_ptr<detail::EngineControl> m_control{};
std::shared_ptr<const detail::SourceView> m_view{};
Sequence m_sequence{0};
std::uint64_t m_pin_id{0};
};
/// Move-only ordered byte-lexicographic iterator retaining its Snapshot.
class Cursor
{
public:
Cursor() noexcept = default;
~Cursor();
Cursor(Cursor&&) noexcept;
Cursor& operator=(Cursor&&) noexcept;
Cursor(const Cursor&) = delete;
Cursor& operator=(const Cursor&) = delete;
[[nodiscard]] Result<ScanPage> next_page();
[[nodiscard]] bool valid() const noexcept { return !m_closed && m_snapshot.valid(); }
void close() noexcept;
private:
friend class Engine;
Cursor(Snapshot snap,
ScanBounds bounds,
std::size_t page_bytes,
std::size_t page_rows,
std::uint64_t cursor_id) noexcept;
Snapshot m_snapshot{};
ScanBounds m_bounds{};
std::size_t m_page_bytes{0};
std::size_t m_page_rows{0};
std::uint64_t m_cursor_id{0};
std::optional<OwnedBytes> m_resume_after{};
bool m_finished{false};
bool m_closed{false};
};
class Engine
{
public:
Engine() noexcept = default;
~Engine();
Engine(Engine&&) noexcept;
Engine& operator=(Engine&&) noexcept;
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
[[nodiscard]] static Result<Engine> open(OpenOptions options);
[[nodiscard]] Result<Snapshot> snapshot();
[[nodiscard]] std::expected<CommitReceipt, WriteFailure> write(
Batch batch,
Durability durability);
[[nodiscard]] std::expected<CommitReceipt, WriteFailure> write(Batch batch)
{
return write(std::move(batch), default_durability());
}
[[nodiscard]] Result<OwnedValue> get(
const Snapshot& snap,
ByteView key) const;
[[nodiscard]] Result<OwnedValue> get(
const Snapshot& snap,
std::string_view key) const
{
return get(snap, to_byte_view(key));
}
[[nodiscard]] Result<Cursor> scan(
Snapshot snap,
ScanBounds bounds = ScanBounds::all()) const;
[[nodiscard]] Result<void> checkpoint();
[[nodiscard]] Result<void> compact();
[[nodiscard]] Result<void> sync();
[[nodiscard]] Result<void> close();
/// Copy consistent manifest, tables, and necessary WAL prefix into
/// `destination` while keeping this engine open and pinning sources.
[[nodiscard]] Result<void> export_backup(
const std::filesystem::path& destination);
[[nodiscard]] EngineState state() const noexcept;
[[nodiscard]] EngineStats stats() const noexcept;
[[nodiscard]] Durability default_durability() const noexcept;
[[nodiscard]] const Limits& limits() const noexcept;
private:
friend class AsyncStorageAdapter;
explicit Engine(std::shared_ptr<detail::EngineControl> control) noexcept;
std::shared_ptr<detail::EngineControl> m_control{};
};
} // namespace Void::Storage
+145
View File
@@ -0,0 +1,145 @@
#pragma once
#include <Void/Storage/Types.hpp>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <vector>
namespace Void::Storage
{
enum class FileOpenMode : std::uint8_t {
ReadOnly = 0,
ReadWriteExisting = 1,
CreateNew = 2,
CreateOrOpen = 3
};
class FileHandle
{
public:
virtual ~FileHandle() = default;
[[nodiscard]] virtual Result<std::size_t> pread(
std::uint64_t offset, std::span<std::byte> out) = 0;
[[nodiscard]] virtual Result<void> pread_exact(
std::uint64_t offset, std::span<std::byte> out) = 0;
[[nodiscard]] virtual Result<void> pwrite_all(
std::uint64_t offset, ByteView data) = 0;
[[nodiscard]] virtual Result<std::uint64_t> append_all(ByteView data) = 0;
[[nodiscard]] virtual Result<void> sync() = 0;
[[nodiscard]] virtual Result<void> truncate(std::uint64_t new_size) = 0;
[[nodiscard]] virtual Result<std::uint64_t> size() const = 0;
[[nodiscard]] virtual Result<void> close() = 0;
};
class DirLockHandle
{
public:
virtual ~DirLockHandle() = default;
};
class FilePort
{
public:
virtual ~FilePort() = default;
[[nodiscard]] virtual Result<void> ensure_dir(
const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<bool> exists(
const std::filesystem::path& p) = 0;
[[nodiscard]] virtual Result<std::uint64_t> file_size(
const std::filesystem::path& p) = 0;
[[nodiscard]] virtual Result<std::vector<std::string>> list_dir(
const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<std::unique_ptr<DirLockHandle>>
lock_directory(const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<std::unique_ptr<FileHandle>> open_file(
const std::filesystem::path& p, FileOpenMode mode) = 0;
[[nodiscard]] virtual Result<void> rename_atomic(
const std::filesystem::path& from,
const std::filesystem::path& to) = 0;
[[nodiscard]] virtual Result<void> unlink_file(
const std::filesystem::path& p) = 0;
[[nodiscard]] virtual Result<void> sync_dir(
const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<void> probe_durability_capabilities(
const std::filesystem::path& dir) = 0;
};
[[nodiscard]] std::shared_ptr<FilePort> make_posix_file_port();
enum class FaultOp : std::uint8_t {
LockDir = 0,
ProbeDurability = 1,
OpenFile = 2,
AppendWrite = 3,
PWrite = 4,
SyncFile = 5,
SyncDir = 6,
Rename = 7,
Unlink = 8,
Truncate = 9
};
struct FaultRule {
FaultOp op{FaultOp::SyncFile};
std::string path_contains{};
/// 1-based hit index among matching operations (0 = fail every match).
std::uint64_t hit_index{1};
StorageErrorCode error_code{StorageErrorCode::io_error};
/// For write ops: write at most this many bytes before failing (SIZE_MAX = skip write).
std::optional<std::size_t> partial_write_bytes{};
bool consumed{false};
std::uint64_t match_count{0};
};
/// Deterministic filesystem fault-injection proxy wrapping a FilePort
/// (default: PosixFilePort) for crash, partial-write, and sync-failure tests.
class FaultInjectingFilePort final : public FilePort
{
public:
explicit FaultInjectingFilePort(
std::shared_ptr<FilePort> delegate = make_posix_file_port());
void add_rule(FaultRule rule);
void clear_rules();
void set_pause_before_sync(std::function<void()> hook);
[[nodiscard]] std::uint64_t op_count(FaultOp op) const noexcept;
[[nodiscard]] Result<void> ensure_dir(const std::filesystem::path& dir) override;
[[nodiscard]] Result<bool> exists(const std::filesystem::path& p) override;
[[nodiscard]] Result<std::uint64_t> file_size(const std::filesystem::path& p) override;
[[nodiscard]] Result<std::vector<std::string>> list_dir(const std::filesystem::path& dir) override;
[[nodiscard]] Result<std::unique_ptr<DirLockHandle>> lock_directory(const std::filesystem::path& dir) override;
[[nodiscard]] Result<std::unique_ptr<FileHandle>> open_file(const std::filesystem::path& p, FileOpenMode mode) override;
[[nodiscard]] Result<void> rename_atomic(const std::filesystem::path& from, const std::filesystem::path& to) override;
[[nodiscard]] Result<void> unlink_file(const std::filesystem::path& p) override;
[[nodiscard]] Result<void> sync_dir(const std::filesystem::path& dir) override;
[[nodiscard]] Result<void> probe_durability_capabilities(const std::filesystem::path& dir) override;
private:
friend class FaultFileHandle;
struct MatchedFault {
StorageErrorCode error_code{StorageErrorCode::none};
std::optional<std::size_t> partial_write_bytes{};
bool triggered{false};
};
[[nodiscard]] MatchedFault check_fault(FaultOp op, const std::string& path);
void maybe_run_sync_hook();
std::shared_ptr<FilePort> delegate_;
mutable std::mutex mu_;
std::vector<FaultRule> rules_{};
std::function<void()> pause_before_sync_{};
std::uint64_t op_counts_[10]{};
};
} // namespace Void::Storage
+216
View File
@@ -0,0 +1,216 @@
#pragma once
#include <Void/Core/Uuid.hpp>
#include <Void/Storage/Types.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace Void::Storage
{
inline constexpr std::array<char, 8> kWalSegmentMagic{'V', 'O', 'I', 'D', 'W', 'A', 'L', '1'};
inline constexpr std::uint16_t kWalFormatMajor = 1;
inline constexpr std::uint16_t kWalFormatMinor = 0;
inline constexpr std::uint32_t kWalSegmentHeaderSize = 64;
inline constexpr std::uint32_t kWalRecordMagic = 0x56575231u; // "1RWV" little-endian
inline constexpr std::uint16_t kWalRecordVersion = 1;
inline constexpr std::uint32_t kWalRecordHeaderSize = 36;
inline constexpr std::uint32_t kWalRecordTrailerSize = 8;
enum class WalRecordType : std::uint16_t {
Begin = 1,
Put = 2,
Erase = 3,
Commit = 4
};
struct WalSegmentHeader {
std::uint16_t major{kWalFormatMajor};
std::uint16_t minor{kWalFormatMinor};
std::uint32_t header_size{kWalSegmentHeaderSize};
Void::Uuid::Uuid database_uuid{};
std::uint64_t segment_id{0};
std::uint64_t previous_segment_id{0};
Sequence first_candidate_sequence{0};
std::uint32_t flags{0};
};
struct WalRecordHeader {
std::uint32_t total_length{0};
WalRecordType type{WalRecordType::Begin};
std::uint16_t record_version{kWalRecordVersion};
std::uint32_t flags{0};
Sequence batch_sequence{0};
std::uint32_t ordinal{0};
std::uint32_t payload_length{0};
};
struct WalBeginPayload {
std::uint32_t op_count{0};
std::uint64_t total_op_bytes{0};
};
struct WalMutationPayload {
OwnedBytes key{};
OwnedBytes value{};
};
struct WalCommitPayload {
std::uint32_t op_count{0};
std::uint64_t total_op_bytes{0};
std::uint32_t aggregate_crc32c{0};
};
[[nodiscard]] Result<OwnedBytes> encode_wal_segment_header(const WalSegmentHeader& hdr);
[[nodiscard]] Result<WalSegmentHeader> decode_wal_segment_header(ByteView bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_record_frame(
WalRecordType type,
Sequence batch_sequence,
std::uint32_t ordinal,
ByteView payload);
/// Decode and verify ONLY the 36-byte record header before reading/allocating payload.
[[nodiscard]] Result<WalRecordHeader> decode_wal_record_header(
ByteView header_bytes,
std::size_t max_payload_bytes);
/// Verify full record CRC32C and trailing repeated length after reading payload+trailer.
[[nodiscard]] Result<void> verify_wal_record_frame(
const WalRecordHeader& hdr,
ByteView full_record_bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_begin_payload(const WalBeginPayload& p);
[[nodiscard]] Result<WalBeginPayload> decode_wal_begin_payload(ByteView bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_mutation_payload(
bool is_erase, ByteView key, ByteView value);
[[nodiscard]] Result<WalMutationPayload> decode_wal_mutation_payload(
bool is_erase,
ByteView bytes,
std::size_t max_key_bytes,
std::size_t max_value_bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_commit_payload(const WalCommitPayload& p);
[[nodiscard]] Result<WalCommitPayload> decode_wal_commit_payload(ByteView bytes);
// ── V1 Immutable Sorted Table (`VOIDTBL1`) ───────────────────────────────
inline constexpr std::array<char, 8> kTableMagic{'V', 'O', 'I', 'D', 'T', 'B', 'L', '1'};
inline constexpr std::array<char, 8> kTableFooterMagic{'V', 'O', 'I', 'D', 'T', 'B', 'F', '1'};
inline constexpr std::uint32_t kTableHeaderSize = 76;
inline constexpr std::uint32_t kTableFooterSize = 48;
struct TableEntryRecord {
OwnedBytes key{};
Sequence sequence{0};
bool erased{false};
OwnedBytes value{};
};
struct TableHeader {
std::uint16_t major{1};
std::uint16_t minor{0};
std::uint32_t header_size{kTableHeaderSize};
Void::Uuid::Uuid database_uuid{};
std::uint64_t table_id{0};
std::uint32_t level{0};
std::uint32_t flags{0};
std::uint64_t entry_count{0};
Sequence min_sequence{0};
Sequence max_sequence{0};
};
struct TableBlockIndexEntry {
OwnedBytes first_key{};
OwnedBytes last_key{};
std::uint64_t offset{0};
std::uint32_t byte_length{0};
};
struct TableFooter {
std::uint64_t index_offset{0};
std::uint64_t index_size{0};
std::uint64_t data_end_offset{0};
std::uint32_t file_crc32c{0};
};
struct TableMeta {
std::uint64_t table_id{0};
std::uint32_t level{0};
std::uint64_t file_size{0};
std::uint64_t entry_count{0};
Sequence min_sequence{0};
Sequence max_sequence{0};
OwnedBytes min_key{};
OwnedBytes max_key{};
std::uint32_t file_crc32c{0};
};
[[nodiscard]] Result<OwnedBytes> encode_table_header(const TableHeader& hdr);
[[nodiscard]] Result<TableHeader> decode_table_header(ByteView bytes);
[[nodiscard]] Result<OwnedBytes> encode_table_block(
std::span<const TableEntryRecord> entries,
std::size_t max_bytes);
[[nodiscard]] Result<std::vector<TableEntryRecord>> decode_table_block(
ByteView bytes,
std::size_t max_key_bytes,
std::size_t max_value_bytes);
[[nodiscard]] Result<OwnedBytes> encode_table_index(
std::span<const TableBlockIndexEntry> index,
std::size_t max_bytes);
[[nodiscard]] Result<std::vector<TableBlockIndexEntry>> decode_table_index(
ByteView bytes,
std::size_t max_key_bytes);
[[nodiscard]] Result<OwnedBytes> encode_table_footer(const TableFooter& footer);
[[nodiscard]] Result<TableFooter> decode_table_footer(ByteView bytes);
// ── V1 Manifest (`VOIDMNF1`) & CURRENT (`VOIDCUR1`) ──────────────────────
inline constexpr std::array<char, 8> kManifestMagic{'V', 'O', 'I', 'D', 'M', 'N', 'F', '1'};
inline constexpr std::array<char, 8> kCurrentMagic{'V', 'O', 'I', 'D', 'C', 'U', 'R', '1'};
inline constexpr std::string_view kComparatorIdV1 = "void.byte.lex.v1";
struct ManifestData {
std::uint16_t major{1};
std::uint16_t minor{0};
std::uint32_t flags{0};
Void::Uuid::Uuid database_uuid{};
std::uint64_t generation{0};
Sequence checkpoint_sequence{0};
Sequence next_sequence_hint{1};
std::uint64_t next_file_id{1};
std::string comparator{kComparatorIdV1};
std::vector<TableMeta> tables{};
std::vector<std::uint64_t> wal_segments{};
};
struct CurrentPointer {
std::uint16_t major{1};
std::uint16_t minor{0};
Void::Uuid::Uuid database_uuid{};
std::uint64_t generation{0};
std::string manifest_filename{};
};
[[nodiscard]] Result<OwnedBytes> encode_manifest(
const ManifestData& m,
std::size_t max_manifest_bytes);
[[nodiscard]] Result<ManifestData> decode_manifest(
ByteView bytes,
std::size_t max_manifest_bytes,
std::size_t max_tables,
std::size_t max_key_bytes);
[[nodiscard]] Result<OwnedBytes> encode_current(const CurrentPointer& cur);
[[nodiscard]] Result<CurrentPointer> decode_current(ByteView bytes);
[[nodiscard]] std::string make_wal_filename(std::uint64_t segment_id);
[[nodiscard]] std::string make_table_filename(std::uint64_t table_id);
[[nodiscard]] std::string make_manifest_filename(std::uint64_t generation);
} // namespace Void::Storage
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <Void/Storage/AsyncAdapter.hpp>
#include <Void/Storage/Batch.hpp>
#include <Void/Storage/Crc32c.hpp>
#include <Void/Storage/Engine.hpp>
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Format.hpp>
#include <Void/Storage/Tools.hpp>
#include <Void/Storage/Types.hpp>
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Types.hpp>
#include <cstdint>
#include <filesystem>
#include <memory>
namespace Void::Storage
{
struct VerifyReport {
std::uint64_t manifest_generation{0};
Sequence checkpoint_sequence{0};
std::uint64_t tables_verified{0};
std::uint64_t blocks_verified{0};
std::uint64_t wal_segments_verified{0};
std::uint64_t wal_batches_verified{0};
};
struct SalvageReport {
Sequence highest_recovered_sequence{0};
std::uint64_t recovered_batches{0};
std::uint64_t keys_recovered{0};
std::uint64_t tombstones_preserved{0};
std::uint64_t truncated_or_skipped_bytes{0};
};
/// Read-only full structural & block-level verification of an offline or
/// quiesced Storage directory (CURRENT, MANIFEST, every block of every table,
/// and every manifest-listed WAL segment).
[[nodiscard]] Result<VerifyReport> verify_directory(
const std::filesystem::path& directory,
const Limits& limits = {},
std::shared_ptr<FilePort> port = nullptr);
/// Restore a verified backup directory into `destination` without mutating
/// `backup_dir`.
[[nodiscard]] Result<void> restore_backup(
const std::filesystem::path& backup_dir,
const std::filesystem::path& destination,
const Limits& limits = {},
std::shared_ptr<FilePort> port = nullptr);
/// Offline salvage: extracts the valid prefix of committed data and valid
/// tables/WAL records from `source_dir` into a fresh `destination_dir`.
/// Refuses same-directory salvage.
[[nodiscard]] Result<SalvageReport> salvage_directory(
const std::filesystem::path& source_dir,
const std::filesystem::path& destination_dir,
const Limits& limits = {},
std::shared_ptr<FilePort> port = nullptr);
} // namespace Void::Storage
+381
View File
@@ -0,0 +1,381 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <memory_resource>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
namespace Void::Storage
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
using Sequence = std::uint64_t;
using ByteView = std::span<const std::byte>;
using OwnedBytes = std::vector<std::byte>;
class FilePort;
enum class Durability : std::uint8_t {
Sync = 0,
Buffered = 1
};
enum class Outcome : std::uint8_t {
NotCommitted = 0,
Committed = 1,
Unknown = 2
};
enum class EngineState : std::uint8_t {
Open = 0,
RecoveryRequired = 1,
Closed = 2
};
enum class StorageErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
not_found = 2,
conflict = 3,
interrupted = 4,
timeout = 5,
overloaded = 6,
unsupported_capability = 7,
io_error = 8,
corrupt = 9,
incomplete_init = 10,
sequence_exhausted = 11,
recovery_required = 12,
busy = 13,
closed = 14,
page_too_small = 15,
quota_exceeded = 16
};
[[nodiscard]] inline Error make_storage_error(
StorageErrorCode code,
std::string message,
std::error_code sys_err = {})
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case StorageErrorCode::none:
kind = ErrorKind::internal;
break;
case StorageErrorCode::invalid_argument:
case StorageErrorCode::page_too_small:
kind = ErrorKind::invalid_argument;
break;
case StorageErrorCode::not_found:
kind = ErrorKind::not_found;
break;
case StorageErrorCode::conflict:
case StorageErrorCode::recovery_required:
case StorageErrorCode::busy:
case StorageErrorCode::incomplete_init:
kind = ErrorKind::conflict;
break;
case StorageErrorCode::interrupted:
case StorageErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case StorageErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case StorageErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case StorageErrorCode::unsupported_capability:
kind = ErrorKind::unsupported;
break;
case StorageErrorCode::io_error:
kind = ErrorKind::io;
break;
case StorageErrorCode::corrupt:
kind = ErrorKind::corrupt;
break;
case StorageErrorCode::sequence_exhausted:
case StorageErrorCode::quota_exceeded:
kind = ErrorKind::exhausted;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kStorageErrorDomain,
static_cast<std::int32_t>(code)},
sys_err};
}
struct StorageError {
StorageErrorCode code{StorageErrorCode::none};
Error error{};
};
struct CommitReceipt {
Sequence sequence{0};
Durability durability{Durability::Sync};
};
struct WriteFailure {
StorageError cause{};
Outcome outcome{Outcome::NotCommitted};
};
struct OwnedValue {
OwnedBytes bytes{};
Sequence version{0};
[[nodiscard]] std::string_view as_string_view() const noexcept
{
return bytes.empty()
? std::string_view{}
: std::string_view{
reinterpret_cast<const char*>(bytes.data()),
bytes.size()};
}
[[nodiscard]] bool operator==(const OwnedValue&) const = default;
};
[[nodiscard]] inline OwnedBytes to_owned_bytes(std::string_view s)
{
OwnedBytes out(s.size());
for (std::size_t i = 0; i < s.size(); ++i) {
out[i] = static_cast<std::byte>(static_cast<unsigned char>(s[i]));
}
return out;
}
[[nodiscard]] inline ByteView to_byte_view(std::string_view s) noexcept
{
return std::as_bytes(std::span{s.data(), s.size()});
}
[[nodiscard]] inline std::string_view to_string_view(ByteView b) noexcept
{
return b.empty()
? std::string_view{}
: std::string_view{
reinterpret_cast<const char*>(b.data()),
b.size()};
}
/// Locale-independent unsigned-byte lexicographic comparison.
[[nodiscard]] inline int byte_compare(ByteView a, ByteView b) noexcept
{
const std::size_t n = std::min(a.size(), b.size());
for (std::size_t i = 0; i < n; ++i) {
const auto xa = std::to_integer<unsigned char>(a[i]);
const auto yb = std::to_integer<unsigned char>(b[i]);
if (xa < yb) return -1;
if (xa > yb) return 1;
}
if (a.size() < b.size()) return -1;
if (a.size() > b.size()) return 1;
return 0;
}
struct ByteLess {
using is_transparent = void;
[[nodiscard]] bool operator()(ByteView a, ByteView b) const noexcept
{
return byte_compare(a, b) < 0;
}
[[nodiscard]] bool operator()(const OwnedBytes& a, const OwnedBytes& b) const noexcept
{
return byte_compare(a, b) < 0;
}
[[nodiscard]] bool operator()(const OwnedBytes& a, ByteView b) const noexcept
{
return byte_compare(a, b) < 0;
}
[[nodiscard]] bool operator()(ByteView a, const OwnedBytes& b) const noexcept
{
return byte_compare(a, b) < 0;
}
};
struct ScanBounds {
std::optional<OwnedBytes> begin{};
std::optional<OwnedBytes> end{};
std::size_t page_bytes{0};
std::size_t page_rows{0};
[[nodiscard]] static ScanBounds all() { return {}; }
[[nodiscard]] static ScanBounds range(ByteView b, ByteView e)
{
ScanBounds sb;
sb.begin.emplace(b.begin(), b.end());
sb.end.emplace(e.begin(), e.end());
return sb;
}
[[nodiscard]] static ScanBounds range(std::string_view b, std::string_view e)
{
return range(to_byte_view(b), to_byte_view(e));
}
[[nodiscard]] static ScanBounds prefix(ByteView p)
{
ScanBounds sb;
sb.begin.emplace(p.begin(), p.end());
OwnedBytes upper(p.begin(), p.end());
while (!upper.empty()) {
const auto b = std::to_integer<unsigned char>(upper.back());
if (b < 0xFFu) {
upper.back() = static_cast<std::byte>(b + 1u);
sb.end = std::move(upper);
return sb;
}
upper.pop_back();
}
// All-0xFF prefix has no finite upper bound.
return sb;
}
[[nodiscard]] static ScanBounds prefix(std::string_view p)
{
return prefix(to_byte_view(p));
}
};
struct ScanEntry {
OwnedBytes key{};
OwnedBytes value{};
Sequence version{0};
};
struct ScanPage {
std::vector<ScanEntry> entries{};
bool has_more{false};
};
struct Limits {
std::size_t max_key_bytes{4096};
std::size_t max_value_bytes{4ULL * 1024ULL * 1024ULL};
std::size_t max_batch_encoded_bytes{16ULL * 1024ULL * 1024ULL};
std::size_t max_batch_mutations{1024};
std::size_t max_batch_conditions{1024};
std::size_t max_pending_batches{64};
std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t active_memtable_target_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_total_memtable_bytes{256ULL * 1024ULL * 1024ULL};
std::size_t max_snapshots{128};
std::size_t max_cursors{128};
std::size_t default_scan_page_bytes{1024ULL * 1024ULL};
std::size_t max_scan_page_bytes{8ULL * 1024ULL * 1024ULL};
std::size_t default_scan_page_rows{1024};
std::size_t max_obsolete_pinned_bytes{1024ULL * 1024ULL * 1024ULL};
std::size_t block_cache_bytes{32ULL * 1024ULL * 1024ULL};
std::size_t compaction_workspace_bytes{16ULL * 1024ULL * 1024ULL};
std::uint64_t wal_segment_target_bytes{64ULL * 1024ULL * 1024ULL};
std::uint64_t max_wal_total_bytes{4ULL * 1024ULL * 1024ULL * 1024ULL};
std::size_t max_active_runs{32};
std::size_t table_block_target_bytes{32768};
std::size_t max_manifest_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_manifest_tables{65536};
std::size_t max_compaction_merge_runs{4};
std::uint64_t compaction_output_target_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t compaction_work_slice_bytes{8ULL * 1024ULL * 1024ULL};
};
[[nodiscard]] inline Result<void> validate_limits(const Limits& l)
{
if (l.max_key_bytes == 0 ||
l.max_value_bytes == 0 ||
l.max_batch_encoded_bytes == 0 ||
l.max_batch_mutations == 0 ||
l.max_batch_conditions == 0 ||
l.max_pending_batches == 0 ||
l.max_pending_bytes == 0 ||
l.active_memtable_target_bytes == 0 ||
l.max_total_memtable_bytes == 0 ||
l.max_snapshots == 0 ||
l.max_cursors == 0 ||
l.default_scan_page_bytes == 0 ||
l.max_scan_page_bytes == 0 ||
l.default_scan_page_rows == 0 ||
l.max_obsolete_pinned_bytes == 0 ||
l.block_cache_bytes == 0 ||
l.compaction_workspace_bytes == 0 ||
l.wal_segment_target_bytes == 0 ||
l.max_wal_total_bytes == 0 ||
l.max_active_runs == 0 ||
l.table_block_target_bytes == 0 ||
l.max_manifest_bytes == 0 ||
l.max_manifest_tables == 0 ||
l.max_compaction_merge_runs == 0 ||
l.compaction_output_target_bytes == 0 ||
l.compaction_work_slice_bytes == 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Limits: all limits must be positive finite values"));
}
if (l.default_scan_page_bytes > l.max_scan_page_bytes ||
l.active_memtable_target_bytes > l.max_total_memtable_bytes ||
l.wal_segment_target_bytes > l.max_wal_total_bytes ||
l.max_batch_encoded_bytes > l.wal_segment_target_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Limits: inconsistent bound ordering (max batch must fit in one WAL segment)"));
}
return {};
}
struct OpenOptions {
std::filesystem::path directory{};
Durability default_durability{Durability::Sync};
Limits limits{};
std::pmr::memory_resource* memory_resource{nullptr};
std::shared_ptr<FilePort> file_port{};
const Void::Time::MonotonicClock* monotonic_clock{nullptr};
std::function<void(std::string_view)> metric_hook{};
/// Optional explicit sequence seed used only when opening a brand-new
/// database (e.g. sequence-exhaustion tests).
Sequence initial_sequence{0};
};
struct EngineStats {
EngineState state{EngineState::Closed};
Sequence committed_sequence{0};
Sequence checkpoint_sequence{0};
Sequence oldest_snapshot_sequence{0};
std::uint64_t live_snapshots{0};
std::uint64_t live_cursors{0};
std::uint64_t active_memtable_bytes{0};
std::uint64_t total_memtable_bytes{0};
std::uint64_t wal_total_bytes{0};
std::uint64_t active_table_count{0};
std::uint64_t obsolete_pinned_bytes{0};
std::uint64_t total_table_bytes{0};
std::uint64_t recovery_truncated_bytes{0};
bool durable_sync_verified{false};
};
} // namespace Void::Storage
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <memory>
#include <string>
namespace Void::SystemAsync
{
struct ProcessManagerOptions {
std::size_t max_active_children{64};
std::size_t max_pending_spawns{128};
std::chrono::milliseconds default_kill_grace{std::chrono::milliseconds{2000}};
};
class ProcessManager;
class ManagedChild
{
public:
ManagedChild() noexcept = default;
~ManagedChild() noexcept;
ManagedChild(const ManagedChild&) = delete;
ManagedChild& operator=(const ManagedChild&) = delete;
ManagedChild(ManagedChild&&) noexcept;
ManagedChild& operator=(ManagedChild&&) noexcept;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] Void::Process::Child& child() noexcept { return child_; }
[[nodiscard]] const Void::Process::Child& child() const noexcept
{
return child_;
}
void release_slot() noexcept;
private:
friend class ProcessManager;
struct SlotGuard;
Void::Process::Child child_{};
std::shared_ptr<void> slot_token_{};
};
class ProcessManager
{
public:
struct Impl;
explicit ProcessManager(
Void::IO::Driver& driver,
Void::Async::Executor& executor,
ProcessManagerOptions options = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~ProcessManager() noexcept;
ProcessManager(const ProcessManager&) = delete;
ProcessManager& operator=(const ProcessManager&) = delete;
ProcessManager(ProcessManager&&) = delete;
ProcessManager& operator=(ProcessManager&&) = delete;
[[nodiscard]] Void::Result::Result<ManagedChild, Void::Result::Error>
spawn(const Void::Process::SpawnOptions& options);
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
communicate(Void::Process::Child& child,
std::string stdin_data = {},
Void::Process::CaptureLimits limits = {},
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
communicate(ManagedChild& managed,
std::string stdin_data = {},
Void::Process::CaptureLimits limits = {},
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
wait(Void::Process::Child& child,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
wait(ManagedChild& managed,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
close_and_join(Void::Async::OperationOptions options = {});
[[nodiscard]] std::size_t active_children() const noexcept;
[[nodiscard]] bool closed() const noexcept;
private:
std::shared_ptr<Impl> impl_;
};
} // namespace Void::SystemAsync
+116
View File
@@ -0,0 +1,116 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <string>
namespace Void::SystemAsync
{
enum class WatchEventKind {
created,
modified,
deleted,
replaced_inode,
symlink_changed,
permission_denied,
rescan_required,
};
struct WatchEvent {
WatchEventKind kind{WatchEventKind::modified};
std::filesystem::path path{};
bool exists{false};
std::uint64_t dev{0};
std::uint64_t ino{0};
std::uint64_t size{0};
int sys_errno{0};
};
struct WatcherLimits {
std::size_t max_watched_paths{1024};
std::size_t max_queued_events{256};
std::chrono::milliseconds poll_interval{std::chrono::milliseconds{250}};
int debounce_polls{1};
};
struct WatchPathOptions {
std::optional<std::filesystem::path> allowed_root{};
bool allow_symlink{false};
};
using WatchCallback = std::function<void(const WatchEvent&)>;
using ErrorSink = std::function<void(const Void::Result::Error&)>;
class WatcherService;
class WatchSubscription
{
public:
WatchSubscription() noexcept = default;
~WatchSubscription() noexcept;
WatchSubscription(const WatchSubscription&) = delete;
WatchSubscription& operator=(const WatchSubscription&) = delete;
WatchSubscription(WatchSubscription&&) noexcept;
WatchSubscription& operator=(WatchSubscription&&) noexcept;
[[nodiscard]] bool active() const noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
close_and_join();
private:
friend class WatcherService;
struct Token;
std::shared_ptr<Token> token_;
};
class WatcherService
{
public:
struct Impl;
explicit WatcherService(
Void::Async::Executor& executor,
WatcherLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
ErrorSink error_sink = {},
bool start_background_thread = false);
~WatcherService() noexcept;
WatcherService(const WatcherService&) = delete;
WatcherService& operator=(const WatcherService&) = delete;
WatcherService(WatcherService&&) = delete;
WatcherService& operator=(WatcherService&&) = delete;
[[nodiscard]] Void::Result::Result<WatchSubscription, Void::Result::Error>
watch(const std::filesystem::path& path,
WatchCallback callback,
WatchPathOptions options = {});
void poll_once();
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] std::size_t queued_event_count() const noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> shutdown();
private:
std::shared_ptr<Impl> impl_;
};
} // namespace Void::SystemAsync
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace Void::FileSystem
{
enum class DirectoryEventKind : std::uint8_t {
Created,
Modified,
Deleted,
Renamed,
AttributeChanged,
RescanRequired,
};
struct DirectoryEvent {
DirectoryEventKind kind{DirectoryEventKind::Modified};
std::filesystem::path path{};
std::filesystem::path old_path{};
bool is_directory{false};
std::string detail{};
};
/// Predicate queried for every discovered/modified path. Returning true skips
/// watching (for directories) and suppresses event delivery for that path.
using IgnorePredicate =
std::function<bool(const std::filesystem::path& path, bool is_directory)>;
struct DirectoryWatcherOptions {
IgnorePredicate ignore{};
std::size_t max_watches{65536};
std::size_t max_queued_events{4096};
std::chrono::milliseconds rename_pair_window{std::chrono::milliseconds{50}};
};
/// Kernel-event (Linux inotify) recursive directory watcher with auto-watch
/// attachment on new subdirectories, rename pairing, ignore filtering, and
/// explicit RescanRequired signaling on queue overflow or watch exhaustion.
class DirectoryWatcher final
{
public:
~DirectoryWatcher() noexcept;
DirectoryWatcher(const DirectoryWatcher&) = delete;
DirectoryWatcher& operator=(const DirectoryWatcher&) = delete;
DirectoryWatcher(DirectoryWatcher&&) noexcept;
DirectoryWatcher& operator=(DirectoryWatcher&&) noexcept;
[[nodiscard]] static Void::Result::Result<DirectoryWatcher,
Void::Result::Error>
create(const std::filesystem::path& root,
DirectoryWatcherOptions options = {});
[[nodiscard]] Void::Result::Result<std::vector<DirectoryEvent>,
Void::Result::Error>
poll(std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Re-walk `root()` and rebuild all inotify watches from scratch.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> rescan();
/// Wake any thread blocked inside poll().
void wake() noexcept;
/// Enqueue a RescanRequired event and wake waiters (deterministic test hook).
void simulate_overflow_for_test();
[[nodiscard]] const std::filesystem::path& root() const noexcept;
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] int native_handle() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> impl_{};
explicit DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::FileSystem
+105 -84
View File
@@ -1,5 +1,7 @@
#pragma once #pragma once
#include <Void/Time/Clock.hpp>
#include <chrono> #include <chrono>
#include <cstdint> #include <cstdint>
#include <optional> #include <optional>
@@ -12,113 +14,132 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
// Generic, app-agnostic process/system resource queries. Used to feed monitors
// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully
// supported; other platforms return nullopt / 0 so callers degrade gracefully.
namespace Void::SystemInfo namespace Void::SystemInfo
{ {
// ── memory ────────────────────────────────────────────────────────────── /// Resident set size (physical memory) of the current process, in bytes.
/// nullopt if it cannot be determined on this platform.
/// Resident set size (physical memory) of the current process, in bytes. [[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
/// nullopt if it cannot be determined on this platform. {
[[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
{
#if defined(__linux__) #if defined(__linux__)
// /proc/self/statm: "size resident shared text lib data dt" in pages. std::ifstream statm{"/proc/self/statm"};
std::ifstream statm{"/proc/self/statm"}; std::uint64_t total_pages = 0, resident_pages = 0;
std::uint64_t total_pages = 0, resident_pages = 0; if (statm >> total_pages >> resident_pages) {
if (statm >> total_pages >> resident_pages) { const long page = ::sysconf(_SC_PAGESIZE);
const long page = ::sysconf(_SC_PAGESIZE); if (page > 0) {
if (page > 0) { return resident_pages * static_cast<std::uint64_t>(page);
return resident_pages * static_cast<std::uint64_t>(page); }
} }
} return std::nullopt;
return std::nullopt;
#else #else
return std::nullopt; return std::nullopt;
#endif #endif
} }
struct SystemMemory { struct SystemMemory {
std::uint64_t total = 0; ///< total physical RAM, bytes std::uint64_t total = 0; ///< total physical RAM, bytes
std::uint64_t available = 0; ///< approx. RAM available to new work std::uint64_t available = 0; ///< approx. RAM available to new work
}; };
/// Total and (approximately) available system memory in bytes. /// Total and (approximately) available system memory in bytes.
[[nodiscard]] inline std::optional<SystemMemory> system_memory() [[nodiscard]] inline std::optional<SystemMemory> system_memory()
{ {
#if defined(__linux__) #if defined(__linux__)
struct ::sysinfo info{}; struct ::sysinfo info{};
if (::sysinfo(&info) != 0) { if (::sysinfo(&info) != 0) {
return std::nullopt; return std::nullopt;
} }
const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1; const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1;
SystemMemory m; SystemMemory m;
m.total = static_cast<std::uint64_t>(info.totalram) * unit; m.total = static_cast<std::uint64_t>(info.totalram) * unit;
// freeram excludes reclaimable cache/buffers, so this is conservative. m.available =
m.available = (static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit;
(static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit; return m;
return m;
#else #else
return std::nullopt; return std::nullopt;
#endif #endif
} }
// ── CPU ───────────────────────────────────────────────────────────────── struct CpuSample {
double ratio{0.0};
bool valid{false};
};
/// Samples this process's CPU usage between successive calls. usage() /// Samples this process's CPU usage between successive calls.
/// returns the fraction of a single core consumed since the previous /// `sample()` explicitly distinguishes real 0.0 from unavailable sampling.
/// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on class CpuSampler
/// multi-core workloads). The first call establishes the baseline and {
/// returns 0. public:
class CpuSampler explicit CpuSampler(
{ const Void::Time::MonotonicClock* clock =
public: &Void::Time::SystemMonotonicClock::instance())
: clock_(clock != nullptr ? clock
: &Void::Time::SystemMonotonicClock::instance())
{
reset();
}
CpuSampler() { reset(); } void reset()
{
void reset() wall_ = clock_->now();
{ baseline_valid_ = false;
wall_ = std::chrono::steady_clock::now();
#if defined(__linux__) #if defined(__linux__)
struct ::tms t{}; struct ::tms t{};
last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1)) if (::times(&t) != static_cast<::clock_t>(-1)) {
? 0 last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
: (t.tms_utime + t.tms_stime); static_cast<std::int64_t>(t.tms_stime);
baseline_valid_ = true;
}
#endif #endif
} }
[[nodiscard]] double usage() [[nodiscard]] CpuSample sample(
{ const Void::Time::MonotonicClock* override_clock = nullptr)
const auto now = std::chrono::steady_clock::now(); {
const std::chrono::duration<double> wall = now - wall_; const Void::Time::MonotonicClock* active =
wall_ = now; (override_clock != nullptr) ? override_clock : clock_;
const auto now = active->now();
const std::chrono::duration<double> wall = now - wall_;
wall_ = now;
#if defined(__linux__) #if defined(__linux__)
const long hz = ::sysconf(_SC_CLK_TCK); const long hz = ::sysconf(_SC_CLK_TCK);
struct ::tms t{}; struct ::tms t{};
if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) || if (!baseline_valid_ || hz <= 0 ||
wall.count() <= 0.0) { ::times(&t) == static_cast<::clock_t>(-1) || wall.count() <= 0.0) {
return 0.0; if (::times(&t) != static_cast<::clock_t>(-1)) {
} last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
const std::int64_t ticks = t.tms_utime + t.tms_stime; static_cast<std::int64_t>(t.tms_stime);
const double cpu_seconds = baseline_valid_ = true;
static_cast<double>(ticks - last_ticks_) / }
static_cast<double>(hz); return CpuSample{0.0, false};
last_ticks_ = ticks; }
return cpu_seconds / wall.count(); const std::int64_t ticks = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
const std::int64_t delta_ticks =
(ticks >= last_ticks_) ? (ticks - last_ticks_) : 0;
last_ticks_ = ticks;
const double cpu_seconds =
static_cast<double>(delta_ticks) / static_cast<double>(hz);
return CpuSample{cpu_seconds / wall.count(), true};
#else #else
return 0.0; (void)wall;
return CpuSample{0.0, false};
#endif #endif
} }
private: [[nodiscard]] double usage()
{
const auto s = sample();
return s.valid ? s.ratio : 0.0;
}
std::chrono::steady_clock::time_point wall_; private:
const Void::Time::MonotonicClock* clock_;
Void::Time::MonotonicClock::time_point wall_{};
bool baseline_valid_{false};
#if defined(__linux__) #if defined(__linux__)
std::int64_t last_ticks_ = 0; std::int64_t last_ticks_{0};
#endif #endif
}; };
} // namespace Void::SystemInfo } // namespace Void::SystemInfo
+1123 -124
View File
File diff suppressed because it is too large. Load diff
+189 -51
View File
@@ -2,72 +2,210 @@
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono> #include <chrono>
#include <cstddef>
#include <filesystem> #include <filesystem>
#include <functional> #include <functional>
#include <optional>
#include <stop_token>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <utility>
#include <vector> #include <vector>
namespace Void::Process namespace Void::Process
{ {
/// Captured output from a completed subprocess. inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
struct Output { inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
int exit_code{0}; inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
std::string out; ///< captured stdout inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL;
std::string err; ///< captured stderr inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL;
};
/// Live line callbacks for run_streaming(). Each fires (on the calling /// Captured output from a completed subprocess.
/// thread, as output arrives) with one line of output, newline stripped. struct Output {
/// Either may be left empty. The full output is still accumulated into the int exit_code{0};
/// returned Output. std::string out; ///< captured stdout
struct StreamCallbacks { std::string err; ///< captured stderr
std::function<void(std::string_view line)> on_stdout; };
std::function<void(std::string_view line)> on_stderr;
};
/// Run an executable synchronously, capturing stdout and stderr separately. /// Live line callbacks for run_streaming() and communicate_blocking().
/// struct StreamCallbacks {
/// @param executable Path to the binary (searched via PATH when relative). std::function<void(std::string_view line)> on_stdout;
/// @param args Additional arguments passed after argv[0]. std::function<void(std::string_view line)> on_stderr;
/// @param stdin_data Data written to the process's stdin before reading. };
/// @param timeout Wall-clock limit; zero means no limit. On expiry the
/// process receives SIGTERM and the call returns.
///
/// Returns an error only when process creation itself fails (pipe or fork
/// failure). A process that exits non-zero still yields a successful Result
/// with the appropriate exit_code. A process whose executable is not found
/// exits with code 127 (POSIX convention).
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr enum class OverflowPolicy {
/// arrive, for progress reporting on long-running or streaming processes. fail_and_terminate,
/// The complete output is still captured into the returned Output. drain_and_truncate,
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error> };
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Run a command through /bin/sh -c "command". enum class EnvMode {
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error> inherit,
shell(std::string_view command, allowlist,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); explicit_only,
};
/// Replace the current process image while preserving its PID and inherited struct EnvironmentPolicy {
/// environment. Returns only when the platform does not support re-exec or EnvMode mode{EnvMode::inherit};
/// exec fails. std::vector<std::string> allowlist{};
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> std::vector<std::pair<std::string, std::string>> set_vars{};
reexec(const std::filesystem::path& executable, std::vector<std::string> unset_keys{};
const std::vector<std::string>& arguments); std::vector<std::string> redacted_keys{};
};
struct CaptureLimits {
std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes};
std::size_t max_stderr_bytes{kDefaultMaxStderrBytes};
std::size_t max_line_bytes{kDefaultMaxLineBytes};
std::size_t max_stdin_bytes{kDefaultMaxStdinBytes};
OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate};
};
struct SpawnOptions {
std::filesystem::path executable{};
std::vector<std::string> arguments{};
std::optional<std::filesystem::path> working_directory{};
EnvironmentPolicy environment{};
bool stdin_pipe{true};
bool stdout_pipe{true};
bool stderr_pipe{true};
bool search_path{true};
bool new_process_group{true};
std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}};
};
struct ExitStatus {
bool exited{false};
int code{-1};
int signal{0};
int raw_status{0};
};
struct CommunicateResult {
ExitStatus status{};
std::string out{};
std::string err{};
bool stdout_truncated{false};
bool stderr_truncated{false};
bool timed_out{false};
bool cancelled{false};
bool overflowed{false};
};
class Child
{
public:
Child() noexcept = default;
Child(long long pid,
long long pgid,
bool owns_process_group,
Void::System::OwnedFd stdin_fd,
Void::System::OwnedFd stdout_fd,
Void::System::OwnedFd stderr_fd,
std::chrono::milliseconds kill_grace) noexcept;
~Child() noexcept;
Child(const Child&) = delete;
Child& operator=(const Child&) = delete;
Child(Child&& other) noexcept;
Child& operator=(Child&& other) noexcept;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] bool process_group_alive() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
[[nodiscard]] int stdin_fd() const noexcept;
[[nodiscard]] int stdout_fd() const noexcept;
[[nodiscard]] int stderr_fd() const noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept;
void close_stdin() noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_signal(int sig) noexcept;
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
[[nodiscard]] Void::Result::Result<std::optional<ExitStatus>, Void::Result::Error>
try_wait();
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1});
private:
long long pid_{-1};
long long pgid_{-1};
bool owns_group_{false};
bool reaped_{true};
ExitStatus cached_status_{};
Void::System::OwnedFd stdin_{};
Void::System::OwnedFd stdout_{};
Void::System::OwnedFd stderr_{};
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
void reset_and_reap() noexcept;
};
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
spawn(const SpawnOptions& options);
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data = {},
CaptureLimits limits = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
const StreamCallbacks* callbacks = nullptr);
/// Run an executable synchronously, capturing stdout and stderr separately.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Run a command through /bin/sh -c "command".
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Replace the current process image while preserving its PID and inherited
/// environment.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments);
/// Replace the current process image with explicit open-descriptor cleanup policy.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments,
bool close_extra_fds);
/// Opt the current process into Linux PR_SET_CHILD_SUBREAPER so orphaned
/// descendant processes in spawned process groups reparent to this process
/// and can be reaped directly via waitpid(-pgid, ...).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
enable_subreaper() noexcept;
} // namespace Void::Process } // namespace Void::Process
+133 -81
View File
@@ -1,9 +1,13 @@
#pragma once #pragma once
#include <Void/Log/Log.hpp>
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
#include <system_error> #include <system_error>
@@ -12,113 +16,161 @@
namespace Void::FileSystem namespace Void::FileSystem
{ {
struct ListDirectoryOptions {
std::size_t max_entries{65536};
};
/// Return true if path exists (file, directory, or symlink). /// Return true if path exists (file, directory, or symlink).
[[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept [[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept
{ {
std::error_code ec; std::error_code ec;
return std::filesystem::exists(path, ec); return std::filesystem::exists(path, ec);
} }
/// Return the size of a regular file in bytes. /// Return the size of a regular file in bytes.
[[nodiscard]] inline Void::Result::Result<std::uintmax_t, Void::Result::Error> [[nodiscard]] inline Void::Result::Result<std::uintmax_t, Void::Result::Error>
file_size(const std::filesystem::path& path) file_size(const std::filesystem::path& path)
{ {
std::error_code ec; std::error_code ec;
auto sz = std::filesystem::file_size(path, ec); auto sz = std::filesystem::file_size(path, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "file_size: cannot stat '{}': {}", path.string(), Void::Log::warn("FileSystem",
ec.message()); "file_size: cannot stat '{}': {}",
return Void::Result::fail( path.string(),
std::format("FileSystem::file_size: cannot stat '{}': {}", ec.message());
path.string(), ec.message())); return std::unexpected{Void::System::make_system_error(
} Void::System::map_errno_to_system_code(ec.value()),
return Void::Result::ok(sz); std::format("FileSystem::file_size: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(sz);
} }
/// Return the last-write time of a path. /// Return the last-write time of a path.
[[nodiscard]] inline Void::Result:: [[nodiscard]] inline Void::Result::
Result<std::filesystem::file_time_type, Void::Result::Error> Result<std::filesystem::file_time_type, Void::Result::Error>
last_modified(const std::filesystem::path& path) last_modified(const std::filesystem::path& path)
{ {
std::error_code ec; std::error_code ec;
auto t = std::filesystem::last_write_time(path, ec); auto t = std::filesystem::last_write_time(path, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "last_modified: cannot stat '{}': {}", path.string(), Void::Log::warn("FileSystem",
ec.message()); "last_modified: cannot stat '{}': {}",
return Void::Result::fail( path.string(),
std::format("FileSystem::last_modified: cannot stat '{}': {}", ec.message());
path.string(), ec.message())); return std::unexpected{Void::System::make_system_error(
} Void::System::map_errno_to_system_code(ec.value()),
return Void::Result::ok(t); std::format("FileSystem::last_modified: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(t);
} }
/// List all entries in a directory (non-recursive, filesystem order). /// List entries in a directory up to `options.max_entries`.
[[nodiscard]] inline Void::Result:: [[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error> Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path) list_directory_bounded(const std::filesystem::path& path,
ListDirectoryOptions options = {})
{ {
std::error_code ec; std::error_code ec;
std::vector<std::filesystem::path> entries; std::vector<std::filesystem::path> entries;
for (const auto& entry : for (const auto& entry : std::filesystem::directory_iterator{path, ec}) {
std::filesystem::directory_iterator{path, ec}) { if (ec) {
if (ec) { break;
break; }
} if (entries.size() >= options.max_entries) {
entries.push_back(entry.path()); return std::unexpected{Void::System::make_system_error(
} Void::System::SystemErrorCode::limit_exceeded,
if (ec) { std::format(
Void::Log::warn("FileSystem", "list_directory: cannot iterate '{}': {}", "FileSystem::list_directory: '{}' exceeded max_entries ({})",
path.string(), ec.message()); path.string(),
return Void::Result::fail( options.max_entries))};
std::format("FileSystem::list_directory: cannot iterate '{}': {}", }
path.string(), ec.message())); entries.push_back(entry.path());
} }
Void::Log::debug("FileSystem", "list_directory: '{}' ({} entries)", if (ec) {
path.string(), entries.size()); Void::Log::warn("FileSystem",
return Void::Result::ok(std::move(entries)); "list_directory: cannot iterate '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::list_directory: cannot iterate '{}': {}",
path.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"list_directory: '{}' ({} entries)",
path.string(),
entries.size());
return Void::Result::ok(std::move(entries));
}
/// List all entries in a directory (bounded at 65,536 default).
[[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path)
{
return list_directory_bounded(path, ListDirectoryOptions{});
} }
/// Copy a single file. Set overwrite=true to allow replacing an existing dst. /// Copy a single file. Set overwrite=true to allow replacing an existing dst.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error> [[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_file(const std::filesystem::path& src, copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst, const std::filesystem::path& dst,
bool overwrite = false) bool overwrite = false)
{ {
std::error_code ec; std::error_code ec;
auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing
: std::filesystem::copy_options::none; : std::filesystem::copy_options::none;
std::filesystem::copy_file(src, dst, opts, ec); std::filesystem::copy_file(src, dst, opts, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "copy_file: '{}' -> '{}': {}", src.string(), Void::Log::warn("FileSystem",
dst.string(), ec.message()); "copy_file: '{}' -> '{}': {}",
return Void::Result::fail( src.string(),
std::format("FileSystem::copy_file: '{}' -> '{}': {}", dst.string(),
src.string(), dst.string(), ec.message())); ec.message());
} return std::unexpected{Void::System::make_system_error(
Void::Log::debug("FileSystem", "copy_file: '{}' -> '{}'", src.string(), Void::System::map_errno_to_system_code(ec.value()),
dst.string()); std::format("FileSystem::copy_file: '{}' -> '{}': {}",
return {}; src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_file: '{}' -> '{}'",
src.string(),
dst.string());
return {};
} }
/// Recursively copy a directory tree from src to dst. /// Recursively copy a directory tree from src to dst.
/// dst must not already exist; its parent must be accessible.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error> [[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_dir(const std::filesystem::path& src, copy_dir(const std::filesystem::path& src, const std::filesystem::path& dst)
const std::filesystem::path& dst)
{ {
std::error_code ec; std::error_code ec;
std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive, std::filesystem::copy(
ec); src, dst, std::filesystem::copy_options::recursive, ec);
if (ec) { if (ec) {
Void::Log::warn("FileSystem", "copy_dir: '{}' -> '{}': {}", src.string(), Void::Log::warn("FileSystem",
dst.string(), ec.message()); "copy_dir: '{}' -> '{}': {}",
return Void::Result::fail( src.string(),
std::format("FileSystem::copy_dir: '{}' -> '{}': {}", dst.string(),
src.string(), dst.string(), ec.message())); ec.message());
} return std::unexpected{Void::System::make_system_error(
Void::Log::debug("FileSystem", "copy_dir: '{}' -> '{}'", src.string(), Void::System::map_errno_to_system_code(ec.value()),
dst.string()); std::format("FileSystem::copy_dir: '{}' -> '{}': {}",
return {}; src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_dir: '{}' -> '{}'",
src.string(),
dst.string());
return {};
} }
} // namespace Void::FileSystem } // namespace Void::FileSystem
+224 -99
View File
@@ -1,126 +1,251 @@
#pragma once #pragma once
#include <Void/System/Path.hpp>
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstdint> #include <cstdint>
#include <expected>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <system_error> #include <system_error>
#include <thread>
#include <utility> #include <utility>
#include <vector>
#ifndef _WIN32
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem namespace Void::FileSystem
{ {
/// RAII scoped directory under `std::filesystem::temp_directory_path()`.
///
/// The directory is created with a unique name on construction and
/// recursively removed on destruction. Useful in tests that need a
/// scratch area without manual cleanup.
///
/// Construction throws `std::system_error` if the directory cannot
/// be created. Use `TempDir::open(prefix)` for a non-throwing
/// `Result`-returning factory.
class TempDir
{
public:
explicit TempDir(std::string_view prefix = "void_test_") /// RAII scoped directory created with private `0700` permissions and removed
: m_path(make_unique_dir(prefix)) /// safely without following symlinks or deleting replaced directories.
{ class TempDir
} {
public:
explicit TempDir(std::string_view prefix = "void_test_")
{
auto created = create_unique_dir(
std::filesystem::temp_directory_path(), prefix);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempDir() noexcept ~TempDir() noexcept { remove_if_owned(); }
{
if (!m_path.empty()) {
Void::Log::debug("FileSystem", "TempDir: removed '{}'", m_path.string());
std::error_code ignore;
std::filesystem::remove_all(m_path, ignore);
}
}
TempDir(const TempDir&) = delete; TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete; TempDir& operator=(const TempDir&) = delete;
TempDir(TempDir&& other) noexcept TempDir(TempDir&& other) noexcept
: m_path(std::exchange(other.m_path, {})) : m_path(std::exchange(other.m_path, {})),
{ m_dev(std::exchange(other.m_dev, 0)),
} m_ino(std::exchange(other.m_ino, 0))
{
}
TempDir& operator=(TempDir&& other) noexcept TempDir& operator=(TempDir&& other) noexcept
{ {
if (this != &other) { if (this != &other) {
if (!m_path.empty()) { remove_if_owned();
std::error_code ignore; m_path = std::exchange(other.m_path, {});
std::filesystem::remove_all(m_path, ignore); m_dev = std::exchange(other.m_dev, 0);
} m_ino = std::exchange(other.m_ino, 0);
m_path = std::exchange(other.m_path, {}); }
} return *this;
return *this; }
}
[[nodiscard]] const std::filesystem::path& path() const noexcept [[nodiscard]] const std::filesystem::path& path() const noexcept
{ {
return m_path; return m_path;
} }
/// Build a path inside the temp dir. [[nodiscard]] std::filesystem::path
/// Example: `auto log_path = tmp / "test.log";` operator/(std::string_view relative) const
[[nodiscard]] std::filesystem::path {
operator/(std::string_view relative) const return m_path / relative;
{ }
return m_path / relative;
}
/// Non-throwing factory. [[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
[[nodiscard]] static Void::Result::Result<TempDir, open(std::string_view prefix = "void_test_")
Void::Result::Error> {
open(std::string_view prefix = "void_test_") return open_in(std::filesystem::temp_directory_path(), prefix);
{ }
try {
return Void::Result::ok(TempDir{prefix});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
private: [[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_test_")
{
return create_unique_dir(directory, prefix);
}
std::filesystem::path m_path; private:
struct InternalEmpty {};
explicit TempDir(InternalEmpty) noexcept {}
static std::filesystem::path std::filesystem::path m_path;
make_unique_dir(std::string_view prefix) std::uint64_t m_dev = 0;
{ std::uint64_t m_ino = 0;
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path(); #ifndef _WIN32
for (int attempt = 0; attempt < 16; ++attempt) { static void clear_dir_contents_nofollow(int dir_fd) noexcept
const auto seed = {
static_cast<std::uint64_t>( const int dup_fd = ::dup(dir_fd);
std::chrono::steady_clock::now() if (dup_fd < 0) {
.time_since_epoch() return;
.count()) ^ }
(counter.fetch_add(1, std::memory_order_relaxed) DIR* dir = ::fdopendir(dup_fd);
<< 16) ^ if (dir == nullptr) {
static_cast<std::uint64_t>(std::hash<std::thread::id>{}( (void)::close(dup_fd);
std::this_thread::get_id())); return;
auto candidate = }
base / std::format("{}{:016x}", prefix, seed); std::vector<std::string> subdirs;
std::error_code ec; std::vector<std::string> files;
if (std::filesystem::create_directory(candidate, ec)) { while (const struct dirent* ent = ::readdir(dir)) {
Void::Log::debug("FileSystem", "TempDir: created '{}'", const std::string_view name{ent->d_name};
candidate.string()); if (name == "." || name == "..") {
return candidate; continue;
} }
} struct stat st {};
throw std::system_error( if (::fstatat(dir_fd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0) {
std::make_error_code(std::errc::file_exists), continue;
"TempDir: failed to create unique directory after 16 " }
"attempts"); if (S_ISDIR(st.st_mode)) {
} subdirs.emplace_back(name);
}; } else {
files.emplace_back(name);
}
}
(void)::closedir(dir);
for (const auto& f : files) {
(void)::unlinkat(dir_fd, f.c_str(), 0);
}
for (const auto& d : subdirs) {
const int sub_fd = ::openat(
dir_fd,
d.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (sub_fd >= 0) {
clear_dir_contents_nofollow(sub_fd);
(void)::close(sub_fd);
(void)::unlinkat(dir_fd, d.c_str(), AT_REMOVEDIR);
}
}
}
#endif
void remove_if_owned() noexcept
{
if (m_path.empty()) {
return;
}
#ifndef _WIN32
struct stat st {};
if (::lstat(m_path.c_str(), &st) != 0 || S_ISLNK(st.st_mode) ||
!S_ISDIR(st.st_mode)) {
return;
}
if (static_cast<std::uint64_t>(st.st_dev) != m_dev ||
static_cast<std::uint64_t>(st.st_ino) != m_ino ||
st.st_uid != ::geteuid()) {
return;
}
const int dir_fd = ::open(
m_path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (dir_fd < 0) {
return;
}
struct stat fd_st {};
if (::fstat(dir_fd, &fd_st) == 0 &&
static_cast<std::uint64_t>(fd_st.st_dev) == m_dev &&
static_cast<std::uint64_t>(fd_st.st_ino) == m_ino) {
clear_dir_contents_nofollow(dir_fd);
}
(void)::close(dir_fd);
(void)::rmdir(m_path.c_str());
Void::Log::debug(
"FileSystem", "TempDir: removed '{}'", m_path.string());
#endif
}
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
create_unique_dir(const std::filesystem::path& base,
std::string_view prefix)
{
#ifndef _WIN32
if (prefix.find('/') != std::string_view::npos ||
prefix.find('\0') != std::string_view::npos) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempDir: prefix must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate = base / std::format("{}{:016x}", prefix, seed);
if (::mkdir(candidate.c_str(), 0700) == 0) {
const int fd = ::open(
candidate.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: open failed after mkdir",
err)};
}
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: fstat failed",
err)};
}
TempDir out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempDir: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"TempDir: failed creating '{}'", candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempDir: failed to create unique directory after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempDir: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem } // namespace Void::FileSystem
+163 -105
View File
@@ -2,135 +2,193 @@
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <cstdint> #include <cstdint>
#include <expected>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
#include <fstream>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <system_error> #include <system_error>
#include <thread> #include <thread>
#include <utility> #include <utility>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem namespace Void::FileSystem
{ {
/// RAII scoped *file* under `std::filesystem::temp_directory_path()`.
///
/// A uniquely-named empty file is created on construction and removed on
/// destruction, unless `keep()` was called. Move-only. Useful for staging
/// downloads, copying a shared library to a fresh inode, etc.
///
/// Construction throws `std::system_error` if the file cannot be created;
/// use `TempFile::open(prefix, ext)` for a non-throwing factory.
class TempFile
{
public:
explicit TempFile(std::string_view prefix = "void_", /// RAII scoped regular file created atomically (`O_CREAT|O_EXCL|O_NOFOLLOW`, `0600`).
std::string_view extension = "") class TempFile
: m_path(make_unique_file(prefix, extension)) {
{ public:
} explicit TempFile(std::string_view prefix = "void_",
std::string_view extension = "")
{
auto created = create_unique_file(
std::filesystem::temp_directory_path(), prefix, extension);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempFile() noexcept ~TempFile() noexcept { remove_if_owned(); }
{
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
Void::Log::debug("FileSystem", "TempFile: removed '{}'",
m_path.string());
}
}
TempFile(const TempFile&) = delete; TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete; TempFile& operator=(const TempFile&) = delete;
TempFile(TempFile&& other) noexcept TempFile(TempFile&& other) noexcept
: m_path(std::exchange(other.m_path, {})), : m_path(std::exchange(other.m_path, {})),
m_keep(std::exchange(other.m_keep, true)) m_keep(std::exchange(other.m_keep, true)),
{ m_dev(std::exchange(other.m_dev, 0)),
} m_ino(std::exchange(other.m_ino, 0))
{
}
TempFile& operator=(TempFile&& other) noexcept TempFile& operator=(TempFile&& other) noexcept
{ {
if (this != &other) { if (this != &other) {
if (!m_path.empty() && !m_keep) { remove_if_owned();
std::error_code ignore; m_path = std::exchange(other.m_path, {});
std::filesystem::remove(m_path, ignore); m_keep = std::exchange(other.m_keep, true);
} m_dev = std::exchange(other.m_dev, 0);
m_path = std::exchange(other.m_path, {}); m_ino = std::exchange(other.m_ino, 0);
m_keep = std::exchange(other.m_keep, true); }
} return *this;
return *this; }
}
[[nodiscard]] const std::filesystem::path& path() const noexcept [[nodiscard]] const std::filesystem::path& path() const noexcept
{ {
return m_path; return m_path;
} }
/// Persist the file beyond this object's lifetime (no removal on std::filesystem::path keep() noexcept
/// destruction). Returns the path for convenience. {
std::filesystem::path keep() noexcept m_keep = true;
{ return m_path;
m_keep = true; }
return m_path;
}
/// Non-throwing factory. [[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
[[nodiscard]] static Void::Result::Result<TempFile, open(std::string_view prefix = "void_",
Void::Result::Error> std::string_view extension = "")
open(std::string_view prefix = "void_", {
std::string_view extension = "") return open_in(
{ std::filesystem::temp_directory_path(), prefix, extension);
try { }
return Void::Result::ok(TempFile{prefix, extension});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
private: [[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_",
std::string_view extension = "")
{
return create_unique_file(directory, prefix, extension);
}
std::filesystem::path m_path; private:
bool m_keep = false; struct InternalEmpty {};
explicit TempFile(InternalEmpty) noexcept {}
static std::filesystem::path std::filesystem::path m_path;
make_unique_file(std::string_view prefix, bool m_keep = true;
std::string_view extension) std::uint64_t m_dev = 0;
{ std::uint64_t m_ino = 0;
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path(); void remove_if_owned() noexcept
for (int attempt = 0; attempt < 16; ++attempt) { {
const auto seed = if (m_path.empty() || m_keep) {
static_cast<std::uint64_t>( return;
std::chrono::steady_clock::now() }
.time_since_epoch() #ifndef _WIN32
.count()) ^ struct stat st {};
(counter.fetch_add(1, std::memory_order_relaxed) << 16) ^ if (::lstat(m_path.c_str(), &st) == 0 && !S_ISLNK(st.st_mode) &&
static_cast<std::uint64_t>( S_ISREG(st.st_mode) &&
std::hash<std::thread::id>{}( static_cast<std::uint64_t>(st.st_dev) == m_dev &&
std::this_thread::get_id())); static_cast<std::uint64_t>(st.st_ino) == m_ino) {
auto candidate = (void)::unlink(m_path.c_str());
base / std::format("{}{:016x}{}", prefix, seed, extension); Void::Log::debug(
std::error_code ec; "FileSystem", "TempFile: removed '{}'", m_path.string());
if (!std::filesystem::exists(candidate, ec)) { }
std::ofstream f(candidate); #endif
if (f) { }
Void::Log::debug("FileSystem",
"TempFile: created '{}'", [[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
candidate.string()); create_unique_file(const std::filesystem::path& base,
return candidate; std::string_view prefix,
} std::string_view extension)
} {
} #ifndef _WIN32
throw std::system_error( if (prefix.find('/') != std::string_view::npos ||
std::make_error_code(std::errc::file_exists), prefix.find('\0') != std::string_view::npos ||
"TempFile: failed to create unique file after 16 attempts"); extension.find('/') != std::string_view::npos ||
} extension.find('\0') != std::string_view::npos) {
}; return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempFile: prefix/extension must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate =
base / std::format("{}{:016x}{}", prefix, seed, extension);
const int fd = ::open(candidate.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
0600);
if (fd >= 0) {
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::unlink(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempFile: fstat failed",
err)};
}
TempFile out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_keep = false;
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempFile: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format("TempFile: failed creating '{}'",
candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempFile: failed to create unique file after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
(void)extension;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempFile: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem } // namespace Void::FileSystem
+207
View File
@@ -0,0 +1,207 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <expected>
#include <format>
#include <string>
#include <string_view>
#include <utility>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::System
{
enum class SystemErrorCode : std::int32_t {
invalid_argument = 1,
not_found = 2,
permission_denied = 3,
already_exists = 4,
spawn_failed = 5,
exec_failed = 6,
timed_out = 7,
cancelled = 8,
output_limit = 9,
line_limit = 10,
io_error = 11,
sync_failed = 12,
durability_unknown = 13,
limit_exceeded = 14,
busy = 15,
self_join = 16,
unsupported = 17,
unavailable = 18,
internal = 19,
};
[[nodiscard]] constexpr Void::Result::ErrorKind
classify_system_error(SystemErrorCode code) noexcept
{
switch (code) {
case SystemErrorCode::invalid_argument:
return Void::Result::ErrorKind::invalid_argument;
case SystemErrorCode::not_found:
return Void::Result::ErrorKind::not_found;
case SystemErrorCode::already_exists:
case SystemErrorCode::busy:
case SystemErrorCode::self_join:
return Void::Result::ErrorKind::conflict;
case SystemErrorCode::timed_out:
return Void::Result::ErrorKind::timeout;
case SystemErrorCode::cancelled:
return Void::Result::ErrorKind::cancelled;
case SystemErrorCode::output_limit:
case SystemErrorCode::line_limit:
case SystemErrorCode::limit_exceeded:
return Void::Result::ErrorKind::exhausted;
case SystemErrorCode::unsupported:
return Void::Result::ErrorKind::unsupported;
case SystemErrorCode::unavailable:
return Void::Result::ErrorKind::overloaded;
case SystemErrorCode::permission_denied:
case SystemErrorCode::spawn_failed:
case SystemErrorCode::exec_failed:
case SystemErrorCode::io_error:
case SystemErrorCode::sync_failed:
case SystemErrorCode::durability_unknown:
return Void::Result::ErrorKind::io;
case SystemErrorCode::internal:
return Void::Result::ErrorKind::internal;
}
return Void::Result::ErrorKind::internal;
}
[[nodiscard]] inline SystemErrorCode
map_errno_to_system_code(int sys_errno) noexcept
{
switch (sys_errno) {
case ENOENT:
return SystemErrorCode::not_found;
case EACCES:
case EPERM:
case EROFS:
return SystemErrorCode::permission_denied;
case EEXIST:
return SystemErrorCode::already_exists;
case ETIMEDOUT:
return SystemErrorCode::timed_out;
case ECANCELED:
return SystemErrorCode::cancelled;
case EBUSY:
return SystemErrorCode::busy;
case EINVAL:
case ENAMETOOLONG:
case EISDIR:
case ENOTDIR:
return SystemErrorCode::invalid_argument;
case ENOSYS:
case EOPNOTSUPP:
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
case ENOTSUP:
#endif
return SystemErrorCode::unsupported;
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
return SystemErrorCode::unavailable;
default:
return SystemErrorCode::io_error;
}
}
[[nodiscard]] inline Void::Result::Error make_system_error(
SystemErrorCode code, std::string_view message, int sys_errno = 0)
{
std::string detail;
if (sys_errno != 0) {
detail = std::format("{} (errno={}: {})",
message,
sys_errno,
std::strerror(sys_errno));
} else {
detail.assign(message);
}
std::error_code sys_ec{};
if (sys_errno != 0) {
sys_ec = std::error_code{sys_errno, std::generic_category()};
}
return Void::Result::Error{
classify_system_error(code),
std::move(detail),
Void::Result::ErrorCode{Void::Result::kSystemErrorDomain,
static_cast<std::int32_t>(code)},
sys_ec};
}
class OwnedFd
{
public:
OwnedFd() noexcept = default;
explicit OwnedFd(int fd) noexcept : fd_(fd) {}
~OwnedFd() noexcept { reset(); }
OwnedFd(const OwnedFd&) = delete;
OwnedFd& operator=(const OwnedFd&) = delete;
OwnedFd(OwnedFd&& other) noexcept
: fd_(std::exchange(other.fd_, -1))
{
}
OwnedFd& operator=(OwnedFd&& other) noexcept
{
if (this != &other) {
reset();
fd_ = std::exchange(other.fd_, -1);
}
return *this;
}
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
[[nodiscard]] explicit operator bool() const noexcept { return valid(); }
[[nodiscard]] int get() const noexcept { return fd_; }
[[nodiscard]] int release() noexcept { return std::exchange(fd_, -1); }
void reset(int new_fd = -1) noexcept
{
const int old = std::exchange(fd_, new_fd);
#ifndef _WIN32
if (old >= 0) {
(void)::close(old);
}
#else
(void)old;
#endif
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> close() noexcept
{
const int old = std::exchange(fd_, -1);
if (old < 0) {
return {};
}
#ifndef _WIN32
if (::close(old) != 0) {
const int err = errno;
return std::unexpected{make_system_error(
map_errno_to_system_code(err), "OwnedFd::close failed", err)};
}
#endif
return {};
}
private:
int fd_{-1};
};
} // namespace Void::System
+185 -5
View File
@@ -1,10 +1,190 @@
#pragma once #pragma once
namespace Void::Testing { #include <Void/Testing/Config.hpp>
#include <Void/Testing/Detail/Registry.hpp>
// Aliases to void so users can omit return statements safely #include <initializer_list>
// and avoid compiler warnings/errors. Perfectly matches std::function<void()>. #include <string>
using Test = void; #include <string_view>
using DisabledTest = void; #include <utility>
#include <vector>
namespace Void::Testing
{
// Aliases to void so users can omit return statements safely
// and avoid compiler warnings/errors. Perfectly matches
// std::function<void()>.
using Test = void;
using DisabledTest = void;
namespace Detail
{
[[nodiscard]] inline std::string
normalize_suite_label(std::string_view raw)
{
if (raw.size() >= 2 && raw.front() == '"' && raw.back() == '"') {
raw = raw.substr(1, raw.size() - 2);
}
return std::string{raw};
}
class NativeRegistrar final
{
public:
NativeRegistrar(void (*fn)(), std::string_view suite,
const char* file, int line,
std::string_view name,
std::initializer_list<const char*> tags = {},
bool disabled = false,
std::string_view skip_reason = {})
{
std::vector<std::string> tag_vec;
tag_vec.reserve(tags.size());
for (const char* t : tags) {
if (t != nullptr) {
tag_vec.emplace_back(t);
}
}
Registry::instance().add(TestCase{
.run = fn,
.name = std::string{name},
.suite = normalize_suite_label(suite),
.file = file != nullptr ? file : "",
.line = line,
.disabled = disabled,
.skip_reason = std::string{skip_reason},
.tags = std::move(tag_vec),
});
}
};
template <typename FixtureT> class NativeFixtureRegistrar final
{
public:
NativeFixtureRegistrar(void (*fn)(FixtureT&),
std::string_view suite,
const char* file, int line,
std::string_view name,
std::initializer_list<const char*> tags = {},
bool disabled = false,
std::string_view skip_reason = {})
{
std::vector<std::string> tag_vec;
tag_vec.reserve(tags.size());
for (const char* t : tags) {
if (t != nullptr) {
tag_vec.emplace_back(t);
}
}
Registry::instance().add(TestCase{
.run =
[fn]() {
FixtureT fixture{};
if constexpr (requires { fixture.setup(); }) {
fixture.setup();
}
try {
fn(fixture);
} catch (...) {
if constexpr (requires {
fixture.teardown();
}) {
fixture.teardown();
}
throw;
}
if constexpr (requires { fixture.teardown(); }) {
fixture.teardown();
}
},
.name = std::string{name},
.suite = normalize_suite_label(suite),
.file = file != nullptr ? file : "",
.line = line,
.disabled = disabled,
.skip_reason = std::string{skip_reason},
.tags = std::move(tag_vec),
});
}
};
} // namespace Detail
} // namespace Void::Testing } // namespace Void::Testing
#define VOID_TESTING_DETAIL_CAT_IMPL(a, b) a##b
#define VOID_TESTING_DETAIL_CAT(a, b) VOID_TESTING_DETAIL_CAT_IMPL(a, b)
#ifdef __COUNTER__
#define VOID_TESTING_DETAIL_NEXT_ID __COUNTER__
#else
#define VOID_TESTING_DETAIL_NEXT_ID __LINE__
#endif
#define VOID_TESTING_DETAIL_DEFINE_TEST(suite_expr, test_name, disabled_flag, \
skip_msg, uid, ...) \
static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)(); \
namespace \
{ \
[[maybe_unused]] const ::Void::Testing::Detail::NativeRegistrar \
VOID_TESTING_DETAIL_CAT(_void_native_test_reg_, uid){ \
&VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid), \
(suite_expr), \
__FILE__, \
__LINE__, \
#test_name, \
{__VA_ARGS__}, \
(disabled_flag), \
(skip_msg)}; \
} \
static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)()
#define VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, test_name, \
disabled_flag, skip_msg, uid) \
static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \
fixture_type&); \
namespace \
{ \
[[maybe_unused]] const ::Void::Testing::Detail::NativeFixtureRegistrar< \
fixture_type> \
VOID_TESTING_DETAIL_CAT(_void_native_fx_reg_, uid){ \
&VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid), \
#fixture_type, \
__FILE__, \
__LINE__, \
#test_name, \
{}, \
(disabled_flag), \
(skip_msg)}; \
} \
static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \
[[maybe_unused]] fixture_type& fixture)
/// Declare a self-registering test case with zero CMake scanner dependency.
/// Symbols are internal-linkage and counter-disambiguated so files sharing the
/// same basename in different subdirectories link cleanly together.
#define VOID_TEST(suite, name) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID)
/// Same as VOID_TEST, taking tags (string literals) after `name`.
#define VOID_TEST_TAGGED(suite, name, ...) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID, __VA_ARGS__)
/// Declare a skipped/disabled self-registering test case.
#define VOID_TEST_DISABLED(suite, name, reason) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, true, (reason), \
VOID_TESTING_DETAIL_NEXT_ID)
/// Declare a self-registering fixture test. The fixture instance is bound as
/// `fixture` inside the test body, with optional setup()/teardown() hooks.
#define VOID_TEST_FIXTURE(fixture_type, name) \
VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID)
#define VOID_TEST_FIXTURE_DISABLED(fixture_type, name, reason) \
VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, true, (reason), \
VOID_TESTING_DETAIL_NEXT_ID)
+94 -23
View File
@@ -438,6 +438,54 @@ namespace Void::Semver
using Clause = std::vector<Comparator>; using Clause = std::vector<Comparator>;
std::vector<Clause> m_alternatives; std::vector<Clause> m_alternatives;
struct PartialVersion {
Version version{};
int components{0};
};
[[nodiscard]] static std::optional<PartialVersion>
parse_partial(std::string_view token)
{
if (token.empty()) {
return std::nullopt;
}
if (token.find('-') != std::string_view::npos ||
token.find('+') != std::string_view::npos) {
const auto full = parse_strict(token);
if (!full) {
return std::nullopt;
}
return PartialVersion{*full, 3};
}
const auto first_dot = token.find('.');
if (first_dot == std::string_view::npos) {
unsigned major = 0;
if (!Detail::parse_component(token, major)) {
return std::nullopt;
}
return PartialVersion{
Version{.major = major, .minor = 0, .patch = 0}, 1};
}
const auto second_dot = token.find('.', first_dot + 1);
if (second_dot == std::string_view::npos) {
unsigned major = 0;
unsigned minor = 0;
if (!Detail::parse_component(token.substr(0, first_dot),
major) ||
!Detail::parse_component(token.substr(first_dot + 1),
minor)) {
return std::nullopt;
}
return PartialVersion{
Version{.major = major, .minor = minor, .patch = 0}, 2};
}
const auto full = parse_strict(token);
if (!full) {
return std::nullopt;
}
return PartialVersion{*full, 3};
}
[[nodiscard]] static bool append_token(Clause& clause, [[nodiscard]] static bool append_token(Clause& clause,
std::string_view token) std::string_view token)
{ {
@@ -447,53 +495,76 @@ namespace Void::Semver
if (token.starts_with('^') || token.starts_with('~')) { if (token.starts_with('^') || token.starts_with('~')) {
const char kind = token.front(); const char kind = token.front();
token.remove_prefix(1); token.remove_prefix(1);
const auto lower = parse_strict(token); const auto partial = parse_partial(token);
if (!lower) { if (!partial) {
return false; return false;
} }
const Version& lower = partial->version;
Version upper; Version upper;
if (kind == '~') { if (kind == '~') {
if (lower->minor == if (partial->components == 1) {
if (lower.major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else {
if (lower.minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major,
.minor = lower.minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
}
} else if (partial->components == 1) {
if (lower.major ==
std::numeric_limits<unsigned>::max()) { std::numeric_limits<unsigned>::max()) {
return false; return false;
} }
upper = Version{.major = lower->major, upper = Version{.major = lower.major + 1,
.minor = lower->minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->major > 0) {
if (lower->major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major + 1,
.minor = 0, .minor = 0,
.patch = 0, .patch = 0,
.pre_release = {}, .pre_release = {},
.build = {}}; .build = {}};
} else if (lower->minor > 0) { } else if (lower.major > 0) {
if (lower->minor == if (lower.major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower.minor > 0) {
if (lower.minor ==
std::numeric_limits<unsigned>::max()) { std::numeric_limits<unsigned>::max()) {
return false; return false;
} }
upper = Version{.major = 0, upper = Version{.major = 0,
.minor = lower->minor + 1, .minor = lower.minor + 1,
.patch = 0, .patch = 0,
.pre_release = {}, .pre_release = {},
.build = {}}; .build = {}};
} else { } else {
if (lower->patch == if (lower.patch ==
std::numeric_limits<unsigned>::max()) { std::numeric_limits<unsigned>::max()) {
return false; return false;
} }
upper = Version{.major = 0, upper = Version{.major = 0,
.minor = 0, .minor = 0,
.patch = lower->patch + 1, .patch = lower.patch + 1,
.pre_release = {}, .pre_release = {},
.build = {}}; .build = {}};
} }
clause.push_back({Operation::GreaterEqual, *lower}); clause.push_back({Operation::GreaterEqual, lower});
clause.push_back({Operation::Less, std::move(upper)}); clause.push_back({Operation::Less, std::move(upper)});
return true; return true;
} }
@@ -518,11 +589,11 @@ namespace Void::Semver
} else if (token.starts_with('=')) { } else if (token.starts_with('=')) {
token.remove_prefix(1); token.remove_prefix(1);
} }
const auto version = parse_strict(token); const auto partial = parse_partial(token);
if (!version) { if (!partial) {
return false; return false;
} }
clause.push_back({operation, *version}); clause.push_back({operation, partial->version});
return true; return true;
} }
+107
View File
@@ -4,6 +4,7 @@
#include <Void/Functional/Error.hpp> #include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp> #include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp> #include <Void/Text/Semver.hpp>
#include <Void/Update/Types.hpp>
#include <array> #include <array>
#include <chrono> #include <chrono>
@@ -68,6 +69,8 @@ namespace Void::Update
std::chrono::system_clock::time_point now{ std::chrono::system_clock::time_point now{
std::chrono::system_clock::now()}; std::chrono::system_clock::now()};
bool requireUnexpired{true}; bool requireUnexpired{true};
SchemaParsePolicy parsePolicy{SchemaParsePolicy::LegacyGeneralJson};
std::size_t maxJsonDepth{64};
}; };
struct VerifiedFeed { struct VerifiedFeed {
@@ -193,4 +196,108 @@ namespace Void::Update
/// Select the greatest compatible version, independent of feed order. /// Select the greatest compatible version, independent of feed order.
[[nodiscard]] std::optional<Release> [[nodiscard]] std::optional<Release>
selectRelease(const Feed& feed, const SelectionRequest& request); selectRelease(const Feed& feed, const SelectionRequest& request);
/// Non-forgeable signature-verified release selection retaining the exact
/// verified envelope bytes, signer key ID, policy decision, and selected
/// release/component metadata. Can only be constructed by verified factory
/// functions.
class VerifiedSelection
{
public:
VerifiedSelection(const VerifiedSelection&) = default;
VerifiedSelection(VerifiedSelection&&) noexcept = default;
VerifiedSelection& operator=(const VerifiedSelection&) = default;
VerifiedSelection& operator=(VerifiedSelection&&) noexcept = default;
[[nodiscard]] const std::string&
signed_envelope_bytes() const noexcept
{
return m_signed_envelope;
}
[[nodiscard]] const std::string&
signed_payload_bytes() const noexcept
{
return m_signed_payload;
}
[[nodiscard]] const std::string& signer_key_id() const noexcept
{
return m_signer_key_id;
}
[[nodiscard]] const std::string& feed_id() const noexcept
{
return m_feed_id;
}
[[nodiscard]] std::uint64_t sequence() const noexcept
{
return m_sequence;
}
[[nodiscard]] std::chrono::system_clock::time_point
expires_at() const noexcept
{
return m_expires_at;
}
[[nodiscard]] SchemaParsePolicy parse_policy() const noexcept
{
return m_parse_policy;
}
[[nodiscard]] const ReleaseIdentity& release() const noexcept
{
return m_release;
}
[[nodiscard]] const std::map<std::string, ComponentRelease>&
component_releases() const noexcept
{
return m_components;
}
private:
VerifiedSelection() = default;
std::string m_signed_envelope{};
std::string m_signed_payload{};
std::string m_signer_key_id{};
std::string m_feed_id{};
std::uint64_t m_sequence{0};
std::chrono::system_clock::time_point m_expires_at{};
SchemaParsePolicy m_parse_policy{
SchemaParsePolicy::LegacyGeneralJson};
ReleaseIdentity m_release{};
std::map<std::string, ComponentRelease> m_components{};
friend Void::Result::Result<VerifiedSelection>
verify_and_select_release(std::string_view envelopeJson,
const Keyring& keys,
const SelectionRequest& request,
const VerificationPolicy& policy);
friend Void::Result::Result<VerifiedSelection>
verify_and_select_component_set(
std::string_view catalogEnvelopeJson,
const std::map<std::string, std::string>&
releaseEnvelopeJsons,
const Keyring& keys, std::string_view primaryComponentId,
const VerificationPolicy& policy);
};
/// Verify an aggregate feed envelope (verify-before-parse), validate
/// policy, and produce a non-forgeable VerifiedSelection for the best
/// compatible release.
[[nodiscard]] Void::Result::Result<VerifiedSelection>
verify_and_select_release(std::string_view envelopeJson,
const Keyring& keys,
const SelectionRequest& request,
const VerificationPolicy& policy = {});
/// Verify a signed component catalog envelope and signed per-component
/// release envelopes, validate dependency closure and transaction limits
/// (<= 32 components, <= 256 dependency edges), and return a non-forgeable
/// VerifiedSelection.
[[nodiscard]] Void::Result::Result<VerifiedSelection>
verify_and_select_component_set(
std::string_view catalogEnvelopeJson,
const std::map<std::string, std::string>& releaseEnvelopeJsons,
const Keyring& keys, std::string_view primaryComponentId,
const VerificationPolicy& policy = {});
} // namespace Void::Update } // namespace Void::Update
+228
View File
@@ -0,0 +1,228 @@
#pragma once
#include <Void/Archive/Archive.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Update/Feed.hpp>
#include <Void/Update/Types.hpp>
#include <Void/Update/VersionStore.hpp>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Update
{
/// Durable high-water sequence floor per (feed_id, channel) persisted via
/// atomic file replacement + directory sync. Monotonic across restarts, key
/// rotations, and civil-clock rollbacks; corrupt floor files fail with
/// RecoveryRequired instead of resetting to zero.
class ReplayFloorStore
{
public:
explicit ReplayFloorStore(std::filesystem::path file_path);
[[nodiscard]] Void::Result::Result<void> load();
[[nodiscard]] std::optional<std::uint64_t>
floor(std::string_view feed_id,
std::string_view channel) const;
/// Validate `sequence >= stored_floor` (or strictly `>` when
/// `require_strictly_greater` is true) and durably persist the new
/// high-water mark before returning.
[[nodiscard]] Void::Result::Result<void>
advance(std::string_view feed_id, std::string_view channel,
std::uint64_t sequence,
bool require_strictly_greater = false);
private:
std::filesystem::path m_path{};
mutable std::mutex m_mu{};
std::map<std::string, std::uint64_t, std::less<>> m_floors{};
bool m_loaded{false};
};
/// Explicit trust-root store supporting application bootstrap,
/// authenticated old-trust key rotation, operator-approved rotation, and
/// key revocation without rewriting historical signed bytes.
class TrustStore
{
public:
[[nodiscard]] static std::string
rotation_statement(std::string_view new_key_id,
const Ed25519PublicKey& new_public_key);
[[nodiscard]] Void::Result::Result<void> bootstrap(Keyring keys);
/// Rotate in `new_key_id` using an Ed25519 signature produced by an
/// active trusted key (`authorizing_key_id`) over
/// `rotation_statement(new_key_id, new_public_key)`.
[[nodiscard]] Void::Result::Result<void>
rotate_key_authenticated(
std::string new_key_id,
const Ed25519PublicKey& new_public_key,
std::span<const std::byte> signature,
std::string_view authorizing_key_id);
[[nodiscard]] Void::Result::Result<void>
rotate_key_operator(std::string new_key_id,
const Ed25519PublicKey& new_public_key);
[[nodiscard]] Void::Result::Result<void>
revoke_key(std::string_view key_id);
[[nodiscard]] Keyring snapshot() const;
[[nodiscard]] bool is_revoked(std::string_view key_id) const;
private:
mutable std::mutex m_mu{};
Keyring m_active{};
std::set<std::string, std::less<>> m_revoked{};
};
struct DownloadRequest {
std::string url{};
std::string expected_sha256{};
std::uint64_t expected_size{0};
std::uint64_t max_bytes{0};
std::optional<std::string> resume_validator{};
std::uint64_t resume_offset{0};
std::stop_token stop{};
};
struct DownloadMetadata {
std::string validator{};
bool resumed{false};
};
/// Abstract bounded artifact download transport. Concrete Net/HTTP
/// transports implement this interface without coupling Update to Net.
class ArtifactTransport
{
public:
virtual ~ArtifactTransport() = default;
[[nodiscard]] virtual Void::Result::Result<DownloadMetadata>
download(
const DownloadRequest& request,
const std::function<
Void::Result::Result<void>(std::span<const std::byte>)>&
on_chunk) = 0;
};
/// Offline local-file transport for deterministic update workflow and
/// installed-consumer testing.
class LocalFileArtifactTransport final : public ArtifactTransport
{
public:
void map_url(std::string url, std::filesystem::path file_path,
std::string validator = "v1");
void set_fail_next(bool fail) noexcept;
void set_truncate_bytes(std::optional<std::size_t> bytes) noexcept;
[[nodiscard]] Void::Result::Result<DownloadMetadata> download(
const DownloadRequest& request,
const std::function<
Void::Result::Result<void>(std::span<const std::byte>)>&
on_chunk) override;
private:
struct Entry {
std::filesystem::path path{};
std::string validator{};
};
mutable std::mutex m_mu{};
std::map<std::string, Entry, std::less<>> m_entries{};
bool m_fail_next{false};
std::optional<std::size_t> m_truncate_bytes{};
};
struct LifecycleHooks {
/// Required when ActivationMode::ExternalLifecycle is selected.
std::function<Void::Result::Result<void>(
const Semver::Version&, const std::filesystem::path&)>
activate_external{};
/// Cooperative health probe executed outside coordinator locks.
/// Defaults to immediately healthy if unset.
std::function<Void::Result::Result<bool>(
const Semver::Version&, const std::filesystem::path&)>
health_probe{};
/// Invoked before rollback on readiness failure to stop/join the
/// candidate cleanly.
std::function<void(const Semver::Version&)> stop_candidate{};
/// Returns currently pinned live generations (e.g. loaded plugins)
/// that pruning must not delete.
std::function<std::vector<Semver::Version>()> live_pinned_versions{};
/// Owning progress event snapshot invoked outside coordinator locks.
std::function<void(const InstallReceipt&)> on_progress{};
/// Optional post-commit cleanup hook (also usable to inject cleanup
/// failures in tests to verify CleanupPending without rollback).
std::function<Void::Result::Result<void>()>
post_commit_cleanup_hook{};
};
/// Serialized per-store installation orchestrator combining verified
/// selections, monotonic replay floors, exact-digest streaming downloads,
/// Archive atomic staging, VersionStore single-commit activation,
/// checksummed operation journaling, and pin-aware bounded pruning.
class InstallCoordinator
{
public:
InstallCoordinator(VersionStore& store,
ReplayFloorStore& floor_store,
std::shared_ptr<ArtifactTransport> transport,
LifecycleHooks hooks = {});
InstallCoordinator(const InstallCoordinator&) = delete;
InstallCoordinator& operator=(const InstallCoordinator&) = delete;
[[nodiscard]] Void::Result::Result<InstallReceipt>
install(const VerifiedSelection& selection,
const InstallOptions& options = {});
/// Idempotent recovery pass inspecting both the checksummed
/// operation journal and VersionStore's durable activation/health
/// evidence. Corrupt or unknown journal records halt with
/// RecoveryRequired without discarding evidence.
[[nodiscard]] Void::Result::Result<InstallReceipt> reconcile();
/// Retry post-commit cleanup/pruning after a CleanupPending
/// outcome. Never rolls back a committed version.
[[nodiscard]] Void::Result::Result<InstallReceipt>
retry_cleanup(const InstallOptions& options = {});
void shutdown() noexcept;
[[nodiscard]] bool is_shutdown() const noexcept;
[[nodiscard]] std::filesystem::path
operation_journal_path() const;
private:
VersionStore& m_store;
ReplayFloorStore& m_floor_store;
std::shared_ptr<ArtifactTransport> m_transport;
LifecycleHooks m_hooks{};
mutable std::mutex m_state_mu{};
bool m_active{false};
bool m_shutdown{false};
};
} // namespace Void::Update
+209
View File
@@ -0,0 +1,209 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <stop_token>
#include <string>
#include <system_error>
#include <utility>
namespace Void::Update
{
enum class UpdateErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
signature_failed = 2,
untrusted_key = 3,
replay_rejected = 4,
expired = 5,
schema_error = 6,
mirror_mismatch = 7,
digest_mismatch = 8,
size_mismatch = 9,
limit_exceeded = 10,
transport_error = 11,
staging_error = 12,
activation_failed = 13,
health_check_failed = 14,
recovery_required = 15,
cleanup_pending = 16,
unknown_outcome = 17,
conflict = 18,
cancelled = 19,
timeout = 20,
closed = 21,
io_error = 22
};
[[nodiscard]] inline Void::Result::Error
make_update_error(UpdateErrorCode 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 UpdateErrorCode::none:
kind = ErrorKind::internal;
break;
case UpdateErrorCode::invalid_argument:
case UpdateErrorCode::schema_error:
kind = ErrorKind::invalid_argument;
break;
case UpdateErrorCode::signature_failed:
case UpdateErrorCode::untrusted_key:
case UpdateErrorCode::mirror_mismatch:
case UpdateErrorCode::digest_mismatch:
case UpdateErrorCode::size_mismatch:
case UpdateErrorCode::recovery_required:
kind = ErrorKind::corrupt;
break;
case UpdateErrorCode::replay_rejected:
case UpdateErrorCode::expired:
case UpdateErrorCode::conflict:
case UpdateErrorCode::cleanup_pending:
kind = ErrorKind::conflict;
break;
case UpdateErrorCode::limit_exceeded:
kind = ErrorKind::exhausted;
break;
case UpdateErrorCode::transport_error:
case UpdateErrorCode::staging_error:
case UpdateErrorCode::io_error:
kind = ErrorKind::io;
break;
case UpdateErrorCode::activation_failed:
case UpdateErrorCode::health_check_failed:
case UpdateErrorCode::unknown_outcome:
kind = ErrorKind::internal;
break;
case UpdateErrorCode::cancelled:
case UpdateErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case UpdateErrorCode::timeout:
kind = ErrorKind::timeout;
break;
}
const ErrorCode domain_code{Void::Result::kUpdateErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
/// Explicit JSON parsing policy for signed payloads (C-07).
/// LegacyGeneralJson preserves existing accepted documents;
/// StrictJsonProfile additionally enforces Void::Json::Strict rules
/// (no duplicate keys, integer-only strict numbers, bounded nesting depth).
enum class SchemaParsePolicy : std::uint8_t {
LegacyGeneralJson = 0,
StrictJsonProfile = 1
};
enum class InstallState : std::uint8_t {
Verified = 0,
Downloading,
Staged,
Published,
Activated,
HealthyCommitted,
CleanupPending,
RolledBack,
RecoveryRequired
};
enum class ActivationMode : std::uint8_t {
InternalVersionStore = 0,
ExternalLifecycle = 1
};
struct UpdateLimits {
static constexpr std::size_t kDefaultMaxActiveInstalls = 1;
static constexpr std::size_t kDefaultMaxQueuedSelections = 8;
static constexpr std::size_t kDefaultMaxConcurrentDownloads = 2;
static constexpr std::uint64_t kDefaultMaxArtifactBytes =
512ULL * 1024 * 1024;
static constexpr std::uint64_t kDefaultStagingQuotaBytes =
2ULL * 1024 * 1024 * 1024;
static constexpr std::size_t kDefaultMaxComponentsPerTransaction =
32;
static constexpr std::size_t kDefaultMaxDependencyEdges = 256;
static constexpr std::chrono::milliseconds kDefaultInstallDeadline{
std::chrono::minutes{10}};
static constexpr std::chrono::milliseconds kDefaultReadinessTimeout{
std::chrono::seconds{30}};
static constexpr std::chrono::milliseconds
kDefaultHealthProbeInterval{std::chrono::seconds{1}};
static constexpr std::size_t kDefaultConsecutiveHealthyRequired = 3;
static constexpr std::size_t kDefaultRetainedPreviousVersions = 2;
static constexpr std::size_t kDefaultPruneBatchLimit = 16;
};
struct ReleaseIdentity {
std::string component{};
std::string artifact_id{};
std::string channel{};
Semver::Version version{};
std::uint64_t sequence{0};
std::string sha256{};
std::uint64_t size{0};
std::string url{};
std::string package_type{};
};
struct InstallReceipt {
std::string install_id{};
InstallState state{InstallState::Verified};
ReleaseIdentity release{};
std::string signer_key_id{};
std::string diagnostic{};
bool cleanup_retryable{false};
};
struct InstallOptions {
ActivationMode activation_mode{
ActivationMode::InternalVersionStore};
std::size_t max_active_installs{
UpdateLimits::kDefaultMaxActiveInstalls};
std::size_t max_queued_selections{
UpdateLimits::kDefaultMaxQueuedSelections};
std::size_t max_concurrent_downloads{
UpdateLimits::kDefaultMaxConcurrentDownloads};
std::uint64_t max_artifact_bytes{
UpdateLimits::kDefaultMaxArtifactBytes};
std::uint64_t staging_quota_bytes{
UpdateLimits::kDefaultStagingQuotaBytes};
std::size_t max_components{
UpdateLimits::kDefaultMaxComponentsPerTransaction};
std::size_t max_dependency_edges{
UpdateLimits::kDefaultMaxDependencyEdges};
std::chrono::milliseconds install_deadline{
UpdateLimits::kDefaultInstallDeadline};
std::chrono::milliseconds readiness_timeout{
UpdateLimits::kDefaultReadinessTimeout};
std::chrono::milliseconds health_probe_interval{
UpdateLimits::kDefaultHealthProbeInterval};
std::size_t consecutive_healthy_required{
UpdateLimits::kDefaultConsecutiveHealthyRequired};
std::size_t retained_previous_versions{
UpdateLimits::kDefaultRetainedPreviousVersions};
std::size_t prune_batch_limit{
UpdateLimits::kDefaultPruneBatchLimit};
bool allow_resumable_download{false};
std::optional<std::filesystem::path> isolated_archive_worker{};
std::stop_token stop{};
const Void::Time::MonotonicClock* monotonic_clock{nullptr};
const Void::Time::CivilClock* civil_clock{nullptr};
};
} // namespace Void::Update
+2
View File
@@ -1,4 +1,6 @@
#pragma once #pragma once
#include <Void/Update/Feed.hpp> #include <Void/Update/Feed.hpp>
#include <Void/Update/Install.hpp>
#include <Void/Update/Types.hpp>
#include <Void/Update/VersionStore.hpp> #include <Void/Update/VersionStore.hpp>
+16
View File
@@ -8,10 +8,16 @@
#include <cstdint> #include <cstdint>
#include <filesystem> #include <filesystem>
#include <optional> #include <optional>
#include <span>
#include <vector> #include <vector>
namespace Void::Update namespace Void::Update
{ {
struct PruneReport {
std::vector<Semver::Version> removed{};
std::vector<Semver::Version> skipped_due_to_pins{};
bool batch_limit_reached{false};
};
struct PendingActivation { struct PendingActivation {
std::optional<Semver::Version> previousVersion; std::optional<Semver::Version> previousVersion;
Semver::Version candidateVersion; Semver::Version candidateVersion;
@@ -86,6 +92,16 @@ namespace Void::Update
Void::Result::Result<std::vector<Semver::Version>> Void::Result::Result<std::vector<Semver::Version>>
prune(std::size_t retainedPreviousVersions); prune(std::size_t retainedPreviousVersions);
/// Pin-aware bounded pruning pass. Never deletes the active
/// version, pending activation candidate/previous, top
/// `retainedPreviousVersions` healthy versions, or any version in
/// `pinnedVersions`. Reports pin-blocked candidates and honors
/// `batchLimit` (default 16 publications per pass).
[[nodiscard]] Void::Result::Result<PruneReport>
pruneWithPins(std::size_t retainedPreviousVersions,
std::span<const Semver::Version> pinnedVersions,
std::size_t batchLimit = 16);
[[nodiscard]] Void::Result::Result<std::optional<Semver::Version>> [[nodiscard]] Void::Result::Result<std::optional<Semver::Version>>
currentVersion() const; currentVersion() const;
[[nodiscard]] Void::Result::Result<std::optional<PendingActivation>> [[nodiscard]] Void::Result::Result<std::optional<PendingActivation>>
+148 -30
View File
@@ -1,10 +1,13 @@
#include <Void/Archive/Archive.hpp> #include <Void/Archive/Archive.hpp>
#include "BuiltinTar.hpp"
#include <array> #include <array>
#include <atomic> #include <atomic>
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
#include <format> #include <format>
#include <limits>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <set> #include <set>
@@ -13,8 +16,10 @@
#include <system_error> #include <system_error>
#include <utility> #include <utility>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h> #include <archive.h>
#include <archive_entry.h> #include <archive_entry.h>
#endif
#ifndef _WIN32 #ifndef _WIN32
#include <fcntl.h> #include <fcntl.h>
@@ -28,6 +33,7 @@ namespace Void::Archive
{ {
namespace namespace
{ {
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using ArchiveHandle = using ArchiveHandle =
std::unique_ptr<archive, decltype(&archive_read_free)>; std::unique_ptr<archive, decltype(&archive_read_free)>;
@@ -39,6 +45,7 @@ namespace Void::Archive
"Archive::extract: {}: {}", operation, "Archive::extract: {}: {}", operation,
message == nullptr ? "unknown archive error" : message)}; message == nullptr ? "unknown archive error" : message)};
} }
#endif
[[nodiscard]] std::optional<std::filesystem::path> [[nodiscard]] std::optional<std::filesystem::path>
safe_relative_path(std::string_view rawPath, bool directory) safe_relative_path(std::string_view rawPath, bool directory)
@@ -225,12 +232,14 @@ namespace Void::Archive
return {}; return {};
} }
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t> [[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, int rootDescriptor, extract_regular_stream(int rootDescriptor,
const std::filesystem::path &relative, const std::filesystem::path &relative,
const std::filesystem::path &displayRoot, const std::filesystem::path &displayRoot,
const ExtractionOptions &options, const ExtractionOptions &options,
std::uint64_t alreadyExtracted, bool executable) std::uint64_t alreadyExtracted,
bool executable, ReadFn &&read_fn)
{ {
auto openedParent = open_parent_directory( auto openedParent = open_parent_directory(
rootDescriptor, relative.parent_path(), displayRoot); rootDescriptor, relative.parent_path(), displayRoot);
@@ -286,15 +295,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{}; std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0; std::uint64_t fileBytes = 0;
for (;;) { for (;;) {
const auto count = auto chunk = read_fn(std::span{buffer});
archive_read_data(reader, buffer.data(), buffer.size()); if (!chunk.has_value()) {
if (count == 0) { return fail(chunk.error().message());
}
if (*chunk == 0) {
break; break;
} }
if (count < 0) { const auto amount = static_cast<std::uint64_t>(*chunk);
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
if (amount > options.maxFileBytes - fileBytes || if (amount > options.maxFileBytes - fileBytes ||
amount > amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) { options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -303,11 +311,11 @@ namespace Void::Archive
} }
std::size_t written = 0; std::size_t written = 0;
while (written < static_cast<std::size_t>(count)) { while (written < *chunk) {
const auto result = ::write( const auto result = ::write(
descriptor.get(), descriptor.get(),
reinterpret_cast<const char *>(buffer.data()) + written, reinterpret_cast<const char *>(buffer.data()) + written,
static_cast<std::size_t>(count) - written); *chunk - written);
if (result < 0 && errno == EINTR) { if (result < 0 && errno == EINTR) {
continue; continue;
} }
@@ -448,10 +456,12 @@ namespace Void::Archive
return {}; return {};
} }
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t> [[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, const std::filesystem::path &path, extract_regular_stream(const std::filesystem::path &path,
const ExtractionOptions &options, const ExtractionOptions &options,
std::uint64_t alreadyExtracted) std::uint64_t alreadyExtracted,
ReadFn &&read_fn)
{ {
std::error_code error; std::error_code error;
const auto status = std::filesystem::symlink_status(path, error); const auto status = std::filesystem::symlink_status(path, error);
@@ -486,15 +496,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{}; std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0; std::uint64_t fileBytes = 0;
for (;;) { for (;;) {
const auto count = auto chunk = read_fn(std::span{buffer});
archive_read_data(reader, buffer.data(), buffer.size()); if (!chunk.has_value()) {
if (count == 0) { return fail(chunk.error().message());
}
if (*chunk == 0) {
break; break;
} }
if (count < 0) { const auto amount = static_cast<std::uint64_t>(*chunk);
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
if (amount > options.maxFileBytes - fileBytes || if (amount > options.maxFileBytes - fileBytes ||
amount > amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) { options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -502,7 +511,7 @@ namespace Void::Archive
"Archive::extract: extracted size exceeds policy"); "Archive::extract: extracted size exceeds policy");
} }
output.write(reinterpret_cast<const char *>(buffer.data()), output.write(reinterpret_cast<const char *>(buffer.data()),
count); static_cast<std::streamsize>(*chunk));
if (!output) { if (!output) {
return fail("Archive::extract: write failed"); return fail("Archive::extract: write failed");
} }
@@ -544,11 +553,13 @@ namespace Void::Archive
} }
#endif #endif
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
ArchiveHandle reader{archive_read_new(), &archive_read_free}; ArchiveHandle reader{archive_read_new(), &archive_read_free};
if (!reader) { if (!reader) {
return Void::Result::fail( return Void::Result::fail(
"Archive::extract: cannot allocate archive reader"); "Archive::extract: cannot allocate archive reader");
} }
archive_read_support_filter_gzip(reader.get());
archive_read_support_filter_zstd(reader.get()); archive_read_support_filter_zstd(reader.get());
archive_read_support_filter_none(reader.get()); archive_read_support_filter_none(reader.get());
archive_read_support_format_tar(reader.get()); archive_read_support_format_tar(reader.get());
@@ -633,14 +644,23 @@ namespace Void::Archive
return Void::Result::fail( return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy"); "Archive::extract: declared entry size exceeds policy");
} }
auto read_libarchive_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
const auto count =
archive_read_data(reader.get(), dst.data(), dst.size());
if (count < 0) {
return std::unexpected{archive_error(reader.get(), "read entry")};
}
return static_cast<std::size_t>(count);
};
#ifndef _WIN32 #ifndef _WIN32
const bool executable = (archive_entry_perm(entry) & 0111) != 0; const bool executable = (archive_entry_perm(entry) & 0111) != 0;
auto extracted = auto extracted = extract_regular_stream(
extract_regular(reader.get(), root->get(), *relative, root->get(), *relative, destination, options, result.bytes,
destination, options, result.bytes, executable); executable, read_libarchive_chunk);
#else #else
auto extracted = auto extracted = extract_regular_stream(
extract_regular(reader.get(), output, options, result.bytes); output, options, result.bytes, read_libarchive_chunk);
#endif #endif
if (!extracted) { if (!extracted) {
return std::unexpected{extracted.error()}; return std::unexpected{extracted.error()};
@@ -648,5 +668,103 @@ namespace Void::Archive
result.bytes += *extracted; result.bytes += *extracted;
} }
return result; return result;
#else
auto source = FileByteSource::open(archivePath);
if (!source.has_value()) {
return std::unexpected{std::move(source.error())};
}
ReadLimits limits;
limits.max_entries = options.maxEntries;
limits.max_file_bytes = options.maxFileBytes;
limits.max_total_bytes = options.maxTotalBytes;
limits.max_compressed_bytes = std::numeric_limits<std::uint64_t>::max();
Detail::BuiltinTarStream stream{
*source, limits, {}, std::nullopt,
Void::Time::SystemMonotonicClock::instance()};
if (auto opened = stream.open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
ExtractionResult result;
std::set<std::filesystem::path> seen;
for (;;) {
auto next = stream.next_entry();
if (!next.has_value()) {
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
break;
}
if (++result.entries > options.maxEntries) {
return Void::Result::fail(
"Archive::extract: entry count exceeds policy");
}
const auto &entry = **next;
if (entry.type == EntryType::Hardlink ||
entry.type == EntryType::Symlink || !entry.linkname.empty()) {
return Void::Result::fail(
"Archive::extract: links are not allowed");
}
if (entry.type != EntryType::Directory &&
entry.type != EntryType::RegularFile) {
return Void::Result::fail(
"Archive::extract: special files are not allowed");
}
const bool is_dir = (entry.type == EntryType::Directory);
auto relative = safe_relative_path(entry.path, is_dir);
if (!relative || !seen.insert(*relative).second) {
return Void::Result::fail(std::format(
"Archive::extract: unsafe or duplicate path '{}'",
entry.path));
}
#ifdef _WIN32
if (auto parents = safe_parents(root, relative->parent_path());
!parents) {
return std::unexpected{parents.error()};
}
const auto output = root / *relative;
#endif
if (is_dir) {
#ifndef _WIN32
auto created =
create_directory_entry(root->get(), *relative, destination,
options.overwriteExisting);
#else
auto created =
create_directory_entry(output, options.overwriteExisting);
#endif
if (!created) {
return std::unexpected{created.error()};
}
continue;
}
if (entry.declared_size > options.maxFileBytes ||
entry.declared_size > options.maxTotalBytes - result.bytes) {
return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy");
}
auto read_builtin_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
return stream.read_entry_data(dst);
};
#ifndef _WIN32
const bool executable = (entry.mode & 0111U) != 0U;
auto extracted = extract_regular_stream(
root->get(), *relative, destination, options, result.bytes,
executable, read_builtin_chunk);
#else
auto extracted = extract_regular_stream(
output, options, result.bytes, read_builtin_chunk);
#endif
if (!extracted) {
return std::unexpected{extracted.error()};
}
result.bytes += *extracted;
}
return result;
#endif
} }
} // namespace Void::Archive } // namespace Void::Archive
+867
View File
@@ -0,0 +1,867 @@
#include "BuiltinTar.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <cstring>
#include <format>
#include <string_view>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::Archive::Detail
{
namespace
{
constexpr std::size_t kTarBlockSize = 512;
[[nodiscard]] bool is_zero_block(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
for (const std::byte b : block) {
if (b != std::byte{0}) {
return false;
}
}
return true;
}
inline void write_octal(std::span<std::byte> field, std::uint64_t value) noexcept
{
if (field.size() < 2) {
return;
}
field.back() = std::byte{0};
std::size_t pos = field.size() - 1;
while (pos > 0) {
--pos;
field[pos] = static_cast<std::byte>('0' + (value & 7ULL));
value >>= 3ULL;
}
}
[[nodiscard]] Void::Result::Result<std::uint64_t>
parse_octal(std::span<const std::byte> field, const char* name)
{
const auto* p = reinterpret_cast<const unsigned char*>(field.data());
std::size_t n = field.size();
if (n > 0 && (p[0] & 0x80U) != 0U) {
// POSIX / GNU big-endian base-256 unsigned extension.
if ((p[0] & 0x40U) != 0U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: negative base-256 field '{}'",
name))};
}
std::uint64_t v = static_cast<std::uint64_t>(p[0] & 0x3FU);
for (std::size_t i = 1; i < n; ++i) {
if (v > (std::numeric_limits<std::uint64_t>::max() >> 8U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: overflowing field '{}'",
name))};
}
v = (v << 8U) | static_cast<std::uint64_t>(p[i]);
}
return v;
}
std::size_t i = 0;
while (i < n && (p[i] == ' ' || p[i] == '\0')) {
++i;
}
if (i == n) {
return std::uint64_t{0};
}
std::uint64_t out = 0;
bool saw_digit = false;
for (; i < n; ++i) {
if (p[i] == '\0' || p[i] == ' ') {
break;
}
if (p[i] < '0' || p[i] > '7') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: invalid octal character in '{}'",
name))};
}
if (out > (std::numeric_limits<std::uint64_t>::max() >> 3U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: octal overflow in '{}'", name))};
}
out = (out << 3U) | static_cast<std::uint64_t>(p[i] - '0');
saw_digit = true;
}
if (!saw_digit) {
return std::uint64_t{0};
}
return out;
}
[[nodiscard]] std::string_view
c_field(std::span<const std::byte> field) noexcept
{
const char* s = reinterpret_cast<const char*>(field.data());
std::size_t len = 0;
while (len < field.size() && s[len] != '\0') {
++len;
}
return {s, len};
}
[[nodiscard]] std::uint32_t
compute_checksum_unsigned(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::uint32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::uint32_t>(' ');
} else {
sum += static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(block[i]));
}
}
return sum;
}
[[nodiscard]] std::int32_t
compute_checksum_signed(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::int32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::int32_t>(' ');
} else {
sum += static_cast<std::int32_t>(
static_cast<signed char>(
std::to_integer<unsigned char>(block[i])));
}
}
return sum;
}
void build_ustar_header(std::array<std::byte, kTarBlockSize>& hdr,
std::string_view wire_name, char typeflag,
std::uint32_t mode, std::uint32_t uid,
std::uint32_t gid, std::uint64_t size,
std::uint64_t mtime) noexcept
{
hdr.fill(std::byte{0});
// Split into prefix (<=155) + name (<=100) only when needed and valid;
// callers handling paths >255 emit PAX 'x' before this header.
std::string_view prefix{};
std::string_view name = wire_name;
if (wire_name.size() > 100) {
const std::size_t min_split =
wire_name.size() > 100 ? wire_name.size() - 101 : 0;
const std::size_t max_split = std::min<std::size_t>(155, wire_name.size() - 1);
std::size_t chosen = std::string_view::npos;
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_name.size() && wire_name[pos] == '/') {
const std::string_view cand_prefix = wire_name.substr(0, pos);
const std::string_view cand_name = wire_name.substr(pos + 1);
if (!cand_prefix.empty() && cand_prefix.size() <= 155 &&
!cand_name.empty() && cand_name.size() <= 100) {
chosen = pos;
break;
}
}
if (pos == 0) {
break;
}
}
if (chosen != std::string_view::npos) {
prefix = wire_name.substr(0, chosen);
name = wire_name.substr(chosen + 1);
} else {
name = wire_name.substr(0, 100);
}
}
std::memcpy(hdr.data() + 0, name.data(), std::min<std::size_t>(name.size(), 100));
write_octal(std::span{hdr}.subspan(100, 8), mode & 07777U);
write_octal(std::span{hdr}.subspan(108, 8), uid);
write_octal(std::span{hdr}.subspan(116, 8), gid);
// Clamp size field to 11 octal digits when PAX overrides size.
const std::uint64_t ustar_size =
size <= 077777777777ULL ? size : 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), ustar_size);
write_octal(std::span{hdr}.subspan(136, 12), mtime);
std::fill(hdr.begin() + 148, hdr.begin() + 156, std::byte{' '});
hdr[156] = static_cast<std::byte>(typeflag);
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = std::byte{'0'};
hdr[264] = std::byte{'0'};
write_octal(std::span{hdr}.subspan(329, 8), 0);
write_octal(std::span{hdr}.subspan(337, 8), 0);
if (!prefix.empty()) {
std::memcpy(hdr.data() + 345, prefix.data(),
std::min<std::size_t>(prefix.size(), 155));
}
const std::uint32_t sum = compute_checksum_unsigned(hdr);
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = std::byte{' '};
}
[[nodiscard]] std::string
make_pax_record(std::string_view key, std::string_view value)
{
const std::size_t rest_len = 1U + key.size() + 1U + value.size() + 1U;
std::size_t total = rest_len + 1U;
for (;;) {
const std::string digits = std::to_string(total);
const std::size_t next = digits.size() + rest_len;
if (next == total) {
break;
}
total = next;
}
return std::format("{} {}={}\n", total, key, value);
}
[[nodiscard]] Void::Result::Result<void>
write_padding(ByteSink& sink, std::uint64_t written)
{
const std::size_t rem = static_cast<std::size_t>(written % kTarBlockSize);
if (rem == 0) {
return {};
}
std::array<std::byte, kTarBlockSize> zeros{};
return sink.write(std::span{zeros}.subspan(0, kTarBlockSize - rem));
}
[[nodiscard]] bool
can_fit_ustar_path(std::string_view wire_path) noexcept
{
if (wire_path.size() <= 100) {
return true;
}
if (wire_path.size() > 256) {
return false;
}
const std::size_t min_split = wire_path.size() - 101;
const std::size_t max_split = std::min<std::size_t>(155, wire_path.size() - 1);
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_path.size() && wire_path[pos] == '/') {
const std::size_t p_len = pos;
const std::size_t n_len = wire_path.size() - (pos + 1);
if (p_len >= 1 && p_len <= 155 && n_len >= 1 && n_len <= 100) {
return true;
}
}
if (pos == 0) {
break;
}
}
return false;
}
[[nodiscard]] Void::Result::Result<void>
parse_pax_records(std::string_view payload, std::string& path_out,
std::string& link_out,
std::optional<std::uint64_t>& size_out,
std::size_t max_path_bytes)
{
std::size_t pos = 0;
while (pos < payload.size()) {
const std::size_t sp = payload.find(' ', pos);
if (sp == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: malformed PAX record length")};
}
std::size_t rec_len = 0;
const auto lr = std::from_chars(payload.data() + pos,
payload.data() + sp, rec_len);
if (lr.ec != std::errc{} || lr.ptr != payload.data() + sp ||
rec_len == 0 || pos + rec_len > payload.size() ||
sp >= pos + rec_len) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX extended header record length")};
}
const std::string_view rec =
payload.substr(sp + 1, pos + rec_len - (sp + 1));
if (rec.empty() || rec.back() != '\n') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing trailing newline")};
}
const std::string_view kv = rec.substr(0, rec.size() - 1);
const std::size_t eq = kv.find('=');
if (eq == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing '='")};
}
const std::string_view key = kv.substr(0, eq);
const std::string_view val = kv.substr(eq + 1);
if (key == "path") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX path exceeds configured limit")};
}
path_out.assign(val);
} else if (key == "linkpath") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX linkpath exceeds configured limit")};
}
link_out.assign(val);
} else if (key == "size") {
std::uint64_t parsed_size = 0;
const auto sr = std::from_chars(
val.data(), val.data() + val.size(), parsed_size);
if (sr.ec != std::errc{} ||
sr.ptr != val.data() + val.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX size field")};
}
size_out = parsed_size;
}
pos += rec_len;
}
return {};
}
} // namespace
Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options)
{
const std::uint64_t mtime =
options.reproducible
? static_cast<std::uint64_t>(std::max<std::int64_t>(
0, options.canonical_mtime))
: static_cast<std::uint64_t>(std::max<std::int64_t>(
0,
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count()));
const std::uint32_t uid =
options.reproducible ? options.canonical_uid : 0U;
const std::uint32_t gid =
options.reproducible ? options.canonical_gid : 0U;
std::array<std::byte, kTarBlockSize> hdr{};
std::vector<std::byte> io_buf(options.limits.transfer_buffer_bytes);
for (const auto& item : items) {
if (options.stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::create_archive: cancelled")};
}
const std::string wire_path =
item.is_directory ? (item.path + "/") : item.path;
const bool need_pax_path = !can_fit_ustar_path(wire_path);
const bool need_pax_size = item.size > 077777777777ULL;
if (need_pax_path || need_pax_size) {
std::string pax;
if (need_pax_path) {
pax += make_pax_record("path", wire_path);
}
if (need_pax_size) {
pax += make_pax_record("size", std::to_string(item.size));
}
std::string pax_name = "PaxHeaders.0/";
const std::size_t suffix_take = std::min<std::size_t>(
100U - pax_name.size(), item.path.size());
pax_name.append(item.path.substr(0, suffix_take));
build_ustar_header(hdr, pax_name, 'x', 0644U, 0U, 0U,
pax.size(), 0ULL);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
const auto pax_bytes =
std::as_bytes(std::span{pax.data(), pax.size()});
if (auto w = sink.write(pax_bytes); !w.has_value()) {
return w;
}
if (auto p = write_padding(sink, pax.size()); !p.has_value()) {
return p;
}
}
build_ustar_header(hdr, wire_path, item.is_directory ? '5' : '0',
item.mode, uid, gid, item.size, mtime);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
if (!item.is_directory) {
if (item.source_fd >= 0) {
#ifndef _WIN32
std::uint64_t remaining = item.size;
while (remaining > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(remaining, io_buf.size()));
const ssize_t r =
::read(item.source_fd, io_buf.data(), want);
if (r < 0 && errno == EINTR) {
continue;
}
if (r <= 0) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::io_error,
"Archive::create_archive: source file shrunk "
"or read failed")};
}
if (auto w = sink.write(std::span<const std::byte>{
io_buf.data(), static_cast<std::size_t>(r)});
!w.has_value()) {
return w;
}
remaining -= static_cast<std::uint64_t>(r);
}
#endif
} else if (!item.inline_content.empty()) {
if (auto w = sink.write(item.inline_content);
!w.has_value()) {
return w;
}
}
if (auto p = write_padding(sink, item.size); !p.has_value()) {
return p;
}
}
}
// Standard two 512-byte zero EOF blocks.
std::array<std::byte, kTarBlockSize * 2> eof_blocks{};
return sink.write(eof_blocks);
}
BuiltinTarStream::BuiltinTarStream(
ByteSource& source, const ReadLimits& limits, std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock)
: m_source(&source), m_limits(limits), m_stop(std::move(stop)),
m_deadline(deadline), m_clock(&clock)
{
}
Void::Result::Result<void> BuiltinTarStream::check_stop_deadline() const
{
if (m_stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::Reader: operation cancelled")};
}
if (m_deadline.has_value() && m_clock->now() >= *m_deadline) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::timeout,
"Archive::Reader: deadline expired")};
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_exact_or_eof(std::span<std::byte> dst)
{
std::size_t filled = 0;
if (m_prefetch_off < m_prefetch.size()) {
const std::size_t take =
std::min(dst.size(), m_prefetch.size() - m_prefetch_off);
std::memcpy(dst.data(), m_prefetch.data() + m_prefetch_off, take);
m_prefetch_off += take;
filled += take;
if (m_prefetch_off == m_prefetch.size()) {
m_prefetch.clear();
m_prefetch_off = 0;
}
}
while (filled < dst.size()) {
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return std::unexpected{std::move(chk.error())};
}
const std::size_t want = dst.size() - filled;
auto r = m_source->read(dst.subspan(filled, want));
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
if (*r == 0) {
break;
}
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes - m_total_compressed) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: compressed input exceeds limit")};
}
m_total_compressed += n;
filled += *r;
}
return filled;
}
Void::Result::Result<void>
BuiltinTarStream::read_exact_required(std::span<std::byte> dst,
const char* context)
{
auto n = read_exact_or_eof(dst);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
if (*n != dst.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive::Reader: unexpected EOF while reading {}",
context))};
}
return {};
}
Void::Result::Result<void>
BuiltinTarStream::discard_bytes(std::uint64_t count,
const char* context)
{
std::array<std::byte, 4096> scratch{};
std::uint64_t rem = count;
while (rem > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(rem, scratch.size()));
if (auto r = read_exact_required(std::span{scratch}.subspan(0, want),
context);
!r.has_value()) {
return r;
}
rem -= want;
}
return {};
}
Void::Result::Result<void> BuiltinTarStream::open()
{
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return chk;
}
m_prefetch.resize(std::min<std::size_t>(512U,
m_limits.transfer_buffer_bytes));
auto r = m_source->read(m_prefetch);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
m_prefetch.resize(*r);
m_prefetch_off = 0;
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: input exceeds compressed limit")};
}
m_total_compressed = n;
if (*r == 0) {
m_reached_eof = true;
return {};
}
// Reject compressed streams cleanly when LibArchive is unavailable.
if (m_prefetch.size() >= 2 &&
m_prefetch[0] == std::byte{0x1F} &&
m_prefetch[1] == std::byte{0x8B}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: gzip archives require LibArchive backend")};
}
if (m_prefetch.size() >= 4 &&
m_prefetch[0] == std::byte{0x28} &&
m_prefetch[1] == std::byte{0xB5} &&
m_prefetch[2] == std::byte{0x2F} &&
m_prefetch[3] == std::byte{0xFD}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: zstd archives require LibArchive backend")};
}
return {};
}
Void::Result::Result<std::optional<BuiltinTarEntry>>
BuiltinTarStream::next_entry()
{
if (m_reached_eof) {
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (m_has_active_entry) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::conflict,
"Archive::Reader: active entry must be drained or skipped")};
}
std::string next_pax_path;
std::string next_pax_link;
std::optional<std::uint64_t> next_pax_size;
std::string global_pax_path;
std::string global_pax_link;
std::optional<std::uint64_t> global_pax_size;
std::string gnu_long_name;
std::string gnu_long_link;
std::array<std::byte, kTarBlockSize> hdr{};
for (;;) {
auto nread = read_exact_or_eof(hdr);
if (!nread.has_value()) {
return std::unexpected{std::move(nread.error())};
}
if (*nread == 0) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (*nread != kTarBlockSize) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: truncated tar header block")};
}
if (is_zero_block(hdr)) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
auto recorded_sum = parse_octal(std::span{hdr}.subspan(148, 8),
"chksum");
if (!recorded_sum.has_value()) {
return std::unexpected{std::move(recorded_sum.error())};
}
const std::uint32_t usum = compute_checksum_unsigned(hdr);
const std::int32_t ssum = compute_checksum_signed(hdr);
if (*recorded_sum != usum &&
static_cast<std::int64_t>(*recorded_sum) !=
static_cast<std::int64_t>(ssum)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: tar header checksum mismatch")};
}
auto parsed_mode =
parse_octal(std::span{hdr}.subspan(100, 8), "mode");
if (!parsed_mode.has_value()) {
return std::unexpected{std::move(parsed_mode.error())};
}
auto parsed_size =
parse_octal(std::span{hdr}.subspan(124, 12), "size");
if (!parsed_size.has_value()) {
return std::unexpected{std::move(parsed_size.error())};
}
const char typeflag = static_cast<char>(std::to_integer<unsigned char>(hdr[156]));
if (typeflag == 'x' || typeflag == 'g' || typeflag == 'L' ||
typeflag == 'K') {
if (*parsed_size > m_limits.max_metadata_bytes ||
*parsed_size >
m_limits.max_metadata_bytes - m_metadata_budget_used) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: tar extended header exceeds metadata "
"limit")};
}
m_metadata_budget_used += static_cast<std::size_t>(*parsed_size);
std::string payload(static_cast<std::size_t>(*parsed_size), '\0');
if (!payload.empty()) {
if (auto rr = read_exact_required(
std::as_writable_bytes(std::span{payload}),
"extended tar header");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
}
const std::size_t pad =
static_cast<std::size_t>((kTarBlockSize - (*parsed_size % kTarBlockSize)) % kTarBlockSize);
if (pad > 0) {
if (auto dr = discard_bytes(pad, "extended header padding");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (typeflag == 'x') {
if (auto pr = parse_pax_records(
payload, next_pax_path, next_pax_link,
next_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else if (typeflag == 'g') {
if (auto pr = parse_pax_records(
payload, global_pax_path, global_pax_link,
global_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else {
while (!payload.empty() && payload.back() == '\0') {
payload.pop_back();
}
if (payload.size() > m_limits.max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: GNU long name exceeds limit")};
}
if (typeflag == 'L') {
gnu_long_name = std::move(payload);
} else {
gnu_long_link = std::move(payload);
}
}
continue;
}
const std::string_view magic_view =
c_field(std::span{hdr}.subspan(257, 6));
std::string path;
if (!next_pax_path.empty()) {
path = std::move(next_pax_path);
} else if (!gnu_long_name.empty()) {
path = std::move(gnu_long_name);
} else if (!global_pax_path.empty()) {
path = global_pax_path;
} else {
const std::string_view name =
c_field(std::span{hdr}.subspan(0, 100));
const std::string_view prefix =
magic_view.starts_with("ustar")
? c_field(std::span{hdr}.subspan(345, 155))
: std::string_view{};
if (!prefix.empty()) {
path = std::string{prefix} + "/" + std::string{name};
} else {
path.assign(name);
}
}
std::string link;
if (!next_pax_link.empty()) {
link = std::move(next_pax_link);
} else if (!gnu_long_link.empty()) {
link = std::move(gnu_long_link);
} else if (!global_pax_link.empty()) {
link = global_pax_link;
} else {
link.assign(c_field(std::span{hdr}.subspan(157, 100)));
}
const std::uint64_t entry_size =
next_pax_size.has_value()
? *next_pax_size
: (global_pax_size.has_value() ? *global_pax_size
: *parsed_size);
EntryType etype = EntryType::Other;
if (typeflag == '1') {
etype = EntryType::Hardlink;
} else if (typeflag == '2') {
etype = EntryType::Symlink;
} else if (typeflag == '5') {
etype = EntryType::Directory;
} else if (typeflag == '0' || typeflag == '\0') {
if (typeflag == '\0' && !magic_view.starts_with("ustar") &&
entry_size == 0 && path.ends_with('/')) {
etype = EntryType::Directory;
} else {
etype = EntryType::RegularFile;
}
}
BuiltinTarEntry out{};
out.path = std::move(path);
out.linkname = std::move(link);
out.type = etype;
out.mode = static_cast<std::uint32_t>(*parsed_mode & 07777ULL);
out.declared_size =
(etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_size = (etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_remaining = m_entry_size;
m_has_active_entry = (etype == EntryType::RegularFile);
// Non-regular entries with declared non-zero payload must advance
// over padding if any (standard tar has 0 size for dirs/links).
if (!m_has_active_entry && entry_size > 0) {
const std::uint64_t pad =
(kTarBlockSize - (entry_size % kTarBlockSize)) % kTarBlockSize;
if (auto dr = discard_bytes(entry_size + pad,
"non-regular entry payload");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
return std::optional<BuiltinTarEntry>{std::move(out)};
}
}
Void::Result::Result<void> BuiltinTarStream::finish_active_entry_padding()
{
m_has_active_entry = false;
const std::uint64_t pad =
(kTarBlockSize - (m_entry_size % kTarBlockSize)) % kTarBlockSize;
m_entry_size = 0;
m_entry_remaining = 0;
if (pad > 0) {
return discard_bytes(pad, "tar entry block padding");
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_entry_data(std::span<std::byte> dst)
{
if (!m_has_active_entry) {
return std::size_t{0};
}
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return std::size_t{0};
}
if (dst.empty()) {
return std::size_t{0};
}
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(dst.size(), m_entry_remaining));
if (auto rr = read_exact_required(dst.subspan(0, want),
"tar entry data");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
m_entry_remaining -= want;
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
}
return want;
}
Void::Result::Result<std::uint64_t> BuiltinTarStream::skip_entry_data()
{
if (!m_has_active_entry) {
return std::uint64_t{0};
}
const std::uint64_t skipped = m_entry_remaining;
const std::uint64_t rem = m_entry_remaining;
m_entry_remaining = 0;
if (rem > 0) {
if (auto dr = discard_bytes(rem, "tar entry data");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return skipped;
}
} // namespace Void::Archive::Detail
+93
View File
@@ -0,0 +1,93 @@
#pragma once
#include <Void/Archive/Types.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
namespace Void::Archive::Detail
{
struct BuiltinCreateItem {
std::string path{};
bool is_directory{false};
std::uint32_t mode{0644};
std::uint64_t size{0};
std::span<const std::byte> inline_content{};
int source_fd{-1};
};
[[nodiscard]] Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options);
struct BuiltinTarEntry {
std::string path{};
std::string linkname{};
EntryType type{EntryType::RegularFile};
std::uint64_t declared_size{0};
std::uint32_t mode{0644};
};
class BuiltinTarStream
{
public:
BuiltinTarStream(
ByteSource& source, const ReadLimits& limits,
std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock);
[[nodiscard]] Void::Result::Result<void> open();
[[nodiscard]] Void::Result::Result<std::optional<BuiltinTarEntry>>
next_entry();
[[nodiscard]] Void::Result::Result<std::size_t>
read_entry_data(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry_data();
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept
{
return m_total_compressed;
}
private:
[[nodiscard]] Void::Result::Result<void> check_stop_deadline() const;
[[nodiscard]] Void::Result::Result<std::size_t>
read_exact_or_eof(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<void>
read_exact_required(std::span<std::byte> dst,
const char* context);
[[nodiscard]] Void::Result::Result<void>
discard_bytes(std::uint64_t count, const char* context);
[[nodiscard]] Void::Result::Result<void>
finish_active_entry_padding();
ByteSource* m_source{nullptr};
ReadLimits m_limits{};
std::stop_token m_stop{};
std::optional<Void::Time::MonotonicClock::time_point> m_deadline{};
const Void::Time::MonotonicClock* m_clock{
&Void::Time::SystemMonotonicClock::instance()};
std::vector<std::byte> m_prefetch{};
std::size_t m_prefetch_off{0};
std::uint64_t m_total_compressed{0};
bool m_reached_eof{false};
bool m_has_active_entry{false};
std::uint64_t m_entry_size{0};
std::uint64_t m_entry_remaining{0};
std::size_t m_metadata_budget_used{0};
};
} // namespace Void::Archive::Detail
File diff suppressed because it is too large. Load diff
+17 -2
View File
@@ -1,4 +1,19 @@
set(_void_archive_ext_deps "")
set(_void_archive_has_libarchive 0)
if(NOT CMAKE_DISABLE_FIND_PACKAGE_LibArchive)
if(NOT TARGET LibArchive::LibArchive)
find_package(LibArchive QUIET)
endif()
if(TARGET LibArchive::LibArchive)
list(APPEND _void_archive_ext_deps LibArchive::LibArchive)
set(_void_archive_has_libarchive 1)
endif()
endif()
void_add_module(Archive void_add_module(Archive
INTERNAL_DEPS Functional INTERNAL_DEPS Functional Time System
EXTERNAL_DEPS LibArchive::LibArchive EXTERNAL_DEPS ${_void_archive_ext_deps}
)
target_compile_definitions(Void_Archive PUBLIC
VOID_ARCHIVE_HAS_LIBARCHIVE=${_void_archive_has_libarchive}
) )
+276 -77
View File
@@ -7,108 +7,284 @@ namespace Void::Argparse
Parser::Parser(std::string program, std::string description) Parser::Parser(std::string program, std::string description)
: program_{std::move(program)}, description_{std::move(description)} : program_{std::move(program)}, description_{std::move(description)}
{}
Parser& Parser::flag(std::string_view lng, std::string_view sht,
std::string_view desc, bool& out)
{ {
flags_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, &out}); }
Parser::~Parser() = default;
Parser::Parser(Parser&&) noexcept = default;
Parser& Parser::operator=(Parser&&) noexcept = default;
Parser& Parser::flag(std::string_view lng,
std::string_view sht,
std::string_view desc,
bool& out)
{
flags_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, &out});
return *this; return *this;
} }
Parser& Parser::option(std::string_view lng, std::string_view sht, Parser& Parser::option(std::string_view lng,
std::string_view desc, std::optional<std::string>& out) std::string_view sht,
std::string_view desc,
std::optional<std::string>& out)
{ {
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr}); options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr, nullptr});
return *this; return *this;
} }
Parser& Parser::option_default(std::string_view lng, std::string_view sht, Parser& Parser::option_many(std::string_view lng,
std::string_view desc, std::string& out, std::string_view sht,
std::string_view default_value) std::string_view desc,
std::vector<std::string>& out)
{
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, nullptr, nullptr, &out});
return *this;
}
Parser& Parser::option_default(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::string& out,
std::string_view default_value)
{ {
out = std::string{default_value}; out = std::string{default_value};
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, options_.push_back({std::string{lng},
std::string{default_value}, nullptr, &out}); std::string{sht},
std::string{desc},
std::string{default_value},
nullptr,
&out,
nullptr});
return *this; return *this;
} }
Parser& Parser::positional(std::string_view name, std::string_view desc, std::string& out) Parser& Parser::positional(std::string_view name,
std::string_view desc,
std::string& out)
{ {
positionals_.push_back({std::string{name}, std::string{desc}, &out}); positionals_.push_back({std::string{name}, std::string{desc}, &out});
return *this; return *this;
} }
std::expected<void, std::string> Parser& Parser::positional_many(std::string_view name,
Parser::parse(int argc, const char* const* argv) const std::string_view desc,
std::vector<std::string>& out,
bool required)
{ {
positional_many_ = MultiPosEntry{
std::string{name}, std::string{desc}, &out, required};
return *this;
}
Parser& Parser::subcommand(std::string name,
std::string description,
std::function<void()> on_selected)
{
const std::string sub_prog =
program_.empty() ? name : (program_ + " " + name);
auto sub_parser = std::make_unique<Parser>(sub_prog, std::move(description));
Parser* raw = sub_parser.get();
subcommands_.push_back(SubcommandEntry{
.name = std::move(name),
.parser = std::move(sub_parser),
.on_selected = std::move(on_selected),
});
return *raw;
}
Parser& Parser::require_subcommand(bool required) noexcept
{
has_explicit_require_sub_ = true;
require_subcommand_ = required;
return *this;
}
ParseResult Parser::parse_detailed(int argc, const char* const* argv) const
{
const Parser* active = this;
std::size_t pos_idx = 0; std::size_t pos_idx = 0;
bool after_double_dash = false;
std::vector<std::string> matched_path;
std::vector<const std::function<void()>*> callbacks;
auto match_flag_or_opt = [&](const Parser* p,
std::string_view arg,
int& i,
bool& matched,
std::string& err) -> bool {
for (const auto& f : p->flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched = true;
return true;
}
}
for (const auto& opt : p->options_) {
std::string_view value;
bool found = false;
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=') {
value = arg.substr(opt.lng.size() + 1);
found = true;
} else if (arg == opt.lng ||
(!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc) {
err = "option '" + std::string{arg} + "' requires a value";
return false;
}
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
if (opt.out_many) opt.out_many->push_back(val_str);
matched = true;
return true;
}
}
matched = false;
return true;
};
for (int i = 1; i < argc; ++i) { for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]}; const std::string_view arg{argv[i]};
// Help if (!after_double_dash) {
if (arg == "--help" || arg == "-h") { if (arg == "--") {
return std::unexpected{help()}; after_double_dash = true;
} continue;
}
// Flag check if (arg == "--help" || arg == "-h") {
bool matched_flag = false; return ParseResult{
for (const auto& f : flags_) { .outcome = ParseOutcome::Help,
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) { .message = active->help(),
*f.out = true; .matched_command_path = std::move(matched_path),
matched_flag = true; };
break; }
bool matched = false;
std::string err;
if (!match_flag_or_opt(active, arg, i, matched, err)) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = std::move(err),
.matched_command_path = std::move(matched_path),
};
}
if (matched) {
continue;
}
if (arg.size() > 1 && arg[0] == '-') {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown option: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (pos_idx == 0 && !active->subcommands_.empty()) {
const SubcommandEntry* chosen = nullptr;
for (const auto& sub : active->subcommands_) {
if (sub.name == arg) {
chosen = &sub;
break;
}
}
if (chosen != nullptr) {
matched_path.push_back(chosen->name);
if (chosen->on_selected) {
callbacks.push_back(&chosen->on_selected);
}
active = chosen->parser.get();
pos_idx = 0;
continue;
}
if (active->positionals_.empty() &&
!active->positional_many_.has_value()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown subcommand: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
} }
} }
if (matched_flag) continue;
// Option check: --key=value or --key value or -k value if (pos_idx < active->positionals_.size()) {
bool matched_opt = false; *active->positionals_[pos_idx++].out = std::string{arg};
for (const auto& opt : options_) { } else if (active->positional_many_.has_value() &&
std::string_view value; active->positional_many_->out != nullptr) {
bool found = false; active->positional_many_->out->push_back(std::string{arg});
} else {
// --key=value return ParseResult{
if (arg.size() > opt.lng.size() + 1 && .outcome = ParseOutcome::Error,
arg.substr(0, opt.lng.size()) == opt.lng && .message =
arg[opt.lng.size()] == '=') "unexpected positional argument: " + std::string{arg},
{ .matched_command_path = std::move(matched_path),
value = arg.substr(opt.lng.size() + 1); };
found = true;
}
// --key value or -k value
else if (arg == opt.lng || (!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc)
return std::unexpected{"option '" + std::string{arg} + "' requires a value"};
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
matched_opt = true;
break;
}
} }
if (matched_opt) continue;
// Unknown --/- prefixed arg
if (arg.size() > 1 && arg[0] == '-')
return std::unexpected{"unknown option: " + std::string{arg}};
// Positional
if (pos_idx >= positionals_.size())
return std::unexpected{"unexpected positional argument: " + std::string{arg}};
*positionals_[pos_idx++].out = std::string{arg};
} }
// Check required positionals if (!active->subcommands_.empty()) {
for (std::size_t j = pos_idx; j < positionals_.size(); ++j) const bool req = active->has_explicit_require_sub_
return std::unexpected{"missing required argument: <" + positionals_[j].name + ">"}; ? active->require_subcommand_
: true;
if (req) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing subcommand for '" + active->program_ + "'",
.matched_command_path = std::move(matched_path),
};
}
}
for (std::size_t j = pos_idx; j < active->positionals_.size(); ++j) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required argument: <" +
active->positionals_[j].name + ">",
.matched_command_path = std::move(matched_path),
};
}
if (active->positional_many_.has_value() &&
active->positional_many_->required &&
active->positional_many_->out != nullptr &&
active->positional_many_->out->empty()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required arguments: <" +
active->positional_many_->name + ">",
.matched_command_path = std::move(matched_path),
};
}
for (const auto* cb : callbacks) {
(*cb)();
}
return ParseResult{
.outcome = ParseOutcome::Ok,
.message = {},
.matched_command_path = std::move(matched_path),
};
}
std::expected<void, std::string> Parser::parse(int argc,
const char* const* argv) const
{
auto res = parse_detailed(argc, argv);
if (!res.ok()) {
return std::unexpected{std::move(res.message)};
}
return {}; return {};
} }
@@ -116,19 +292,42 @@ std::string Parser::help() const
{ {
std::ostringstream os; std::ostringstream os;
os << "Usage: " << program_; os << "Usage: " << program_;
for (const auto& f : flags_) os << " [" << f.lng << "]"; for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& o : options_) { for (const auto& o : options_) {
const std::string_view dn = std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0); const std::string_view dn =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " [" << o.lng << " <" << dn << ">]"; os << " [" << o.lng << " <" << dn << ">]";
} }
if (!subcommands_.empty()) {
os << " <command>";
}
for (const auto& p : positionals_) os << " <" << p.name << ">"; for (const auto& p : positionals_) os << " <" << p.name << ">";
if (positional_many_.has_value()) {
os << (positional_many_->required ? " <" : " [")
<< positional_many_->name
<< (positional_many_->required ? "...>" : "...]");
}
os << "\n"; os << "\n";
if (!description_.empty()) os << "\n" << description_ << "\n"; if (!description_.empty()) os << "\n" << description_ << "\n";
if (!positionals_.empty()) { if (!subcommands_.empty()) {
os << "\nCommands:\n";
for (const auto& s : subcommands_) {
os << " " << s.name;
if (!s.parser->description_.empty()) {
os << " " << s.parser->description_;
}
os << "\n";
}
}
if (!positionals_.empty() || positional_many_.has_value()) {
os << "\nArguments:\n"; os << "\nArguments:\n";
for (const auto& p : positionals_) for (const auto& p : positionals_)
os << " <" << p.name << "> " << p.desc << "\n"; os << " <" << p.name << "> " << p.desc << "\n";
if (positional_many_.has_value()) {
os << " <" << positional_many_->name << "...> "
<< positional_many_->desc << "\n";
}
} }
if (!flags_.empty()) { if (!flags_.empty()) {
os << "\nFlags:\n"; os << "\nFlags:\n";
@@ -141,13 +340,13 @@ std::string Parser::help() const
if (!options_.empty()) { if (!options_.empty()) {
os << "\nOptions:\n"; os << "\nOptions:\n";
for (const auto& o : options_) { for (const auto& o : options_) {
// Derive a display name from the long option (strip leading --) const std::string_view dname =
const std::string_view dname = std::string_view{o.lng}.substr( std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
o.lng.size() > 2 ? 2 : 0);
os << " " << o.lng; os << " " << o.lng;
if (!o.sht.empty()) os << ", " << o.sht; if (!o.sht.empty()) os << ", " << o.sht;
os << " <" << dname << ">"; os << " <" << dname << ">";
if (!o.def.empty()) os << " (default: " << o.def << ")"; if (!o.def.empty()) os << " (default: " << o.def << ")";
if (o.out_many != nullptr) os << " (repeatable)";
os << " " << o.desc << "\n"; os << " " << o.desc << "\n";
} }
} }
@@ -155,4 +354,4 @@ std::string Parser::help() const
return os.str(); return os.str();
} }
} // namespace Void::Argparse } // namespace Void::Argparse
+766
View File
@@ -0,0 +1,766 @@
#include <Void/Configuration/Schema.hpp>
#include <Void/Data/Ini.hpp>
#include <Void/Data/Json.hpp>
#include <Void/System/Path.hpp>
#include <algorithm>
#include <cctype>
#include <charconv>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <numeric>
#include <system_error>
#if defined(__unix__) || defined(__APPLE__)
extern char** environ; // NOLINT
#define VOID_SCHEMA_HAS_ENVIRON 1
#endif
namespace Void::Configuration
{
namespace detail
{
Void::Result::Result<bool> parse_strict_bool(std::string_view raw)
{
std::string lower;
lower.reserve(raw.size());
for (const char c : raw) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "true" || lower == "1" || lower == "yes" ||
lower == "on") {
return true;
}
if (lower == "false" || lower == "0" || lower == "no" ||
lower == "off") {
return false;
}
return Void::Result::fail(make_config_error(
ConfigErrorCode::type_mismatch, "expected boolean value"));
}
Void::Result::Result<std::int64_t> parse_strict_i64_or_bytes(
std::string_view raw, bool allow_bytes, bool is_secret)
{
if (raw.empty()) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::type_mismatch, "empty integer value"));
}
std::int64_t exact = 0;
const char* begin = raw.data();
const char* end = raw.data() + raw.size();
const auto [ptr, ec] = std::from_chars(begin, end, exact);
if (ec == std::errc{} && ptr == end) {
return exact;
}
if (ec == std::errc::result_out_of_range) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::range_error,
std::string{"signed integer overflow: "} +
redact_display(raw, is_secret)));
}
if (allow_bytes) {
double num = 0.0;
const auto [bptr, bec] = std::from_chars(begin, end, num);
if (bec == std::errc{} && bptr != begin && std::isfinite(num) &&
num >= 0.0) {
std::string_view suffix{bptr, end};
while (!suffix.empty() && suffix.front() == ' ') {
suffix.remove_prefix(1);
}
double mult = 0.0;
if (suffix == "B" || suffix.empty()) {
mult = 1.0;
} else if (suffix == "KB") {
mult = 1e3;
} else if (suffix == "MB") {
mult = 1e6;
} else if (suffix == "GB") {
mult = 1e9;
} else if (suffix == "TB") {
mult = 1e12;
} else if (suffix == "KiB") {
mult = 1024.0;
} else if (suffix == "MiB") {
mult = 1024.0 * 1024.0;
} else if (suffix == "GiB") {
mult = 1024.0 * 1024.0 * 1024.0;
} else if (suffix == "TiB") {
mult = 1024.0 * 1024.0 * 1024.0 * 1024.0;
}
if (mult > 0.0) {
const double scaled = num * mult;
if (std::isfinite(scaled) &&
scaled <=
static_cast<double>(
std::numeric_limits<std::int64_t>::max())) {
return static_cast<std::int64_t>(scaled);
}
return Void::Result::fail(make_config_error(
ConfigErrorCode::range_error,
"byte-size value overflows int64_t"));
}
}
}
return Void::Result::fail(make_config_error(
ConfigErrorCode::type_mismatch,
std::string{"not a signed integer or byte size: "} +
redact_display(raw, is_secret)));
}
Void::Result::Result<std::uint64_t> parse_strict_u64_or_bytes(
std::string_view raw, bool allow_bytes, bool is_secret)
{
if (raw.empty()) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::type_mismatch,
"empty unsigned integer value"));
}
std::uint64_t exact = 0;
const char* begin = raw.data();
const char* end = raw.data() + raw.size();
const auto [ptr, ec] = std::from_chars(begin, end, exact);
if (ec == std::errc{} && ptr == end) {
return exact;
}
if (ec == std::errc::result_out_of_range) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::range_error,
std::string{"unsigned integer overflow: "} +
redact_display(raw, is_secret)));
}
if (allow_bytes) {
double num = 0.0;
const auto [bptr, bec] = std::from_chars(begin, end, num);
if (bec == std::errc{} && bptr != begin && std::isfinite(num) &&
num >= 0.0) {
std::string_view suffix{bptr, end};
while (!suffix.empty() && suffix.front() == ' ') {
suffix.remove_prefix(1);
}
double mult = 0.0;
if (suffix == "B" || suffix.empty()) {
mult = 1.0;
} else if (suffix == "KB") {
mult = 1e3;
} else if (suffix == "MB") {
mult = 1e6;
} else if (suffix == "GB") {
mult = 1e9;
} else if (suffix == "TB") {
mult = 1e12;
} else if (suffix == "KiB") {
mult = 1024.0;
} else if (suffix == "MiB") {
mult = 1024.0 * 1024.0;
} else if (suffix == "GiB") {
mult = 1024.0 * 1024.0 * 1024.0;
} else if (suffix == "TiB") {
mult = 1024.0 * 1024.0 * 1024.0 * 1024.0;
}
if (mult > 0.0) {
const double scaled = num * mult;
if (std::isfinite(scaled) &&
scaled < 18446744073709551616.0) {
return static_cast<std::uint64_t>(scaled);
}
return Void::Result::fail(make_config_error(
ConfigErrorCode::range_error,
"byte-size value overflows uint64_t"));
}
}
}
return Void::Result::fail(make_config_error(
ConfigErrorCode::type_mismatch,
std::string{"not an unsigned integer or byte size: "} +
redact_display(raw, is_secret)));
}
Void::Result::Result<double> parse_strict_real(std::string_view raw,
bool is_secret)
{
if (raw.empty()) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::type_mismatch, "empty real value"));
}
double val = 0.0;
const char* begin = raw.data();
const char* end = raw.data() + raw.size();
const auto [ptr, ec] = std::from_chars(begin, end, val);
if (ec != std::errc{} || ptr != end || !std::isfinite(val)) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::type_mismatch,
std::string{"invalid finite real: "} +
redact_display(raw, is_secret)));
}
return val;
}
bool try_parse_vector_index(std::string_view suffix, std::size_t& out)
{
if (suffix.empty()) {
return false;
}
if (suffix.size() > 1 && suffix.front() == '0') {
return false;
}
std::size_t idx = 0;
const auto [ptr, ec] = std::from_chars(
suffix.data(), suffix.data() + suffix.size(), idx);
if (ec != std::errc{} || ptr != suffix.data() + suffix.size()) {
return false;
}
out = idx;
return true;
}
} // namespace detail
namespace
{
int precedence_rank(SourceKind kind) noexcept
{
switch (kind) {
case SourceKind::Defaults:
return 0;
case SourceKind::FileKeyValue:
case SourceKind::FileIni:
case SourceKind::FileJson:
return 1;
case SourceKind::Environment:
return 2;
case SourceKind::CliArgs:
return 3;
}
return 0;
}
struct EmittedItem {
std::string key{};
ValueState state{ValueState::Present};
std::string value{};
std::uint32_t line{0};
};
Void::Result::Result<void>
flatten_json_checked(const Void::Json::Value& v,
const std::string& prefix, std::size_t depth,
const ConfigLimits& limits,
std::vector<EmittedItem>& out,
std::unordered_set<std::string>& dot_paths,
std::unordered_set<std::string>& nested_paths)
{
if (depth > limits.max_nesting_depth) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: JSON nesting depth exceeds max_nesting_depth"));
}
if (v.is_object()) {
for (const auto& [k, child] : v.as_object()) {
if (k.size() > limits.max_key_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: JSON key exceeds max_key_bytes"));
}
const std::string full =
prefix.empty() ? k : prefix + "." + k;
if (k.find('.') != std::string::npos) {
if (nested_paths.contains(full)) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::key_collision,
"Configuration: key collision between literal dot '" +
full + "' and nested JSON path"));
}
dot_paths.insert(full);
} else if (!prefix.empty()) {
if (dot_paths.contains(full)) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::key_collision,
"Configuration: key collision between nested path '" +
full + "' and literal dotted key"));
}
nested_paths.insert(full);
}
if (auto r = flatten_json_checked(
child, full, depth + 1, limits, out, dot_paths,
nested_paths);
!r) {
return r;
}
}
return {};
}
if (v.is_array()) {
const auto& arr = v.as_array();
if (arr.size() > limits.max_vector_items) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: JSON array exceeds max_vector_items"));
}
for (std::size_t i = 0; i < arr.size(); ++i) {
const std::string child_key =
prefix + "." + std::to_string(i);
if (dot_paths.contains(child_key)) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::key_collision,
"Configuration: key collision with dotted path '" +
child_key + "'"));
}
nested_paths.insert(child_key);
if (auto r = flatten_json_checked(
arr[i], child_key, depth + 1, limits, out,
dot_paths, nested_paths);
!r) {
return r;
}
}
return {};
}
if (prefix.empty()) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::parse_error,
"Configuration: top-level JSON configuration must be an object"));
}
if (prefix.size() > limits.max_key_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: flattened key exceeds max_key_bytes"));
}
if (v.is_null()) {
out.push_back(EmittedItem{prefix, ValueState::Null, {}, 0});
} else if (v.is_string()) {
const auto& s = v.as_string();
out.push_back(EmittedItem{
prefix,
s.empty() ? ValueState::Empty : ValueState::Present, s, 0});
} else if (v.is_bool()) {
out.push_back(EmittedItem{
prefix, ValueState::Present,
v.as_bool() ? "true" : "false", 0});
} else if (v.is_int()) {
out.push_back(EmittedItem{
prefix, ValueState::Present, std::to_string(v.as_int()), 0});
} else if (v.is_uint()) {
out.push_back(EmittedItem{
prefix, ValueState::Present, std::to_string(v.as_uint()),
0});
} else if (v.is_number()) {
const double d = v.as_number();
if (!std::isfinite(d)) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::parse_error,
"Configuration: non-finite number for '" + prefix +
"'"));
}
std::string s;
if (!(d == 0.0 && std::signbit(d)) && std::floor(d) == d &&
std::abs(d) < 1e15) {
s = std::to_string(static_cast<long long>(d));
} else {
s = std::format("{}", d);
}
out.push_back(
EmittedItem{prefix, ValueState::Present, std::move(s), 0});
}
return {};
}
Void::Result::Result<std::string>
read_bounded_source_file(const std::filesystem::path& path,
const ConfigLimits& limits)
{
std::error_code ec;
const auto sz = std::filesystem::file_size(path, ec);
if (ec) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::io_error,
"Configuration: cannot stat source file '" + path.string() +
"'"));
}
if (sz > limits.max_source_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: source file '" + path.string() +
"' exceeds max_source_bytes"));
}
auto txt = Void::FileSystem::read_file(path);
if (!txt) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::io_error,
"Configuration: read error on '" + path.string() + "'"));
}
if (txt->size() > limits.max_source_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: source file '" + path.string() +
"' exceeds max_source_bytes"));
}
return *txt;
}
} // namespace
Void::Result::Result<MergedConfig>
load_sources(const SourceSet& sources, const ConfigLimits& limits,
const std::unordered_set<std::string>& secret_keys,
std::vector<Diagnostic>* diagnostics_out)
{
const auto& specs = sources.specs();
if (specs.size() > limits.max_sources) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration::load_sources: number of sources exceeds max_sources"));
}
std::vector<std::size_t> order(specs.size());
std::iota(order.begin(), order.end(), 0);
std::stable_sort(order.begin(), order.end(), [&](std::size_t a,
std::size_t b) {
const int ra = precedence_rank(specs[a].kind);
const int rb = precedence_rank(specs[b].kind);
return ra < rb;
});
MergedConfig merged;
std::size_t merged_bytes = 0;
auto record_diag = [&](const Diagnostic& d) {
if (diagnostics_out != nullptr &&
diagnostics_out->size() < limits.max_diagnostics) {
diagnostics_out->push_back(d);
}
};
auto apply_item =
[&](const SourceSpec& spec,
const EmittedItem& item) -> Void::Result::Result<void> {
const bool is_secret = secret_keys.contains(item.key);
if (item.key.size() > limits.max_key_bytes) {
Diagnostic d{ConfigErrorCode::limit_exceeded, "limit",
SourceLocation{spec.id, item.key, item.line},
"Configuration: key exceeds max_key_bytes",
is_secret};
record_diag(d);
return Void::Result::fail(
make_config_error(d.code, d.message));
}
if (item.value.size() > limits.max_scalar_bytes) {
Diagnostic d{
ConfigErrorCode::limit_exceeded, "limit",
SourceLocation{spec.id, item.key, item.line},
"Configuration: scalar value for '" + item.key + "' (" +
detail::redact_display(
std::to_string(item.value.size()) + "B",
is_secret) +
") exceeds max_scalar_bytes",
is_secret};
record_diag(d);
return Void::Result::fail(
make_config_error(d.code, d.message));
}
const std::size_t delta =
item.key.size() + (is_secret ? 0 : item.value.size()) +
spec.id.size();
if (merged_bytes + delta > limits.max_merged_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: merged configuration exceeds max_merged_bytes"));
}
if (!merged.entries.contains(item.key) &&
merged.entries.size() >= limits.max_keys) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: key count exceeds max_keys"));
}
merged_bytes += delta;
const SourceLocation loc{spec.id, item.key, item.line};
merged.entries[item.key] =
MergedEntry{item.state, item.value, loc};
SourceOrigin origin{spec.id, spec.kind, item.line, item.state};
auto& prov = merged.provenance->entries[item.key];
if (!prov.key.empty()) {
prov.shadowed.push_back(std::move(prov.winner));
} else {
prov.key = item.key;
}
prov.winner = std::move(origin);
prov.redacted = prov.redacted || is_secret;
return {};
};
for (const std::size_t idx : order) {
const auto& spec = specs[idx];
std::vector<EmittedItem> items;
for (const auto& rm_key : spec.removals) {
items.push_back(EmittedItem{rm_key, ValueState::Removed, {}, 0});
}
switch (spec.kind) {
case SourceKind::Defaults: {
for (const auto& [k, v] : spec.entries) {
items.push_back(EmittedItem{
k, v.empty() ? ValueState::Empty : ValueState::Present,
v, 0});
}
break;
}
case SourceKind::FileKeyValue: {
std::string text;
if (spec.is_inline) {
if (spec.inline_text.size() > limits.max_source_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: inline KV exceeds max_source_bytes"));
}
text = spec.inline_text;
} else {
auto r =
read_bounded_source_file(spec.file_path, limits);
if (!r) return Void::Result::fail(std::move(r).error());
text = std::move(*r);
}
std::size_t pos = 0;
std::uint32_t lineno = 0;
while (pos <= text.size()) {
++lineno;
const auto nl = text.find('\n', pos);
std::string_view line =
nl == std::string::npos
? std::string_view{text}.substr(pos)
: std::string_view{text}.substr(pos, nl - pos);
if (!line.empty() && line.back() == '\r') {
line.remove_suffix(1);
}
while (!line.empty() && line.front() == ' ') {
line.remove_prefix(1);
}
if (!line.empty() && line.front() != '#') {
const auto eq = line.find('=');
if (eq == std::string_view::npos) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::parse_error,
std::format(
"Configuration: source '{}' line {}: missing '='",
spec.id, lineno)));
}
auto k = line.substr(0, eq);
while (!k.empty() && k.back() == ' ') {
k.remove_suffix(1);
}
auto v = line.substr(eq + 1);
items.push_back(EmittedItem{
std::string{k},
v.empty() ? ValueState::Empty
: ValueState::Present,
std::string{v}, lineno});
}
if (nl == std::string::npos) break;
pos = nl + 1;
}
break;
}
case SourceKind::FileIni: {
std::string text;
if (spec.is_inline) {
if (spec.inline_text.size() > limits.max_source_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: inline INI exceeds max_source_bytes"));
}
text = spec.inline_text;
} else {
auto r =
read_bounded_source_file(spec.file_path, limits);
if (!r) return Void::Result::fail(std::move(r).error());
text = std::move(*r);
}
Void::Ini::IniFile ini;
if (auto err = Void::Ini::IniFile::parse(ini, text);
err.has_value()) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::parse_error,
std::format(
"Configuration: INI source '{}' line {}: {}",
spec.id, err->line, err->message)));
}
for (const auto& sec : ini.sections()) {
const auto* tbl = ini.section(sec);
if (tbl == nullptr) continue;
for (const auto& [k, v] : *tbl) {
std::string full =
sec.empty() ? k : sec + "." + k;
items.push_back(EmittedItem{
std::move(full),
v.empty() ? ValueState::Empty
: ValueState::Present,
v, 0});
}
}
break;
}
case SourceKind::FileJson: {
std::string text;
if (spec.is_inline) {
if (spec.inline_text.size() > limits.max_source_bytes) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"Configuration: inline JSON exceeds max_source_bytes"));
}
text = spec.inline_text;
} else {
auto r =
read_bounded_source_file(spec.file_path, limits);
if (!r) return Void::Result::fail(std::move(r).error());
text = std::move(*r);
}
auto parsed = Void::Json::parse(text);
if (!parsed) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::parse_error,
std::format(
"Configuration: JSON source '{}' line {} col {}: {}",
spec.id, parsed.error().line,
parsed.error().col, parsed.error().message)));
}
if (!parsed->is_object()) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::parse_error,
"Configuration: JSON root must be an object in '" +
spec.id + "'"));
}
std::unordered_set<std::string> dot_paths;
std::unordered_set<std::string> nested_paths;
if (auto fr = flatten_json_checked(*parsed, "", 0, limits,
items, dot_paths,
nested_paths);
!fr) {
return Void::Result::fail(std::move(fr).error());
}
break;
}
case SourceKind::Environment: {
for (const auto& [k, v] : spec.entries) {
items.push_back(EmittedItem{
k, v.empty() ? ValueState::Empty : ValueState::Present,
v, 0});
}
for (const auto& k : spec.env_keys) {
if (auto ev = get_env(k); ev) {
items.push_back(EmittedItem{
k,
ev->empty() ? ValueState::Empty
: ValueState::Present,
std::move(*ev), 0});
}
}
if (!spec.env_prefix.empty()) {
#ifdef VOID_SCHEMA_HAS_ENVIRON
for (char** env = environ; *env != nullptr; ++env) {
const std::string_view kv{*env};
const auto eq = kv.find('=');
if (eq == std::string_view::npos ||
!kv.starts_with(spec.env_prefix)) {
continue;
}
const auto raw_k = kv.substr(
spec.env_prefix.size(),
eq - spec.env_prefix.size());
std::string normalized;
normalized.reserve(raw_k.size());
for (std::size_t i = 0; i < raw_k.size(); ++i) {
if (raw_k[i] == '_' && i + 1 < raw_k.size() &&
raw_k[i + 1] == '_') {
normalized += '.';
++i;
} else {
normalized += static_cast<char>(
std::tolower(
static_cast<unsigned char>(
raw_k[i])));
}
}
const auto val_sv = kv.substr(eq + 1);
items.push_back(EmittedItem{
std::move(normalized),
val_sv.empty() ? ValueState::Empty
: ValueState::Present,
std::string{val_sv}, 0});
}
#endif
}
break;
}
case SourceKind::CliArgs: {
for (std::size_t i = 0; i < spec.cli_args.size(); ++i) {
const std::string_view arg{spec.cli_args[i]};
if (!arg.starts_with("--") || arg.size() <= 2) {
continue;
}
const auto body = arg.substr(2);
if (const auto eq = body.find('=');
eq != std::string_view::npos) {
const auto val_sv = body.substr(eq + 1);
items.push_back(EmittedItem{
std::string{body.substr(0, eq)},
val_sv.empty() ? ValueState::Empty
: ValueState::Present,
std::string{val_sv}, 0});
} else if (i + 1 < spec.cli_args.size() &&
!std::string_view{spec.cli_args[i + 1]}
.starts_with("--")) {
const auto val_sv =
std::string_view{spec.cli_args[i + 1]};
items.push_back(EmittedItem{
std::string{body},
val_sv.empty() ? ValueState::Empty
: ValueState::Present,
std::string{val_sv}, 0});
++i;
} else {
items.push_back(EmittedItem{
std::string{body}, ValueState::Present, "true",
0});
}
}
break;
}
}
for (const auto& item : items) {
if (auto r = apply_item(spec, item); !r) {
return Void::Result::fail(std::move(r).error());
}
}
}
// Deterministic FNV-1a digest over sorted entries.
std::uint64_t h = 14695981039346656037ULL;
auto mix = [&](std::string_view s) {
for (const char ch : s) {
h ^= static_cast<unsigned char>(ch);
h *= 1099511628211ULL;
}
h ^= 0xff;
h *= 1099511628211ULL;
};
for (const auto& [k, e] : merged.entries) {
mix(k);
h ^= static_cast<std::uint64_t>(e.state);
h *= 1099511628211ULL;
mix(e.value);
}
merged.revision_digest = h;
return merged;
}
} // namespace Void::Configuration
+1
View File
@@ -1,3 +1,4 @@
void_add_module(Configuration void_add_module(Configuration
INTERNAL_DEPS Core Functional System Data Time LogState INTERNAL_DEPS Core Functional System Data Time LogState
EXCLUDE_HEADERS Void/Configuration/ReloadController.hpp
) )
@@ -0,0 +1,72 @@
#include <Void/Configuration/ReloadController.hpp>
#include <algorithm>
#include <set>
namespace Void::Configuration::detail
{
bool AsyncReloadGate::try_lock() noexcept
{
std::lock_guard lk{mu_};
if (locked_) {
return false;
}
locked_ = true;
return true;
}
bool AsyncReloadGate::enqueue_or_acquire(Void::Async::Executor* exec,
std::coroutine_handle<> h) noexcept
{
std::lock_guard lk{mu_};
if (!locked_) {
locked_ = true;
return false; // do not suspend
}
waiters_.push_back(Waiter{exec, h});
return true;
}
void AsyncReloadGate::release() noexcept
{
Waiter next{};
bool has_next = false;
{
std::lock_guard lk{mu_};
if (!waiters_.empty()) {
next = waiters_.front();
waiters_.pop_front();
has_next = true;
} else {
locked_ = false;
}
}
if (has_next && next.h) {
if (next.exec != nullptr) {
next.exec->post_completion(next.h);
} else {
next.h.resume();
}
}
}
std::vector<std::string> diff_merged_keys(const MergedConfig& old_cfg,
const MergedConfig& new_cfg)
{
std::set<std::string> out;
for (const auto& [k, ne] : new_cfg.entries) {
const auto it = old_cfg.entries.find(k);
if (it == old_cfg.entries.end() || it->second.state != ne.state ||
it->second.value != ne.value) {
out.insert(k);
}
}
for (const auto& [k, oe] : old_cfg.entries) {
if (!new_cfg.entries.contains(k) &&
oe.state != ValueState::Missing) {
out.insert(k);
}
}
return std::vector<std::string>{out.begin(), out.end()};
}
} // namespace Void::Configuration::detail
+4
View File
@@ -0,0 +1,4 @@
void_add_module(ConfigurationAsync
INTERNAL_DEPS Configuration SystemAsync Async Time Functional LogState
EXTRA_HEADERS Void/Configuration/ReloadController.hpp
)
+895
View File
@@ -0,0 +1,895 @@
#include "BuiltinHash.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <utility>
#include <variant>
namespace Void::Crypto::Detail
{
namespace
{
[[nodiscard]] inline std::uint32_t load_be32(const std::byte* p) noexcept
{
return (static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[0])) << 24U) |
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[1])) << 16U) |
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[2])) << 8U) |
static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[3]));
}
inline void store_be32(std::byte* p, std::uint32_t v) noexcept
{
p[0] = static_cast<std::byte>((v >> 24U) & 0xFFU);
p[1] = static_cast<std::byte>((v >> 16U) & 0xFFU);
p[2] = static_cast<std::byte>((v >> 8U) & 0xFFU);
p[3] = static_cast<std::byte>(v & 0xFFU);
}
[[nodiscard]] inline std::uint64_t load_be64(const std::byte* p) noexcept
{
return (static_cast<std::uint64_t>(load_be32(p)) << 32U) |
static_cast<std::uint64_t>(load_be32(p + 4));
}
inline void store_be64(std::byte* p, std::uint64_t v) noexcept
{
store_be32(p, static_cast<std::uint32_t>((v >> 32U) & 0xFFFFFFFFU));
store_be32(p + 4, static_cast<std::uint32_t>(v & 0xFFFFFFFFU));
}
[[nodiscard]] inline std::uint64_t load_le64(const std::byte* p) noexcept
{
return static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[0])) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[1])) << 8U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[2])) << 16U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[3])) << 24U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[4])) << 32U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[5])) << 40U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[6])) << 48U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[7])) << 56U);
}
inline void store_le64(std::byte* p, std::uint64_t v) noexcept
{
for (std::size_t i = 0; i < 8; ++i) {
p[i] = static_cast<std::byte>((v >> (8U * i)) & 0xFFU);
}
}
// ── FIPS 180-4 SHA-1 ─────────────────────────────────────────────────
struct Sha1State {
std::array<std::uint32_t, 5> h{0x67452301U, 0xefcdab89U,
0x98badcfeU, 0x10325476U,
0xc3d2e1f0U};
std::array<std::byte, 64> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint32_t, 80> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be32(block + i * 4);
}
for (std::size_t i = 16; i < 80; ++i) {
w[i] = std::rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^
w[i - 16],
1);
}
std::uint32_t a = h[0];
std::uint32_t b = h[1];
std::uint32_t c = h[2];
std::uint32_t d = h[3];
std::uint32_t e = h[4];
for (std::size_t i = 0; i < 80; ++i) {
std::uint32_t f = 0;
std::uint32_t k = 0;
if (i < 20) {
f = (b & c) | ((~b) & d);
k = 0x5a827999U;
} else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ed9eba1U;
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8f1bbcdcU;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6U;
}
const std::uint32_t temp =
std::rotl(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = std::rotl(b, 30);
b = a;
a = temp;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out20) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 56) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 56, std::byte{0});
store_be64(buf.data() + 56, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 5; ++i) {
store_be32(out20.data() + i * 4, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── FIPS 180-4 SHA-256 ───────────────────────────────────────────────
struct Sha256State {
static constexpr std::array<std::uint32_t, 64> kRound = {
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U,
0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U,
0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U,
0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU,
0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U,
0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U,
0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U,
0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U,
0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U,
0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U,
0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U};
std::array<std::uint32_t, 8> h{0x6a09e667U, 0xbb67ae85U,
0x3c6ef372U, 0xa54ff53aU,
0x510e527fU, 0x9b05688cU,
0x1f83d9abU, 0x5be0cd19U};
std::array<std::byte, 64> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint32_t, 64> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be32(block + i * 4);
}
for (std::size_t i = 16; i < 64; ++i) {
const std::uint32_t s0 = std::rotr(w[i - 15], 7) ^
std::rotr(w[i - 15], 18) ^
(w[i - 15] >> 3U);
const std::uint32_t s1 = std::rotr(w[i - 2], 17) ^
std::rotr(w[i - 2], 19) ^
(w[i - 2] >> 10U);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint32_t a = h[0];
std::uint32_t b = h[1];
std::uint32_t c = h[2];
std::uint32_t d = h[3];
std::uint32_t e = h[4];
std::uint32_t f = h[5];
std::uint32_t g = h[6];
std::uint32_t hv = h[7];
for (std::size_t i = 0; i < 64; ++i) {
const std::uint32_t S1 = std::rotr(e, 6) ^
std::rotr(e, 11) ^
std::rotr(e, 25);
const std::uint32_t ch = (e & f) ^ ((~e) & g);
const std::uint32_t temp1 =
hv + S1 + ch + kRound[i] + w[i];
const std::uint32_t S0 = std::rotr(a, 2) ^
std::rotr(a, 13) ^
std::rotr(a, 22);
const std::uint32_t maj =
(a & b) ^ (a & c) ^ (b & c);
const std::uint32_t temp2 = S0 + maj;
hv = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
h[5] += f;
h[6] += g;
h[7] += hv;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out32) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 56) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 56, std::byte{0});
store_be64(buf.data() + 56, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 8; ++i) {
store_be32(out32.data() + i * 4, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── FIPS 180-4 SHA-512 ───────────────────────────────────────────────
struct Sha512State {
static constexpr std::array<std::uint64_t, 80> kRound = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL};
std::array<std::uint64_t, 8> h{
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
std::array<std::byte, 128> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint64_t, 80> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be64(block + i * 8);
}
for (std::size_t i = 16; i < 80; ++i) {
const std::uint64_t s0 = std::rotr(w[i - 15], 1) ^
std::rotr(w[i - 15], 8) ^
(w[i - 15] >> 7U);
const std::uint64_t s1 = std::rotr(w[i - 2], 19) ^
std::rotr(w[i - 2], 61) ^
(w[i - 2] >> 6U);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint64_t a = h[0];
std::uint64_t b = h[1];
std::uint64_t c = h[2];
std::uint64_t d = h[3];
std::uint64_t e = h[4];
std::uint64_t f = h[5];
std::uint64_t g = h[6];
std::uint64_t hv = h[7];
for (std::size_t i = 0; i < 80; ++i) {
const std::uint64_t S1 = std::rotr(e, 14) ^
std::rotr(e, 18) ^
std::rotr(e, 41);
const std::uint64_t ch = (e & f) ^ ((~e) & g);
const std::uint64_t temp1 =
hv + S1 + ch + kRound[i] + w[i];
const std::uint64_t S0 = std::rotr(a, 28) ^
std::rotr(a, 34) ^
std::rotr(a, 39);
const std::uint64_t maj =
(a & b) ^ (a & c) ^ (b & c);
const std::uint64_t temp2 = S0 + maj;
hv = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
h[5] += f;
h[6] += g;
h[7] += hv;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out64) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 112) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 112, std::byte{0});
store_be64(buf.data() + 112, total_bytes >> 61U);
store_be64(buf.data() + 120, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 8; ++i) {
store_be64(out64.data() + i * 8, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── RFC 7693 BLAKE2b ─────────────────────────────────────────────────
struct Blake2bState {
static constexpr std::array<std::uint64_t, 8> kIv = {
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
static constexpr std::array<std::array<std::uint8_t, 16>, 12>
kSigma = {{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
{11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4},
{7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8},
{9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13},
{2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9},
{12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11},
{13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10},
{6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5},
{10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
}};
std::array<std::uint64_t, 8> h{kIv};
std::array<std::uint64_t, 2> t{0, 0};
std::array<std::byte, 128> buf{};
std::size_t buf_len{0};
std::size_t out_len{64};
void init(std::size_t digest_len) noexcept
{
h = kIv;
out_len = digest_len;
h[0] ^= 0x01010000ULL ^ static_cast<std::uint64_t>(out_len);
t = {0, 0};
buf.fill(std::byte{0});
buf_len = 0;
}
void add_counter(std::uint64_t inc) noexcept
{
t[0] += inc;
if (t[0] < inc) {
++t[1];
}
}
void compress(const std::byte* block, bool is_last) noexcept
{
std::array<std::uint64_t, 16> m{};
for (std::size_t i = 0; i < 16; ++i) {
m[i] = load_le64(block + i * 8);
}
std::array<std::uint64_t, 16> v{};
for (std::size_t i = 0; i < 8; ++i) {
v[i] = h[i];
v[i + 8] = kIv[i];
}
v[12] ^= t[0];
v[13] ^= t[1];
if (is_last) {
v[14] = ~v[14];
}
auto mix = [&](std::size_t r, std::size_t p,
std::size_t ia, std::size_t ib,
std::size_t ic, std::size_t id) noexcept {
const auto s0 = kSigma[r][2 * p];
const auto s1 = kSigma[r][2 * p + 1];
v[ia] = v[ia] + v[ib] + m[s0];
v[id] = std::rotr(v[id] ^ v[ia], 32);
v[ic] = v[ic] + v[id];
v[ib] = std::rotr(v[ib] ^ v[ic], 24);
v[ia] = v[ia] + v[ib] + m[s1];
v[id] = std::rotr(v[id] ^ v[ia], 16);
v[ic] = v[ic] + v[id];
v[ib] = std::rotr(v[ib] ^ v[ic], 63);
};
for (std::size_t r = 0; r < 12; ++r) {
mix(r, 0, 0, 4, 8, 12);
mix(r, 1, 1, 5, 9, 13);
mix(r, 2, 2, 6, 10, 14);
mix(r, 3, 3, 7, 11, 15);
mix(r, 4, 0, 5, 10, 15);
mix(r, 5, 1, 6, 11, 12);
mix(r, 6, 2, 7, 8, 13);
mix(r, 7, 3, 4, 9, 14);
}
for (std::size_t i = 0; i < 8; ++i) {
h[i] ^= v[i] ^ v[i + 8];
}
builtin_secure_wipe(std::as_writable_bytes(std::span{m}));
builtin_secure_wipe(std::as_writable_bytes(std::span{v}));
}
void update(std::span<const std::byte> data) noexcept
{
if (data.empty()) {
return;
}
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
// Only flush a full buffer when more bytes follow so
// finalize() sees the true final block.
if (off < data.size() && buf_len == buf.size()) {
add_counter(128);
compress(buf.data(), false);
buf_len = 0;
}
}
while (off + buf.size() < data.size()) {
add_counter(128);
compress(data.data() + off, false);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data() + buf_len, data.data() + off,
rem);
buf_len += rem;
}
}
void finalize_into(std::span<std::byte> out) noexcept
{
add_counter(static_cast<std::uint64_t>(buf_len));
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data(), true);
std::array<std::byte, 64> full{};
for (std::size_t i = 0; i < 8; ++i) {
store_le64(full.data() + i * 8, h[i]);
}
std::memcpy(out.data(), full.data(), out_len);
builtin_secure_wipe(full);
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(std::as_writable_bytes(std::span{t}));
builtin_secure_wipe(buf);
buf_len = 0;
}
};
} // namespace
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept
{
if (buffer.empty()) {
return;
}
volatile std::byte* p = buffer.data();
for (std::size_t i = 0; i < buffer.size(); ++i) {
p[i] = std::byte{0};
}
std::atomic_signal_fence(std::memory_order_seq_cst);
}
bool builtin_constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
volatile unsigned char diff = 0;
for (std::size_t i = 0; i < lhs.size(); ++i) {
const auto a = static_cast<unsigned char>(lhs[i]);
const auto b = static_cast<unsigned char>(rhs[i]);
diff = static_cast<unsigned char>(diff | (a ^ b));
}
std::atomic_signal_fence(std::memory_order_seq_cst);
return diff == 0;
}
struct BuiltinHasher::State {
std::variant<std::monostate, Sha1State, Sha256State, Sha512State,
Blake2bState>
impl{};
void wipe() noexcept
{
std::visit(
[](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (!std::is_same_v<T, std::monostate>) {
st.wipe();
}
},
impl);
impl.template emplace<std::monostate>();
}
};
BuiltinHasher::~BuiltinHasher() noexcept { destroy(); }
BuiltinHasher::BuiltinHasher(BuiltinHasher&& other) noexcept
: m_state(std::exchange(other.m_state, nullptr))
{
}
BuiltinHasher& BuiltinHasher::operator=(BuiltinHasher&& other) noexcept
{
if (this != &other) {
destroy();
m_state = std::exchange(other.m_state, nullptr);
}
return *this;
}
void BuiltinHasher::destroy() noexcept
{
if (m_state != nullptr) {
m_state->wipe();
delete m_state;
m_state = nullptr;
}
}
bool BuiltinHasher::init(HashAlgorithm algorithm) noexcept
{
if (m_state == nullptr) {
m_state = new (std::nothrow) State();
if (m_state == nullptr) {
return false;
}
} else {
m_state->wipe();
}
switch (algorithm) {
case HashAlgorithm::Sha1:
m_state->impl.emplace<Sha1State>();
return true;
case HashAlgorithm::Sha256:
m_state->impl.emplace<Sha256State>();
return true;
case HashAlgorithm::Sha512:
m_state->impl.emplace<Sha512State>();
return true;
case HashAlgorithm::Blake2b256: {
auto& b = m_state->impl.emplace<Blake2bState>();
b.init(32);
return true;
}
case HashAlgorithm::Blake2b512: {
auto& b = m_state->impl.emplace<Blake2bState>();
b.init(64);
return true;
}
}
return false;
}
void BuiltinHasher::update(std::span<const std::byte> data) noexcept
{
if (m_state == nullptr || data.empty()) {
return;
}
std::visit(
[&](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (!std::is_same_v<T, std::monostate>) {
st.update(data);
}
},
m_state->impl);
}
Digest BuiltinHasher::finalize()
{
Digest out;
if (m_state == nullptr) {
return out;
}
std::visit(
[&](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (std::is_same_v<T, Sha1State>) {
out.resize(20);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Sha256State>) {
out.resize(32);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Sha512State>) {
out.resize(64);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Blake2bState>) {
out.resize(st.out_len);
st.finalize_into(out);
}
},
m_state->impl);
return out;
}
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept
{
std::array<std::byte, 64> key_block{};
if (secret_key.size() > 64) {
Sha256State kh;
kh.update(secret_key);
kh.finalize_into(std::span{key_block}.subspan(0, 32));
} else if (!secret_key.empty()) {
std::memcpy(key_block.data(), secret_key.data(), secret_key.size());
}
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 64; ++i) {
ipad[i] = key_block[i] ^ std::byte{0x36};
opad[i] = key_block[i] ^ std::byte{0x5C};
}
std::array<std::byte, 32> inner_hash{};
{
Sha256State inner;
inner.update(ipad);
inner.update(message);
inner.finalize_into(inner_hash);
}
{
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(output_32);
}
builtin_secure_wipe(key_block);
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
void builtin_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) noexcept
{
std::array<std::byte, 32> zero_salt{};
const auto effective_salt =
salt.empty() ? std::span<const std::byte>{zero_salt} : salt;
std::array<std::byte, 32> prk{};
builtin_hmac_sha256(effective_salt, secret_input, prk);
std::array<std::byte, 32> t{};
std::size_t t_len = 0;
std::size_t written = 0;
std::uint8_t counter = 1;
while (written < secret_output.size()) {
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 32; ++i) {
ipad[i] = prk[i] ^ std::byte{0x36};
opad[i] = prk[i] ^ std::byte{0x5C};
}
for (std::size_t i = 32; i < 64; ++i) {
ipad[i] = std::byte{0x36};
opad[i] = std::byte{0x5C};
}
std::array<std::byte, 32> inner_hash{};
Sha256State inner;
inner.update(ipad);
if (t_len > 0) {
inner.update(std::span<const std::byte>{t.data(), t_len});
}
if (!context.empty()) {
inner.update(context);
}
const std::byte ctr_byte = static_cast<std::byte>(counter);
inner.update(std::span<const std::byte>{&ctr_byte, 1});
inner.finalize_into(inner_hash);
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(t);
t_len = 32;
const std::size_t copy_n =
std::min<std::size_t>(32, secret_output.size() - written);
std::memcpy(secret_output.data() + written, t.data(), copy_n);
written += copy_n;
++counter;
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
builtin_secure_wipe(prk);
builtin_secure_wipe(t);
}
} // namespace Void::Crypto::Detail
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <Void/Crypto/Crypto.hpp>
#include <Void/Crypto/Types.hpp>
#include <cstddef>
#include <span>
namespace Void::Crypto::Detail
{
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept;
[[nodiscard]] bool
builtin_constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept;
class BuiltinHasher
{
public:
BuiltinHasher() noexcept = default;
~BuiltinHasher() noexcept;
BuiltinHasher(BuiltinHasher&& other) noexcept;
BuiltinHasher& operator=(BuiltinHasher&& other) noexcept;
BuiltinHasher(const BuiltinHasher&) = delete;
BuiltinHasher& operator=(const BuiltinHasher&) = delete;
[[nodiscard]] bool init(HashAlgorithm algorithm) noexcept;
void update(std::span<const std::byte> data) noexcept;
[[nodiscard]] Digest finalize();
private:
struct State;
State* m_state{nullptr};
void destroy() noexcept;
};
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept;
void builtin_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) noexcept;
} // namespace Void::Crypto::Detail
+934 -88
View File
File diff suppressed because it is too large. Load diff
+18 -1
View File
@@ -1,4 +1,21 @@
set(_void_crypto_ext_deps "")
set(_void_crypto_has_openssl 0)
if(NOT CMAKE_DISABLE_FIND_PACKAGE_OpenSSL)
if(NOT TARGET OpenSSL::Crypto)
find_package(OpenSSL QUIET)
endif()
if(TARGET OpenSSL::Crypto)
list(APPEND _void_crypto_ext_deps OpenSSL::Crypto)
set(_void_crypto_has_openssl 1)
endif()
endif()
void_add_module(Crypto void_add_module(Crypto
INTERNAL_DEPS Functional INTERNAL_DEPS Functional
EXTERNAL_DEPS OpenSSL::Crypto EXTERNAL_DEPS ${_void_crypto_ext_deps}
EXCLUDE_HEADERS
Void/Crypto/AsyncHash.hpp
)
target_compile_definitions(Void_Crypto PUBLIC
VOID_CRYPTO_HAS_OPENSSL=${_void_crypto_has_openssl}
) )
+522
View File
@@ -0,0 +1,522 @@
#include <Void/Crypto/AsyncHash.hpp>
#include <algorithm>
#include <condition_variable>
#include <deque>
#include <format>
#include <fstream>
#include <functional>
#include <mutex>
#include <stop_token>
#include <thread>
#include <vector>
namespace Void::CryptoAsync
{
namespace
{
[[nodiscard]] Void::Result::Error
map_io_error(const Void::Result::Error& err)
{
if (err.kind() == Void::Result::ErrorKind::cancelled) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::cancelled, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::timeout) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::exhausted) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::resource_exhausted,
err.message(), err.system_code());
}
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::io_error, err.message(),
err.system_code());
}
} // namespace
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)
{
using namespace Void::Crypto;
if (hash_options.chunk_bytes == 0 ||
hash_options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::hash_stream: chunk_bytes must be in [1, 64 KiB]")};
}
if (!stream.valid()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::hash_stream: stream is invalid or closed")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: operation stopped before start")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired before start")};
}
auto hasher = Hasher::create(algorithm, hash_options.provider);
if (!hasher.has_value()) {
co_return std::unexpected{std::move(hasher.error())};
}
auto lease = driver.allocate_buffer(hash_options.chunk_bytes);
if (!lease.has_value()) {
co_return std::unexpected{map_io_error(lease.error())};
}
for (;;) {
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped between chunks")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired between chunks")};
}
auto transfer = co_await stream.read_some_owned(*lease, options);
if (!transfer.has_value()) {
co_return std::unexpected{map_io_error(transfer.error())};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped during stream read")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired after read")};
}
if (transfer->bytes > 0) {
if (auto upd = hasher->update(lease->readable());
!upd.has_value()) {
co_return std::unexpected{std::move(upd.error())};
}
}
if (transfer->eof) {
break;
}
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped before finalize")};
}
co_return hasher->finalize();
}
struct AsyncFileHasher::State : std::enable_shared_from_this<State> {
struct Job {
Job(Void::Crypto::HashAlgorithm alg,
std::filesystem::path p,
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
o)
: algorithm(alg), path(std::move(p)), op(std::move(o))
{
}
Void::Crypto::HashAlgorithm algorithm;
std::filesystem::path path;
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
op;
std::optional<std::stop_callback<std::function<void()>>>
cancel_cb{};
};
State(Void::Async::Executor& exec, FileHasherOptions opts,
const Void::Time::MonotonicClock& clk)
: executor(exec), options(std::move(opts)), clock(clk)
{
}
void start_workers_locked()
{
if (workers_started || options.max_concurrent == 0) {
return;
}
workers_started = true;
const std::size_t count =
std::max<std::size_t>(1, options.max_concurrent);
workers.reserve(count);
auto self = shared_from_this();
for (std::size_t i = 0; i < count; ++i) {
workers.emplace_back([self] { self->worker_loop(); });
}
}
void worker_loop()
{
for (;;) {
std::shared_ptr<Job> job;
{
std::unique_lock lk{mu};
cv.wait(lk, [this] {
if (closing) {
return true;
}
if (queue.empty()) {
return false;
}
if (active < options.max_concurrent &&
reserved_bytes + options.chunk_bytes <=
options.buffer_budget_bytes) {
return true;
}
return std::any_of(
queue.begin(), queue.end(),
[this](const auto& j) {
return j->op->stop_requested() ||
j->op->is_deadline_expired(clock);
});
});
// Purge any already-cancelled or expired jobs in queue.
std::vector<std::pair<std::shared_ptr<Job>,
Void::Result::Error>>
dropped_jobs;
for (auto it = queue.begin(); it != queue.end();) {
auto& item = *it;
if (closing || item->op->stop_requested()) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
closing
? Void::Crypto::CryptoErrorCode::closed
: Void::Crypto::CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: job cancelled while queued"));
it = queue.erase(it);
} else if (item->op->is_deadline_expired(clock)) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired while queued"));
it = queue.erase(it);
} else {
++it;
}
}
if (!dropped_jobs.empty()) {
lk.unlock();
for (auto& [dropped, err] : dropped_jobs) {
dropped->cancel_cb.reset();
const auto kind =
(err.kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
auto ticket = dropped->op->try_commit_error(
std::move(err), kind);
if (ticket.has_value()) {
ticket->dispatch();
}
dropped->op->release_backend_ref_and_dispatch();
}
lk.lock();
}
if (closing && queue.empty()) {
return;
}
if (queue.empty() || active >= options.max_concurrent ||
reserved_bytes + options.chunk_bytes >
options.buffer_budget_bytes) {
continue;
}
job = std::move(queue.front());
queue.pop_front();
++active;
reserved_bytes += options.chunk_bytes;
in_flight.push_back(job->op);
}
job->cancel_cb.reset();
auto result = run_job(*job);
{
std::lock_guard lk{mu};
--active;
reserved_bytes -= options.chunk_bytes;
++completed;
std::erase_if(in_flight, [&](const auto& weak_op) {
auto sp = weak_op.lock();
return !sp || sp == job->op;
});
}
cv.notify_all();
std::optional<Void::Async::ResumeTicket> ticket;
if (result.has_value()) {
ticket = job->op->try_commit_value(std::move(*result));
} else {
const auto kind =
(result.error().kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
ticket = job->op->try_commit_error(
std::move(result.error()), kind);
}
if (ticket.has_value()) {
ticket->dispatch();
}
job->op->release_backend_ref_and_dispatch();
}
}
[[nodiscard]] Void::Result::Result<Void::Crypto::Digest>
run_job(const Job& job) const
{
using namespace Void::Crypto;
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: cancelled before open")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before open")};
}
std::ifstream input{job.path, std::ios::binary};
if (!input.is_open()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: cannot open '{}'",
job.path.string()))};
}
auto hasher = Hasher::create(job.algorithm, options.provider);
if (!hasher.has_value()) {
return std::unexpected{std::move(hasher.error())};
}
std::vector<char> buffer(options.chunk_bytes);
while (input) {
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped during file read")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired during read")};
}
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0) {
const auto bytes = std::as_bytes(std::span{
buffer.data(), static_cast<std::size_t>(count)});
if (auto upd = hasher->update(bytes);
!upd.has_value()) {
return std::unexpected{std::move(upd.error())};
}
}
}
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: I/O error reading '{}'",
job.path.string()))};
}
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before finalize")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before finalize")};
}
return hasher->finalize();
}
Void::Async::Executor& executor;
FileHasherOptions options;
const Void::Time::MonotonicClock& clock;
mutable std::mutex mu{};
std::condition_variable cv{};
std::deque<std::shared_ptr<Job>> queue{};
std::vector<std::weak_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>>
in_flight{};
std::vector<std::thread> workers{};
bool workers_started{false};
bool closing{false};
bool joined{false};
std::size_t active{0};
std::size_t reserved_bytes{0};
std::uint64_t completed{0};
std::uint64_t rejected{0};
};
AsyncFileHasher::AsyncFileHasher(Void::Async::Executor& executor,
FileHasherOptions options,
const Void::Time::MonotonicClock& clock)
: m_state(std::make_shared<State>(executor, std::move(options), clock))
{
}
AsyncFileHasher::~AsyncFileHasher() { (void)close_and_join(); }
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
AsyncFileHasher::hash_file(Void::Crypto::HashAlgorithm algorithm,
std::filesystem::path path,
Void::Async::OperationOptions options)
{
using namespace Void::Crypto;
auto state = m_state;
if (state->options.max_concurrent == 0 ||
state->options.chunk_bytes == 0 ||
state->options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::AsyncFileHasher: invalid options")};
}
if (state->options.chunk_bytes > state->options.buffer_budget_bytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::resource_exhausted,
"CryptoAsync::AsyncFileHasher: chunk_bytes exceeds buffer budget")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before admission")};
}
if (Void::Async::is_deadline_expired(options, state->clock)) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before admission")};
}
auto op = Void::Async::OperationState<Digest>::create(
options, &state->executor, Void::Async::StopBehavior::notify_only);
auto job = std::make_shared<State::Job>(algorithm, std::move(path), op);
{
std::lock_guard lk{state->mu};
if (state->closing) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::AsyncFileHasher: service is closing")};
}
const std::size_t max_effective_concurrent = std::min(
state->options.max_concurrent,
state->options.buffer_budget_bytes / state->options.chunk_bytes);
const std::size_t capacity =
max_effective_concurrent + state->options.max_waiting;
if (state->active + state->queue.size() >= capacity) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::overloaded,
"CryptoAsync::AsyncFileHasher: wait queue is full")};
}
op->acquire_backend_ref();
state->start_workers_locked();
if (options.stop.stop_possible()) {
std::weak_ptr<State> weak_state = state;
job->cancel_cb.emplace(options.stop, [weak_state]() {
if (auto s = weak_state.lock()) {
s->cv.notify_all();
}
});
}
state->queue.push_back(std::move(job));
}
state->cv.notify_one();
co_return co_await op->awaitable(&state->executor);
}
void AsyncFileHasher::request_stop() noexcept
{
std::vector<
std::shared_ptr<Void::Async::OperationState<Void::Crypto::Digest>>>
ops;
{
std::lock_guard lk{m_state->mu};
m_state->closing = true;
for (const auto& j : m_state->queue) {
ops.push_back(j->op);
}
for (const auto& weak_op : m_state->in_flight) {
if (auto sp = weak_op.lock()) {
ops.push_back(std::move(sp));
}
}
}
for (auto& op : ops) {
op->request_stop();
}
m_state->cv.notify_all();
}
Void::Result::Result<void> AsyncFileHasher::close_and_join()
{
request_stop();
std::vector<std::thread> threads;
{
std::lock_guard lk{m_state->mu};
if (m_state->joined) {
return {};
}
m_state->joined = true;
threads.swap(m_state->workers);
}
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
return {};
}
FileHasherStats AsyncFileHasher::stats() const noexcept
{
std::lock_guard lk{m_state->mu};
return FileHasherStats{
.active = m_state->active,
.waiting = m_state->queue.size(),
.reserved_buffer_bytes = m_state->reserved_bytes,
.completed = m_state->completed,
.rejected = m_state->rejected,
.closing = m_state->closing,
};
}
} // namespace Void::CryptoAsync
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff. Show more