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
114 changed files with 26365 additions and 1281 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()
+39 -7
View File
@@ -1,8 +1,8 @@
# Workflow state # Workflow state
Updated: 2026-11-26. Updated: 2026-11-26.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave7` (from `main` Repository: VoidLibrary; active branch `feat/upstream-vbs-requests` (from `main`
at `43922d1`, merged Waves 1–6B and pushed to `origin/main`). at `53d42bd`, merged Waves 1–8 and pushed to `origin/main`).
## Completed objective ## Completed objective
@@ -308,10 +308,42 @@ while leaving local untracked files untouched.
- **`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. - **`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`. - 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–7 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`,
`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`, and `Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`,
`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`) are complete and verified on `Sqlite`/`SqliteAsync`/`Storage` `G-STORE`,
`feat/roadmap-p2-wave7`, ready to merge `--no-ff` into `main`, push to `origin`, and `Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`)
proceed continuously to **Wave 8 (`Configuration`, `Fsm`, `Plugin`, `Service`)**. and the VoidBuildSystem upstream feature wave (`VL-001`..`VL-013`) are complete,
verified, and merged to `main` via `--no-ff`.
+18
View File
@@ -101,6 +101,24 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| 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) | | 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) | | 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
+18
View File
@@ -273,3 +273,21 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
| 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 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 | | 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 | | 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,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.
+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,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.
+21 -6
View File
@@ -29,9 +29,14 @@ namespace Void::Archive
std::uint64_t bytes{0}; std::uint64_t bytes{0};
}; };
/// Extract a tar/tar.zst archive incrementally into `destination` without /// Returns true if Void::Archive was built with LibArchive support (required
/// invoking an external process. Preserved 1.x incremental API; callers /// for .tar.zst and .tar.gz compression/decompression; uncompressed USTAR/PAX
/// requiring all-or-nothing directory visibility should use /// .tar reading and writing work with zero external dependencies).
[[nodiscard]] bool has_libarchive_backend() noexcept;
/// Extract a tar/tar.gz/tar.zst archive incrementally into `destination`
/// without invoking an external process. Preserved 1.x incremental API;
/// callers requiring all-or-nothing directory visibility should use
/// `extract_staged` + `StagedTree::publish`. /// `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,
@@ -177,9 +182,9 @@ namespace Void::Archive
std::chrono::seconds min_age = std::chrono::seconds min_age =
std::chrono::seconds{300}); std::chrono::seconds{300});
/// Create a bounded, optionally reproducible tar or tar.zst archive from /// Create a bounded, optionally reproducible tar, tar.gz, or tar.zst
/// regular file and directory entries. Sorts normalized paths, rejects /// archive from regular file and directory entries. Sorts normalized
/// duplicates/conflicts, and opens source files with O_NOFOLLOW. /// paths, rejects duplicates/conflicts, and opens source files with O_NOFOLLOW.
[[nodiscard]] Void::Result::Result<void> [[nodiscard]] Void::Result::Result<void>
create_archive(ByteSink& sink, std::span<const CreateEntry> entries, create_archive(ByteSink& sink, std::span<const CreateEntry> entries,
const CreationOptions& options = {}); const CreationOptions& options = {});
@@ -189,6 +194,16 @@ namespace Void::Archive
std::span<const CreateEntry> entries, std::span<const CreateEntry> entries,
const CreationOptions& options = {}); 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 /// Hardened untrusted-input profile: extracts the archive in an isolated
/// System child process with bounded execution time and RSS checks, then /// System child process with bounded execution time and RSS checks, then
/// independently verifies the staged tree and inventory in the parent /// independently verifies the staged tree and inventory in the parent
+6 -1
View File
@@ -175,13 +175,17 @@ namespace Void::Archive
ProgressCallback on_progress{}; ProgressCallback on_progress{};
}; };
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd }; enum class ArchiveCompression : std::uint8_t { None = 0, Zstd, Gzip };
struct CreationOptions { struct CreationOptions {
ArchiveCompression compression{ArchiveCompression::Zstd}; ArchiveCompression compression{ArchiveCompression::Zstd};
bool reproducible{true}; bool reproducible{true};
ReadLimits limits{}; ReadLimits limits{};
std::stop_token stop{}; 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 { struct CreateEntry {
@@ -190,6 +194,7 @@ namespace Void::Archive
bool executable{false}; bool executable{false};
std::vector<std::byte> content{}; std::vector<std::byte> content{};
std::optional<std::filesystem::path> source_file{}; std::optional<std::filesystem::path> source_file{};
std::optional<std::uint32_t> mode{};
}; };
struct IsolationOptions { struct IsolationOptions {
+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
+28 -1
View File
@@ -13,9 +13,14 @@
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:
@@ -60,6 +65,11 @@ namespace Void::Crypto
[[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,
const ProviderOptions& provider); 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);
@@ -70,12 +80,29 @@ 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);
/// Move-only owning Ed25519 private key handle. Has no implicit copy, /// Move-only owning Ed25519 private key handle. Has no implicit copy,
/// string conversion, or secret formatting. /// string conversion, or secret formatting.
+2 -1
View File
@@ -111,10 +111,11 @@ namespace Void::Crypto
MovedFrom MovedFrom
}; };
/// Per-operation OpenSSL 3 provider selection. Never mutates process-wide /// Per-operation backend/provider selection. Never mutates process-wide
/// provider state. /// provider state.
struct ProviderOptions { struct ProviderOptions {
std::string property_query{}; std::string property_query{};
bool prefer_builtin{false};
}; };
struct Ed25519PublicKey { struct Ed25519PublicKey {
+246
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <array>
#include <charconv> #include <charconv>
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
@@ -41,6 +42,72 @@ 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:
@@ -179,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;
} }
@@ -435,4 +514,171 @@ namespace Void::Json::Strict
.allowDecimals = true}); .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 {
std::string out;
Detail::serialize_value(out, value, 0U, maximumDepth);
return out;
} catch (const Detail::ParseFailure& failure) {
return std::unexpected{failure.error};
}
}
} // namespace Void::Json::Strict } // namespace Void::Json::Strict
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 {
+5
View File
@@ -71,6 +71,11 @@ namespace Void::Result
inline constexpr std::uint32_t kSecurityErrorDomain = 19; inline constexpr std::uint32_t kSecurityErrorDomain = 19;
inline constexpr std::uint32_t kUpdateErrorDomain = 20; inline constexpr std::uint32_t kUpdateErrorDomain = 20;
inline constexpr std::uint32_t kSqliteErrorDomain = 21; 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};
+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;
+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
+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
+592
View File
@@ -24,10 +24,17 @@
#ifndef _WIN32 #ifndef _WIN32
#include <fcntl.h> #include <fcntl.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h> #include <unistd.h>
#if defined(__linux__) #if defined(__linux__)
#include <sys/random.h> #include <sys/random.h>
#if __has_include(<linux/fs.h>)
#include <linux/fs.h>
#endif
#endif #endif
#endif #endif
@@ -548,4 +555,589 @@ namespace detail
return {}; return {};
} }
// ── VL-010: File Locks, Atomic Symlink Swap, Reflink Copy, Timestamps ────────
enum class LockMode : std::uint8_t {
Shared,
Exclusive,
};
/// RAII advisory file lock backed by POSIX flock(2).
class FileLock final
{
public:
FileLock() noexcept = default;
~FileLock() noexcept { unlock(); }
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
FileLock(FileLock&& other) noexcept
: fd_(std::move(other.fd_))
, mode_(other.mode_)
{
}
FileLock& operator=(FileLock&& other) noexcept
{
if (this != &other) {
unlock();
fd_ = std::move(other.fd_);
mode_ = other.mode_;
}
return *this;
}
[[nodiscard]] bool locked() const noexcept { return fd_.valid(); }
[[nodiscard]] LockMode mode() const noexcept { return mode_; }
[[nodiscard]] int native_handle() const noexcept { return fd_.get(); }
void unlock() noexcept
{
#ifndef _WIN32
if (fd_.valid()) {
while (::flock(fd_.get(), LOCK_UN) != 0 && errno == EINTR) {
}
fd_.reset();
}
#endif
}
[[nodiscard]] static Void::Result::Result<FileLock, Void::Result::Error>
lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
auto res = acquire(path, mode, false);
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
if (!res->has_value()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::internal,
"FileSystem::FileLock::lock: unexpected empty result")};
}
return std::move(**res);
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
try_lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
return acquire(path, mode, true);
}
private:
explicit FileLock(Void::System::OwnedFd fd, LockMode mode) noexcept
: fd_(std::move(fd))
, mode_(mode)
{
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
acquire(const std::filesystem::path& path,
LockMode mode,
bool nonblocking)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::FileLock: empty path")};
}
int raw = ::open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666);
if (raw < 0 && mode == LockMode::Shared &&
(errno == EACCES || errno == EROFS)) {
raw = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
}
if (raw < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: cannot open '{}'",
path.string()),
err)};
}
Void::System::OwnedFd fd{raw};
const int op = (mode == LockMode::Shared ? LOCK_SH : LOCK_EX) |
(nonblocking ? LOCK_NB : 0);
for (;;) {
if (::flock(fd.get(), op) == 0) {
return std::optional<FileLock>{
FileLock{std::move(fd), mode}};
}
const int err = errno;
if (err == EINTR) {
continue;
}
if (nonblocking && (err == EWOULDBLOCK || err == EAGAIN)) {
return std::optional<FileLock>{std::nullopt};
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: flock failed for '{}'",
path.string()),
err)};
}
#else
(void)path;
(void)mode;
(void)nonblocking;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::FileLock: unsupported platform")};
#endif
}
Void::System::OwnedFd fd_{};
LockMode mode_{LockMode::Exclusive};
};
/// Atomically create or replace symlink at `link_path` pointing to `target`
/// (symlinkat temp -> renameat -> optional parent dir fsync).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_symlink_swap(
const std::filesystem::path& link_path,
const std::filesystem::path& target,
ReplaceDurability durability = ReplaceDurability::durable_sync)
{
#ifndef _WIN32
if (link_path.empty() || !link_path.has_filename() || target.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: empty link or target path")};
}
const std::string target_name = link_path.filename().string();
if (target_name == "." || target_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: invalid link filename")};
}
const std::filesystem::path parent =
link_path.parent_path().empty() ? std::filesystem::path{"."}
: link_path.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
std::string tmp_name;
bool created = false;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_lnk_{:016x}", target_name, detail::next_temp_entropy());
if (::symlinkat(target.c_str(), dir_fd.get(), tmp_name.c_str()) == 0) {
created = true;
break;
}
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(
"FileSystem::atomic_symlink_swap: symlinkat failed in '{}'",
parent.string()),
last_err)};
}
}
if (!created) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::atomic_symlink_swap: exhausted temporary link names",
last_err)};
}
bool cleanup = true;
struct CleanupGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~CleanupGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} cleanup_guard{dir_fd.get(), &tmp_name, &cleanup};
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
target_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: renameat failed for '{}'",
link_path.string()),
err)};
}
cleanup = false;
if (durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::atomic_symlink_swap: parent dir fsync failed for '{}'",
link_path.string()),
err)};
}
}
return {};
#else
(void)link_path;
(void)target;
(void)durability;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::atomic_symlink_swap: unsupported platform")};
#endif
}
enum class CopyMethod : std::uint8_t {
Reflink,
PrivateCopy,
};
struct CopyResult {
std::uint64_t bytes{0};
CopyMethod method{CopyMethod::PrivateCopy};
};
struct CopyOptions {
bool overwrite{true};
bool preserve_permissions{true};
ReplaceDurability durability{ReplaceDurability::atomic_visibility};
};
/// Copy a regular file using CoW reflink (`ioctl(FICLONE)`) with atomic
/// staging and private-copy fallback. Explicitly never creates hardlinks.
[[nodiscard]] inline Void::Result::Result<CopyResult, Void::Result::Error>
reflink_copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
CopyOptions options = {})
{
#ifndef _WIN32
if (src.empty() || dst.empty() || !dst.has_filename()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid source or destination path")};
}
const std::string dst_name = dst.filename().string();
if (dst_name == "." || dst_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid destination filename")};
}
const int raw_src = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
if (raw_src < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open '{}'",
src.string()),
err)};
}
Void::System::OwnedFd src_fd{raw_src};
struct stat src_st {};
if (::fstat(src_fd.get(), &src_st) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: fstat failed on '{}'",
src.string()),
err)};
}
if (!S_ISREG(src_st.st_mode)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("FileSystem::reflink_copy_file: '{}' is not a regular file",
src.string()))};
}
const std::filesystem::path parent =
dst.parent_path().empty() ? std::filesystem::path{"."}
: dst.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
const mode_t create_mode = options.preserve_permissions
? static_cast<mode_t>(src_st.st_mode & 0777)
: static_cast<mode_t>(0644);
std::string tmp_name;
Void::System::OwnedFd tmp_fd;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_cp_{:016x}", dst_name, detail::next_temp_entropy());
const int fd = ::openat(dir_fd.get(),
tmp_name.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
create_mode);
if (fd >= 0) {
tmp_fd.reset(fd);
break;
}
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("FileSystem::reflink_copy_file: create temp in '{}'",
parent.string()),
last_err)};
}
}
if (!tmp_fd.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::reflink_copy_file: exhausted temp names",
last_err)};
}
bool cleanup_tmp = true;
struct TempGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~TempGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_tmp};
CopyResult result;
result.bytes = static_cast<std::uint64_t>(src_st.st_size);
bool cloned = false;
#if defined(__linux__) && defined(FICLONE)
for (;;) {
if (::ioctl(tmp_fd.get(), FICLONE, src_fd.get()) == 0) {
cloned = true;
result.method = CopyMethod::Reflink;
break;
}
if (errno == EINTR) {
continue;
}
const int err = errno;
if (err == EOPNOTSUPP || err == EXDEV || err == EINVAL ||
err == ENOTTY || err == ENOSYS || err == EBADF || err == ETXTBSY
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
|| err == ENOTSUP
#endif
) {
break;
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: FICLONE failed for '{}'",
dst.string()),
err)};
}
#endif
if (!cloned) {
result.method = CopyMethod::PrivateCopy;
std::vector<char> buf(64ULL * 1024ULL);
std::uint64_t copied = 0;
for (;;) {
const ssize_t r = ::read(src_fd.get(), buf.data(), buf.size());
if (r > 0) {
std::size_t off = 0;
const auto ur = static_cast<std::size_t>(r);
while (off < ur) {
const ssize_t w =
::write(tmp_fd.get(), buf.data() + off, ur - off);
if (w < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: write failed for '{}'",
dst.string()),
err)};
}
off += static_cast<std::size_t>(w);
}
copied += ur;
} else if (r == 0) {
break;
} else {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: read failed on '{}'",
src.string()),
err)};
}
}
result.bytes = copied;
}
if (options.preserve_permissions) {
(void)::fchmod(tmp_fd.get(), create_mode);
}
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::sync_failed,
std::format("FileSystem::reflink_copy_file: fsync failed for '{}'",
dst.string()),
err)};
}
}
if (auto closed = tmp_fd.close(); !closed.has_value()) {
return std::unexpected{std::move(closed.error())};
}
if (options.overwrite) {
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: rename failed for '{}'",
dst.string()),
err)};
}
} else {
if (::linkat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str(),
0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: publish failed for '{}'",
dst.string()),
err)};
}
(void)::unlinkat(dir_fd.get(), tmp_name.c_str(), 0);
}
cleanup_tmp = false;
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::reflink_copy_file: parent fsync failed for '{}'",
dst.string()),
err)};
}
}
return result;
#else
(void)src;
(void)dst;
(void)options;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::reflink_copy_file: unsupported platform")};
#endif
}
/// Set access and modification timestamps without dereferencing symlinks.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_timestamps_nofollow(const std::filesystem::path& path,
std::int64_t atime_sec,
std::int32_t atime_nsec,
std::int64_t mtime_sec,
std::int32_t mtime_nsec)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: empty path")};
}
auto valid_nsec = [](std::int32_t ns) noexcept {
return (ns >= 0 && ns < 1'000'000'000) || ns == UTIME_NOW ||
ns == UTIME_OMIT;
};
if (!valid_nsec(atime_nsec) || !valid_nsec(mtime_nsec)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: nanoseconds out of range")};
}
struct timespec ts[2]{};
ts[0].tv_sec = static_cast<time_t>(atime_sec);
ts[0].tv_nsec = static_cast<long>(atime_nsec);
ts[1].tv_sec = static_cast<time_t>(mtime_sec);
ts[1].tv_nsec = static_cast<long>(mtime_nsec);
if (::utimensat(AT_FDCWD, path.c_str(), ts, AT_SYMLINK_NOFOLLOW) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::set_timestamps_nofollow: utimensat failed for '{}'",
path.string()),
err)};
}
return {};
#else
(void)path;
(void)atime_sec;
(void)atime_nsec;
(void)mtime_sec;
(void)mtime_nsec;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::set_timestamps_nofollow: unsupported platform")};
#endif
}
/// Set canonical modification and access timestamps (default UNIX epoch 0)
/// without following symlinks (`utimensat(..., AT_SYMLINK_NOFOLLOW)`).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::int64_t unix_seconds = 0,
std::int32_t nanoseconds = 0)
{
return set_timestamps_nofollow(
path, unix_seconds, nanoseconds, unix_seconds, nanoseconds);
}
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::chrono::sys_seconds tp)
{
return set_canonical_mtime(path, tp.time_since_epoch().count(), 0);
}
} // namespace Void::FileSystem } // namespace Void::FileSystem
+7
View File
@@ -116,6 +116,7 @@ public:
[[nodiscard]] bool valid() const noexcept; [[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept; [[nodiscard]] bool running() const noexcept;
[[nodiscard]] bool process_group_alive() const noexcept;
[[nodiscard]] long long pid() const noexcept; [[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept; [[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept; [[nodiscard]] bool owns_process_group() const noexcept;
@@ -201,4 +202,10 @@ private:
const std::vector<std::string>& arguments, const std::vector<std::string>& arguments,
bool close_extra_fds); 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
+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;
} }
+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
+326 -21
View File
@@ -1,6 +1,8 @@
#include <Void/Archive/Archive.hpp> #include <Void/Archive/Archive.hpp>
#include <Void/System/Process.hpp> #include <Void/System/Process.hpp>
#include "BuiltinTar.hpp"
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <atomic> #include <atomic>
@@ -18,8 +20,10 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
#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 <dirent.h> #include <dirent.h>
@@ -51,12 +55,14 @@ namespace Void::Archive
constexpr std::string_view kInventoryFilename = "inventory.txt"; constexpr std::string_view kInventoryFilename = "inventory.txt";
constexpr std::string_view kTreeSubdir = "tree"; constexpr std::string_view kTreeSubdir = "tree";
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using ArchiveReadPtr = using ArchiveReadPtr =
std::unique_ptr<archive, decltype(&archive_read_free)>; std::unique_ptr<archive, decltype(&archive_read_free)>;
using ArchiveWritePtr = using ArchiveWritePtr =
std::unique_ptr<archive, decltype(&archive_write_free)>; std::unique_ptr<archive, decltype(&archive_write_free)>;
using ArchiveEntryPtr = using ArchiveEntryPtr =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>; std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
#endif
class OwnedFd class OwnedFd
{ {
@@ -129,6 +135,7 @@ namespace Void::Archive
std::error_code{err, std::generic_category()}); std::error_code{err, std::generic_category()});
} }
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
[[nodiscard]] Void::Result::Error [[nodiscard]] Void::Result::Error
make_libarchive_error(archive* a, std::string_view op, make_libarchive_error(archive* a, std::string_view op,
ArchiveErrorCode fallback = ArchiveErrorCode fallback =
@@ -140,6 +147,7 @@ namespace Void::Archive
return make_archive_error(fallback, return make_archive_error(fallback,
std::format("Archive: {}: {}", op, detail)); std::format("Archive: {}: {}", op, detail));
} }
#endif
[[nodiscard]] bool is_safe_single_component( [[nodiscard]] bool is_safe_single_component(
std::string_view name, std::size_t max_bytes = 255) noexcept std::string_view name, std::size_t max_bytes = 255) noexcept
@@ -894,6 +902,15 @@ namespace Void::Archive
} }
} // namespace } // namespace
bool has_libarchive_backend() noexcept
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
return true;
#else
return false;
#endif
}
std::string sanitize_diagnostic_path(std::string_view raw) noexcept std::string sanitize_diagnostic_path(std::string_view raw) noexcept
{ {
std::string out; std::string out;
@@ -1088,10 +1105,14 @@ namespace Void::Archive
std::optional<Void::Time::MonotonicClock::time_point> deadline{}; std::optional<Void::Time::MonotonicClock::time_point> deadline{};
const Void::Time::MonotonicClock* clock{ const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()}; &Void::Time::SystemMonotonicClock::instance()};
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
ArchiveReadPtr handle{nullptr, &archive_read_free}; ArchiveReadPtr handle{nullptr, &archive_read_free};
std::vector<std::byte> read_buf{}; std::vector<std::byte> read_buf{};
PathTracker tracker;
std::optional<Void::Result::Error> source_error{}; std::optional<Void::Result::Error> source_error{};
#endif
std::unique_ptr<Detail::BuiltinTarStream> builtin_stream{};
bool using_builtin{false};
PathTracker tracker;
bool has_active_file{false}; bool has_active_file{false};
bool reached_eof{false}; bool reached_eof{false};
bool poisoned{false}; bool poisoned{false};
@@ -1101,7 +1122,10 @@ namespace Void::Archive
std::uint64_t total_compressed{0}; std::uint64_t total_compressed{0};
explicit Impl(const ReadLimits& lim) explicit Impl(const ReadLimits& lim)
: limits(lim), read_buf(lim.transfer_buffer_bytes), : limits(lim),
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
read_buf(lim.transfer_buffer_bytes),
#endif
tracker(lim.max_metadata_bytes) tracker(lim.max_metadata_bytes)
{ {
} }
@@ -1121,6 +1145,7 @@ namespace Void::Archive
return {}; return {};
} }
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
static la_ssize_t libarchive_read_cb(archive* a, void* client_data, static la_ssize_t libarchive_read_cb(archive* a, void* client_data,
const void** buffer) const void** buffer)
{ {
@@ -1150,6 +1175,7 @@ namespace Void::Archive
*buffer = self->read_buf.data(); *buffer = self->read_buf.data();
return static_cast<la_ssize_t>(n); return static_cast<la_ssize_t>(n);
} }
#endif
}; };
Reader::Reader(std::unique_ptr<Impl> impl) noexcept Reader::Reader(std::unique_ptr<Impl> impl) noexcept
@@ -1178,6 +1204,7 @@ namespace Void::Archive
return std::unexpected{std::move(chk.error())}; return std::unexpected{std::move(chk.error())};
} }
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
impl->handle = impl->handle =
ArchiveReadPtr{archive_read_new(), &archive_read_free}; ArchiveReadPtr{archive_read_new(), &archive_read_free};
if (!impl->handle) { if (!impl->handle) {
@@ -1185,6 +1212,7 @@ namespace Void::Archive
ArchiveErrorCode::io_error, ArchiveErrorCode::io_error,
"Archive::Reader: cannot allocate libarchive reader")}; "Archive::Reader: cannot allocate libarchive reader")};
} }
(void)archive_read_support_filter_gzip(impl->handle.get());
(void)archive_read_support_filter_zstd(impl->handle.get()); (void)archive_read_support_filter_zstd(impl->handle.get());
(void)archive_read_support_filter_none(impl->handle.get()); (void)archive_read_support_filter_none(impl->handle.get());
(void)archive_read_support_format_tar(impl->handle.get()); (void)archive_read_support_format_tar(impl->handle.get());
@@ -1199,6 +1227,16 @@ namespace Void::Archive
impl->handle.get(), "open archive", impl->handle.get(), "open archive",
ArchiveErrorCode::unsupported_format)}; ArchiveErrorCode::unsupported_format)};
} }
impl->using_builtin = false;
#else
impl->builtin_stream = std::make_unique<Detail::BuiltinTarStream>(
source, limits, stop, deadline, clock);
if (auto opened = impl->builtin_stream->open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
impl->total_compressed = impl->builtin_stream->total_compressed_bytes();
impl->using_builtin = true;
#endif
return Reader{std::move(impl)}; return Reader{std::move(impl)};
} }
@@ -1242,6 +1280,91 @@ namespace Void::Archive
return std::unexpected{std::move(chk.error())}; return std::unexpected{std::move(chk.error())};
} }
if (m_impl->using_builtin) {
auto next = m_impl->builtin_stream->next_entry();
m_impl->total_compressed =
m_impl->builtin_stream->total_compressed_bytes();
if (!next.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
m_impl->reached_eof = true;
return std::optional<EntryInfo>{std::nullopt};
}
if (m_impl->entries_seen >= m_impl->limits.max_entries) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: entry count exceeds limit")};
}
++m_impl->entries_seen;
const auto& raw = **next;
if (raw.path.empty()) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
"Archive::Reader: entry has no pathname")};
}
if (raw.type == EntryType::Hardlink ||
raw.type == EntryType::Symlink || !raw.linkname.empty()) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
std::format("Archive::Reader: links are not allowed ('{}')",
sanitize_diagnostic_path(raw.path)))};
}
if (raw.type != EntryType::Directory &&
raw.type != EntryType::RegularFile) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
std::format("Archive::Reader: special files are not allowed "
"('{}')",
sanitize_diagnostic_path(raw.path)))};
}
const bool is_dir = (raw.type == EntryType::Directory);
auto vp = validate_archive_path(raw.path, is_dir, m_impl->limits);
if (!vp.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(vp.error())};
}
if (auto rec = m_impl->tracker.record(*vp, is_dir);
!rec.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(rec.error())};
}
std::uint64_t declared_size = 0;
bool executable = false;
if (!is_dir) {
declared_size = raw.declared_size;
if (declared_size > m_impl->limits.max_file_bytes ||
declared_size > m_impl->limits.max_total_bytes -
m_impl->total_decompressed) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: declared entry size exceeds policy")};
}
executable = (raw.mode & 0111U) != 0U;
m_impl->has_active_file = true;
m_impl->entry_bytes_read = 0;
}
return std::optional<EntryInfo>{EntryInfo{
.path = std::move(vp->normalized),
.type = is_dir ? EntryType::Directory : EntryType::RegularFile,
.declared_size = declared_size,
.safe_mode = is_dir ? 0755U : (executable ? 0755U : 0644U),
.executable = executable,
.accepted = true,
}};
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
archive_entry* entry = nullptr; archive_entry* entry = nullptr;
const int status = const int status =
archive_read_next_header(m_impl->handle.get(), &entry); archive_read_next_header(m_impl->handle.get(), &entry);
@@ -1335,6 +1458,12 @@ namespace Void::Archive
.executable = executable, .executable = executable,
.accepted = true, .accepted = true,
}}; }};
#else
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: libarchive backend unavailable")};
#endif
} }
Void::Result::Result<std::size_t> Void::Result::Result<std::size_t>
@@ -1358,21 +1487,46 @@ namespace Void::Archive
const std::size_t to_read = const std::size_t to_read =
std::min(dst.size(), m_impl->limits.transfer_buffer_bytes); std::min(dst.size(), m_impl->limits.transfer_buffer_bytes);
const la_ssize_t n = std::size_t read_bytes = 0;
archive_read_data(m_impl->handle.get(), dst.data(), to_read); if (m_impl->using_builtin) {
if (n == 0) { auto r =
m_impl->has_active_file = false; m_impl->builtin_stream->read_entry_data(dst.subspan(0, to_read));
return std::size_t{0}; m_impl->total_compressed =
} m_impl->builtin_stream->total_compressed_bytes();
if (n < 0) { if (!r.has_value()) {
m_impl->poisoned = true; m_impl->poisoned = true;
if (m_impl->source_error.has_value()) { return std::unexpected{std::move(r.error())};
return std::unexpected{std::move(*m_impl->source_error)};
} }
return std::unexpected{ read_bytes = *r;
make_libarchive_error(m_impl->handle.get(), "read entry data")}; if (read_bytes == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
} else {
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
const la_ssize_t n =
archive_read_data(m_impl->handle.get(), dst.data(), to_read);
if (n == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
if (n < 0) {
m_impl->poisoned = true;
if (m_impl->source_error.has_value()) {
return std::unexpected{std::move(*m_impl->source_error)};
}
return std::unexpected{make_libarchive_error(
m_impl->handle.get(), "read entry data")};
}
read_bytes = static_cast<std::size_t>(n);
#else
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: libarchive backend unavailable")};
#endif
} }
const auto amount = static_cast<std::uint64_t>(n); const auto amount = static_cast<std::uint64_t>(read_bytes);
if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read || if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read ||
amount > m_impl->limits.max_total_bytes - amount > m_impl->limits.max_total_bytes -
m_impl->total_decompressed) { m_impl->total_decompressed) {
@@ -1383,7 +1537,7 @@ namespace Void::Archive
} }
m_impl->entry_bytes_read += amount; m_impl->entry_bytes_read += amount;
m_impl->total_decompressed += amount; m_impl->total_decompressed += amount;
return static_cast<std::size_t>(n); return read_bytes;
} }
Void::Result::Result<std::uint64_t> Reader::skip_entry() Void::Result::Result<std::uint64_t> Reader::skip_entry()
@@ -1462,6 +1616,7 @@ namespace Void::Archive
} }
// Opt-in forensic listing: reports rejected entries without writing. // Opt-in forensic listing: reports rejected entries without writing.
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
struct ForensicState { struct ForensicState {
ByteSource* source{nullptr}; ByteSource* source{nullptr};
ReadLimits limits{}; ReadLimits limits{};
@@ -1477,6 +1632,7 @@ namespace Void::Archive
ArchiveErrorCode::io_error, ArchiveErrorCode::io_error,
"Archive::list_entries: cannot allocate reader")}; "Archive::list_entries: cannot allocate reader")};
} }
(void)archive_read_support_filter_gzip(handle.get());
(void)archive_read_support_filter_zstd(handle.get()); (void)archive_read_support_filter_zstd(handle.get());
(void)archive_read_support_filter_none(handle.get()); (void)archive_read_support_filter_none(handle.get());
(void)archive_read_support_format_tar(handle.get()); (void)archive_read_support_format_tar(handle.get());
@@ -1592,6 +1748,88 @@ namespace Void::Archive
(void)archive_read_data_skip(handle.get()); (void)archive_read_data_skip(handle.get());
} }
return out; return out;
#else
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())};
}
std::vector<EntryInfo> out;
PathTracker tracker{limits.max_metadata_bytes};
std::size_t metadata_bytes = 0;
for (;;) {
auto next = stream.next_entry();
if (!next.has_value()) {
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
break;
}
if (out.size() >= limits.max_entries) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::list_entries: entry count exceeds limit")};
}
const auto& raw = **next;
const std::string sanitized =
raw.path.empty() ? "<missing>"
: sanitize_diagnostic_path(raw.path);
if (sanitized.size() + 64U > limits.max_metadata_bytes ||
metadata_bytes >
limits.max_metadata_bytes - (sanitized.size() + 64U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::list_entries: metadata limit exceeded")};
}
metadata_bytes += sanitized.size() + 64U;
EntryInfo info;
info.path = sanitized;
if (raw.type == EntryType::Hardlink) {
info.type = EntryType::Hardlink;
info.accepted = false;
info.rejection_reason = "hardlink disallowed";
} else if (raw.type == EntryType::Symlink ||
!raw.linkname.empty()) {
info.type = EntryType::Symlink;
info.accepted = false;
info.rejection_reason = "symlink disallowed";
} else if (raw.type != EntryType::Directory &&
raw.type != EntryType::RegularFile) {
info.type = EntryType::Other;
info.accepted = false;
info.rejection_reason = "special file disallowed";
} else {
const bool is_dir = (raw.type == EntryType::Directory);
info.type =
is_dir ? EntryType::Directory : EntryType::RegularFile;
info.declared_size = raw.declared_size;
info.executable = !is_dir && ((raw.mode & 0111U) != 0U);
info.safe_mode =
is_dir ? 0755U : (info.executable ? 0755U : 0644U);
auto vp = validate_archive_path(raw.path, is_dir, limits);
if (!vp.has_value()) {
info.accepted = false;
info.rejection_reason = vp.error().message();
} else if (auto rec = tracker.record(*vp, is_dir);
!rec.has_value()) {
info.accepted = false;
info.rejection_reason = rec.error().message();
} else {
info.path = std::move(vp->normalized);
info.accepted = true;
}
}
out.push_back(std::move(info));
if (auto sk = stream.skip_entry_data(); !sk.has_value()) {
return std::unexpected{std::move(sk.error())};
}
}
return out;
#endif
} }
Void::Result::Result<std::vector<EntryInfo>> Void::Result::Result<std::vector<EntryInfo>>
@@ -2314,6 +2552,30 @@ namespace Void::Archive
return a.path < b.path; return a.path < b.path;
}); });
if (options.compression == ArchiveCompression::None &&
(options.prefer_builtin_tar || !has_libarchive_backend())) {
std::vector<Detail::BuiltinCreateItem> builtin_items;
builtin_items.reserve(normalized.size());
for (const auto& item : normalized) {
const bool is_dir = (item.src->type == EntryType::Directory);
const std::uint32_t perm =
item.src->mode.has_value()
? (*item.src->mode & 0777U)
: (is_dir ? 0755U
: (item.src->executable ? 0755U : 0644U));
builtin_items.push_back(Detail::BuiltinCreateItem{
.path = item.path,
.is_directory = is_dir,
.mode = perm,
.size = item.size,
.inline_content = item.src->content,
.source_fd = item.file_fd.get(),
});
}
return Detail::write_builtin_tar(sink, builtin_items, options);
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
struct SinkBridge { struct SinkBridge {
ByteSink* sink{nullptr}; ByteSink* sink{nullptr};
std::optional<Void::Result::Error> err{}; std::optional<Void::Result::Error> err{};
@@ -2331,6 +2593,19 @@ namespace Void::Archive
return std::unexpected{ return std::unexpected{
make_libarchive_error(writer.get(), "add zstd filter")}; make_libarchive_error(writer.get(), "add zstd filter")};
} }
} else if (options.compression == ArchiveCompression::Gzip) {
if (archive_write_add_filter_gzip(writer.get()) != ARCHIVE_OK) {
return std::unexpected{
make_libarchive_error(writer.get(), "add gzip filter")};
}
if (options.reproducible) {
if (archive_write_set_filter_option(
writer.get(), "gzip", "timestamp", nullptr) !=
ARCHIVE_OK) {
return std::unexpected{make_libarchive_error(
writer.get(), "disable gzip timestamp header")};
}
}
} else { } else {
if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) { if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) {
return std::unexpected{ return std::unexpected{
@@ -2380,14 +2655,24 @@ namespace Void::Archive
const bool is_dir = (item.src->type == EntryType::Directory); const bool is_dir = (item.src->type == EntryType::Directory);
const std::string wire_path = const std::string wire_path =
is_dir ? (item.path + "/") : item.path; is_dir ? (item.path + "/") : item.path;
const std::uint32_t perm =
item.src->mode.has_value()
? (*item.src->mode & 0777U)
: (is_dir ? 0755U
: (item.src->executable ? 0755U : 0644U));
archive_entry_set_pathname(ae.get(), wire_path.c_str()); archive_entry_set_pathname(ae.get(), wire_path.c_str());
archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG); archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG);
archive_entry_set_perm( archive_entry_set_perm(ae.get(), static_cast<mode_t>(perm));
ae.get(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644));
if (options.reproducible) { if (options.reproducible) {
archive_entry_set_mtime(ae.get(), 0, 0); archive_entry_set_mtime(
archive_entry_set_uid(ae.get(), 0); ae.get(),
archive_entry_set_gid(ae.get(), 0); static_cast<std::time_t>(
std::max<std::int64_t>(0, options.canonical_mtime)),
0);
archive_entry_set_uid(
ae.get(), static_cast<la_int64_t>(options.canonical_uid));
archive_entry_set_gid(
ae.get(), static_cast<la_int64_t>(options.canonical_gid));
archive_entry_set_uname(ae.get(), ""); archive_entry_set_uname(ae.get(), "");
archive_entry_set_gname(ae.get(), ""); archive_entry_set_gname(ae.get(), "");
} }
@@ -2473,6 +2758,12 @@ namespace Void::Archive
make_libarchive_error(writer.get(), "close archive writer")}; make_libarchive_error(writer.get(), "close archive writer")};
} }
return {}; return {};
#else
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::create_archive: compressed archives require "
"LibArchive backend")};
#endif
} }
Void::Result::Result<void> Void::Result::Result<void>
@@ -2491,6 +2782,20 @@ namespace Void::Archive
return sink->sync_and_close(); return sink->sync_and_close();
} }
Void::Result::Result<void> create(ByteSink& sink,
std::span<const CreateEntry> entries,
const CreationOptions& options)
{
return create_archive(sink, entries, options);
}
Void::Result::Result<void> create(const std::filesystem::path& output_path,
std::span<const CreateEntry> entries,
const CreationOptions& options)
{
return create_archive(output_path, entries, options);
}
// ── Isolated Child Decoder Profile ─────────────────────────────────────── // ── Isolated Child Decoder Profile ───────────────────────────────────────
Void::Result::Result<StagedTree> Void::Result::Result<StagedTree>
+16 -1
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 Time System 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}
) )
+275 -76
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";
} }
} }
+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
+297 -24
View File
@@ -1,19 +1,24 @@
#include <Void/Crypto/Crypto.hpp> #include <Void/Crypto/Crypto.hpp>
#include "BuiltinHash.hpp"
#include <array> #include <array>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <format> #include <format>
#include <fstream> #include <fstream>
#include <limits> #include <limits>
#include <optional>
#include <utility> #include <utility>
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
#include <openssl/core_names.h> #include <openssl/core_names.h>
#include <openssl/crypto.h> #include <openssl/crypto.h>
#include <openssl/err.h> #include <openssl/err.h>
#include <openssl/evp.h> #include <openssl/evp.h>
#include <openssl/kdf.h> #include <openssl/kdf.h>
#include <openssl/params.h> #include <openssl/params.h>
#endif
namespace Void::Crypto namespace Void::Crypto
{ {
@@ -42,6 +47,36 @@ namespace Void::Crypto
std::format("{}: injected crypto backend fault", operation)); std::format("{}: injected crypto backend fault", operation));
} }
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
[[nodiscard]] bool use_builtin_hash(
HashAlgorithm algorithm, const ProviderOptions& provider) noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin ||
algorithm == HashAlgorithm::Blake2b256) {
return true;
}
return false;
#else
(void)algorithm;
(void)provider;
return true;
#endif
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
[[nodiscard]] const char* [[nodiscard]] const char*
algorithm_name(HashAlgorithm algorithm) noexcept algorithm_name(HashAlgorithm algorithm) noexcept
{ {
@@ -52,6 +87,10 @@ namespace Void::Crypto
return "SHA256"; return "SHA256";
case HashAlgorithm::Sha512: case HashAlgorithm::Sha512:
return "SHA512"; return "SHA512";
case HashAlgorithm::Blake2b256:
return nullptr;
case HashAlgorithm::Blake2b512:
return "BLAKE2B512";
} }
return nullptr; return nullptr;
} }
@@ -78,19 +117,6 @@ namespace Void::Crypto
code, std::format("{}: {}", operation, buffer.data())); code, std::format("{}: {}", operation, buffer.data()));
} }
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>; using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>;
using EvpMdCtxPtr = using EvpMdCtxPtr =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>; std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
@@ -110,6 +136,7 @@ namespace Void::Crypto
? &kEmptyByte ? &kEmptyByte
: reinterpret_cast<const unsigned char*>(span.data()); : reinterpret_cast<const unsigned char*>(span.data());
} }
#endif
[[nodiscard]] Void::Result::Result<bool> [[nodiscard]] Void::Result::Result<bool>
verify_ed25519_impl(std::span<const std::byte> message, verify_ed25519_impl(std::span<const std::byte> message,
@@ -144,6 +171,12 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: Ed25519 requires OpenSSL backend")};
}
ERR_clear_error(); ERR_clear_error();
const char* propq = propq_or_null(provider); const char* propq = propq_or_null(provider);
EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex( EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex(
@@ -182,14 +215,33 @@ namespace Void::Crypto
} }
ERR_clear_error(); ERR_clear_error();
return result == 1; return result == 1;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: built without OpenSSL backend")};
#endif
} }
} // namespace } // namespace
bool has_openssl_backend() noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return true;
#else
return false;
#endif
}
void secure_wipe(std::span<std::byte> buffer) noexcept void secure_wipe(std::span<std::byte> buffer) noexcept
{ {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!buffer.empty()) { if (!buffer.empty()) {
OPENSSL_cleanse(buffer.data(), buffer.size()); OPENSSL_cleanse(buffer.data(), buffer.size());
} }
#else
Detail::builtin_secure_wipe(buffer);
#endif
} }
bool constant_time_equal(std::span<const std::byte> lhs, bool constant_time_equal(std::span<const std::byte> lhs,
@@ -201,7 +253,11 @@ namespace Void::Crypto
if (lhs.empty()) { if (lhs.empty()) {
return true; return true;
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
#else
return Detail::builtin_constant_time_equal(lhs, rhs);
#endif
} }
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
@@ -218,8 +274,12 @@ namespace Void::Crypto
} }
struct Hasher::Impl { struct Hasher::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free}; EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
EvpMdPtr algorithm{nullptr, &EVP_MD_free}; EvpMdPtr algorithm{nullptr, &EVP_MD_free};
#endif
Detail::BuiltinHasher builtin{};
bool using_builtin{false};
HasherState state{HasherState::Ready}; HasherState state{HasherState::Ready};
}; };
@@ -244,18 +304,50 @@ namespace Void::Crypto
Void::Result::Result<Hasher> Void::Result::Result<Hasher>
Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider) Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider)
{ {
const char* md_name = algorithm_name(algorithm); switch (algorithm) {
if (md_name == nullptr) { case HashAlgorithm::Sha1:
return std::unexpected{make_crypto_error( case HashAlgorithm::Sha256:
CryptoErrorCode::unsupported_algorithm, case HashAlgorithm::Sha512:
"Crypto::Hasher: unsupported algorithm")}; case HashAlgorithm::Blake2b256:
case HashAlgorithm::Blake2b512:
break;
default:
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported algorithm")};
} }
if (auto fault = maybe_inject_fault(FaultOperation::hash_create, if (auto fault = maybe_inject_fault(FaultOperation::hash_create,
"Crypto::Hasher::create"); "Crypto::Hasher::create");
fault.has_value()) { fault.has_value()) {
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (use_builtin_hash(algorithm, provider)) {
if (!provider.property_query.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: property_query unavailable on built-in "
"backend")};
}
auto impl = std::make_unique<Impl>();
if (!impl->builtin.init(algorithm)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: built-in initialization failed")};
}
impl->using_builtin = true;
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const char* md_name = algorithm_name(algorithm);
if (md_name == nullptr) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported OpenSSL digest algorithm")};
}
ERR_clear_error(); ERR_clear_error();
auto impl = std::make_unique<Impl>(); auto impl = std::make_unique<Impl>();
impl->algorithm = EvpMdPtr{ impl->algorithm = EvpMdPtr{
@@ -278,8 +370,14 @@ namespace Void::Crypto
CryptoErrorCode::provider_error, CryptoErrorCode::provider_error,
"Crypto::Hasher: digest initialization failed")}; "Crypto::Hasher: digest initialization failed")};
} }
impl->using_builtin = false;
impl->state = HasherState::Ready; impl->state = HasherState::Ready;
return Hasher{std::move(impl)}; return Hasher{std::move(impl)};
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: OpenSSL backend unavailable")};
#endif
} }
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data) Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
@@ -301,6 +399,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Failed; m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (m_impl->using_builtin) {
m_impl->builtin.update(data);
m_impl->state = HasherState::Updating;
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!data.empty() && if (!data.empty() &&
EVP_DigestUpdate(m_impl->context.get(), data.data(), EVP_DigestUpdate(m_impl->context.get(), data.data(),
data.size()) != 1) { data.size()) != 1) {
@@ -311,6 +415,12 @@ namespace Void::Crypto
} }
m_impl->state = HasherState::Updating; m_impl->state = HasherState::Updating;
return {}; return {};
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::update: invalid backend")};
#endif
} }
Void::Result::Result<void> Hasher::update(std::string_view data) Void::Result::Result<void> Hasher::update(std::string_view data)
@@ -337,6 +447,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Failed; m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (m_impl->using_builtin) {
Digest digest = m_impl->builtin.finalize();
m_impl->state = HasherState::Finalized;
return digest;
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get()); const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
if (digest_size <= 0) { if (digest_size <= 0) {
m_impl->state = HasherState::Failed; m_impl->state = HasherState::Failed;
@@ -357,6 +473,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Finalized; m_impl->state = HasherState::Finalized;
digest.resize(written); digest.resize(written);
return digest; return digest;
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid backend")};
#endif
} }
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data) auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
@@ -388,18 +510,31 @@ namespace Void::Crypto
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path) auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest> -> Void::Result::Result<Digest>
{ {
return hashFile(algorithm, path, ProviderOptions{}); return hash_file(algorithm, path, ProviderOptions{});
} }
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider) const ProviderOptions& provider)
-> Void::Result::Result<Digest> -> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, provider);
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, ProviderOptions{});
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{ {
std::ifstream input{path, std::ios::binary}; std::ifstream input{path, std::ios::binary};
if (!input.is_open()) { if (!input.is_open()) {
return std::unexpected{make_crypto_error( return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error, CryptoErrorCode::io_error,
std::format("Crypto::hashFile: cannot open '{}'", std::format("Crypto::hash_file: cannot open '{}'",
path.string()))}; path.string()))};
} }
auto hasher = Hasher::create(algorithm, provider); auto hasher = Hasher::create(algorithm, provider);
@@ -422,7 +557,7 @@ namespace Void::Crypto
if (input.bad() || (!input.eof() && input.fail())) { if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error( return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error, CryptoErrorCode::io_error,
std::format("Crypto::hashFile: I/O error reading '{}'", std::format("Crypto::hash_file: I/O error reading '{}'",
path.string()))}; path.string()))};
} }
return hasher->finalize(); return hasher->finalize();
@@ -452,21 +587,63 @@ namespace Void::Crypto
{ {
return hash(HashAlgorithm::Sha512, data); return hash(HashAlgorithm::Sha512, data);
} }
Void::Result::Result<Digest> blake2b256(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b256(std::string_view data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b512(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> blake2b512(std::string_view data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path) Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
{ {
return hashFile(HashAlgorithm::Sha1, path); return hash_file(HashAlgorithm::Sha1, path);
} }
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path) Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
{ {
return hashFile(HashAlgorithm::Sha256, path); return hash_file(HashAlgorithm::Sha256, path);
} }
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path) Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
{ {
return hashFile(HashAlgorithm::Sha512, path); return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest> sha1_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha1, path);
}
Void::Result::Result<Digest> sha256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha256, path);
}
Void::Result::Result<Digest> sha512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest>
blake2b256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b256, path);
}
Void::Result::Result<Digest>
blake2b512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b512, path);
} }
struct Ed25519PrivateKey::Impl { struct Ed25519PrivateKey::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free}; EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
#else
std::uint8_t unused{0};
#endif
}; };
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
@@ -481,7 +658,11 @@ namespace Void::Crypto
bool Ed25519PrivateKey::valid() const noexcept bool Ed25519PrivateKey::valid() const noexcept
{ {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return m_impl != nullptr && m_impl->pkey != nullptr; return m_impl != nullptr && m_impl->pkey != nullptr;
#else
return false;
#endif
} }
Void::Result::Result<Ed25519PrivateKey> Void::Result::Result<Ed25519PrivateKey>
@@ -492,6 +673,12 @@ namespace Void::Crypto
fault.has_value()) { fault.has_value()) {
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate requires OpenSSL backend")};
}
ERR_clear_error(); ERR_clear_error();
EvpPkeyPtr key{ EvpPkeyPtr key{
EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"), EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"),
@@ -504,6 +691,13 @@ namespace Void::Crypto
auto impl = std::make_unique<Impl>(); auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key); impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)}; return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519PrivateKey> Void::Result::Result<Ed25519PrivateKey>
@@ -523,6 +717,13 @@ namespace Void::Crypto
fault.has_value()) { fault.has_value()) {
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed requires OpenSSL "
"backend")};
}
ERR_clear_error(); ERR_clear_error();
EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex( EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex(
nullptr, "ED25519", propq_or_null(provider), nullptr, "ED25519", propq_or_null(provider),
@@ -536,6 +737,13 @@ namespace Void::Crypto
auto impl = std::make_unique<Impl>(); auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key); impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)}; return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
@@ -546,6 +754,7 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from " "Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
"key")}; "key")};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
Ed25519PublicKey pub; Ed25519PublicKey pub;
std::size_t len = pub.bytes.size(); std::size_t len = pub.bytes.size();
if (EVP_PKEY_get_raw_public_key( if (EVP_PKEY_get_raw_public_key(
@@ -558,6 +767,12 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::public_key failed")}; "Crypto::Ed25519PrivateKey::public_key failed")};
} }
return pub; return pub;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::public_key: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const
@@ -568,6 +783,7 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::export_raw_seed: invalid or " "Crypto::Ed25519PrivateKey::export_raw_seed: invalid or "
"moved-from key")}; "moved-from key")};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
std::array<std::byte, Ed25519SeedSize> raw{}; std::array<std::byte, Ed25519SeedSize> raw{};
std::size_t len = raw.size(); std::size_t len = raw.size();
if (EVP_PKEY_get_raw_private_key( if (EVP_PKEY_get_raw_private_key(
@@ -582,6 +798,12 @@ namespace Void::Crypto
auto result = Ed25519Seed::from_bytes(raw); auto result = Ed25519Seed::from_bytes(raw);
secure_wipe(raw); secure_wipe(raw);
return result; return result;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::export_raw_seed: built without OpenSSL "
"backend")};
#endif
} }
Void::Result::Result<Ed25519Signature> Void::Result::Result<Ed25519Signature>
@@ -607,6 +829,12 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519 requires OpenSSL backend")};
}
ERR_clear_error(); ERR_clear_error();
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) { if (!context) {
@@ -635,6 +863,12 @@ namespace Void::Crypto
"Crypto::sign_ed25519 failed")}; "Crypto::sign_ed25519 failed")};
} }
return signature; return signature;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519: built without OpenSSL backend")};
#endif
} }
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message, Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
@@ -682,6 +916,19 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hmac_sha256(secret_key, message, output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error(); ERR_clear_error();
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)), EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
&EVP_MAC_free}; &EVP_MAC_free};
@@ -732,6 +979,12 @@ namespace Void::Crypto
"Crypto::hmac_sha256_into: EVP_MAC_final failed")}; "Crypto::hmac_sha256_into: EVP_MAC_final failed")};
} }
return {}; return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
#endif
} }
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key, Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
@@ -780,6 +1033,20 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)}; return std::unexpected{std::move(*fault)};
} }
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hkdf_sha256: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hkdf_sha256(secret_input, salt, context,
secret_output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error(); ERR_clear_error();
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)), EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)),
&EVP_KDF_free}; &EVP_KDF_free};
@@ -825,6 +1092,12 @@ namespace Void::Crypto
"Crypto::hkdf_sha256: EVP_KDF_derive failed")}; "Crypto::hkdf_sha256: EVP_KDF_derive failed")};
} }
return {}; return {};
#else
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: OpenSSL backend unavailable")};
#endif
} }
} // namespace Void::Crypto } // namespace Void::Crypto
+16 -1
View File
@@ -1,6 +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 EXCLUDE_HEADERS
Void/Crypto/AsyncHash.hpp Void/Crypto/AsyncHash.hpp
) )
target_compile_definitions(Void_Crypto PUBLIC
VOID_CRYPTO_HAS_OPENSSL=${_void_crypto_has_openssl}
)
+361 -40
View File
@@ -1,22 +1,152 @@
#include <Void/Fsm/Detail/Engine.hpp> #include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm> #include <algorithm>
#include <utility> #include <utility>
namespace Void::Fsm::Detail namespace Void::Fsm::Detail
{ {
namespace
{
Coro::Task<void> external_pump_task(
std::weak_ptr<ExecutionContext> weak_ctx)
{
if (auto ctx = weak_ctx.lock()) {
ctx->run_external_pump_step();
}
co_return;
}
} // namespace
// Default state lifecycle hooks (no-ops). The state's behaviour is driven
// by a per-state, signature-inferred thunk built at registration.
Coro::Task<void> StateBase::on_enter() { co_return; } Coro::Task<void> StateBase::on_enter() { co_return; }
Coro::Task<void> StateBase::on_exit() { co_return; } Coro::Task<void> StateBase::on_exit() { co_return; }
ExecutionContext::ExecutionContext(const Time::MonotonicClock* clock,
FsmLimits limits,
Async::Executor* external_executor)
: m_clock(clock != nullptr ? clock
: &Time::SystemMonotonicClock::instance()),
m_limits(limits), m_external_executor(external_executor)
{
}
ExecutionContext::~ExecutionContext() { stop(); } ExecutionContext::~ExecutionContext() { stop(); }
bool ExecutionContext::try_acquire_child_regions(std::size_t count) noexcept
{
if (count == 0) {
return true;
}
std::size_t cur =
m_active_child_regions.load(std::memory_order_acquire);
for (;;) {
if (count > m_limits.max_child_regions ||
cur > m_limits.max_child_regions - count) {
return false;
}
if (m_active_child_regions.compare_exchange_weak(
cur, cur + count, std::memory_order_acq_rel,
std::memory_order_acquire)) {
return true;
}
}
}
void ExecutionContext::release_child_regions(std::size_t count) noexcept
{
if (count == 0) {
return;
}
m_active_child_regions.fetch_sub(count, std::memory_order_acq_rel);
}
Void::Result::Result<void> ExecutionContext::try_post(EventEnvelope env)
{
if (m_done.load(std::memory_order_acquire)) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"ExecutionContext::try_post: context stopped"));
}
const std::size_t bytes = env.bytes;
std::size_t cur_ev = m_queued_events.load(std::memory_order_acquire);
for (;;) {
if (m_limits.max_mailbox_events > 0 &&
cur_ev >= m_limits.max_mailbox_events) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::overloaded,
"ExecutionContext::try_post: mailbox event limit reached"));
}
if (m_queued_events.compare_exchange_weak(
cur_ev, cur_ev + 1, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
std::size_t cur_bytes = m_queued_bytes.load(std::memory_order_acquire);
for (;;) {
if (m_limits.max_mailbox_bytes > 0 &&
(bytes > m_limits.max_mailbox_bytes ||
cur_bytes > m_limits.max_mailbox_bytes - bytes)) {
m_queued_events.fetch_sub(1, std::memory_order_acq_rel);
return Void::Result::fail(make_fsm_error(
FsmErrorCode::overloaded,
"ExecutionContext::try_post: mailbox byte limit reached"));
}
if (m_queued_bytes.compare_exchange_weak(
cur_bytes, cur_bytes + bytes, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
m_queue.push(std::move(env));
wake();
return {};
}
void ExecutionContext::post(EventEnvelope env) void ExecutionContext::post(EventEnvelope env)
{ {
m_queue.push(std::move(env)); auto r = try_post(std::move(env));
if (!r) {
Void::Log::warn("Fsm", "dropped user event: {}",
r.error().message());
}
}
Void::Result::Result<void>
ExecutionContext::try_post_control(std::function<void()> fn)
{
if (!fn) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_argument,
"ExecutionContext::try_post_control: empty callback"));
}
if (m_done.load(std::memory_order_acquire)) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"ExecutionContext::try_post_control: context stopped"));
}
std::size_t cur = m_queued_control.load(std::memory_order_acquire);
for (;;) {
if (m_limits.max_control_messages > 0 &&
cur >= m_limits.max_control_messages) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::overloaded,
"ExecutionContext::try_post_control: control lane limit reached"));
}
if (m_queued_control.compare_exchange_weak(
cur, cur + 1, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
m_control_queue.push(std::move(fn));
wake(); wake();
return {};
} }
bool ExecutionContext::try_take_any( bool ExecutionContext::try_take_any(
@@ -26,57 +156,170 @@ namespace Void::Fsm::Detail
const auto it = m_buffers.find(std::type_index{*ty}); const auto it = m_buffers.find(std::type_index{*ty});
if (it != m_buffers.end() && !it->second.empty()) { if (it != m_buffers.end() && !it->second.empty()) {
out.type = ty; out.type = ty;
out.value = std::move(it->second.front()); out.bytes = it->second.front().bytes;
out.value = std::move(it->second.front().value);
it->second.pop_front(); it->second.pop_front();
if (m_buffered_events > 0) {
--m_buffered_events;
}
m_buffered_bytes -= std::min(m_buffered_bytes, out.bytes);
return true; return true;
} }
} }
return false; return false;
} }
void ExecutionContext::set_waiter( ExecutionContext::WaiterId ExecutionContext::set_waiter(
std::span<const std::type_info* const> types, std::span<const std::type_info* const> types,
std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out, std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out,
std::optional<std::chrono::steady_clock::time_point> deadline) std::optional<Time::MonotonicClock::time_point> deadline,
ScopeId scope, bool* cancelled)
{ {
Waiter w; Waiter w;
w.id = m_next_waiter++; w.id = m_next_waiter++;
w.scope = scope;
w.types.assign(types.begin(), types.end()); w.types.assign(types.begin(), types.end());
w.cont = cont; w.cont = cont;
w.slot = slot; w.slot = slot;
w.timed_out = timed_out; w.timed_out = timed_out;
w.cancelled = cancelled;
w.timer = 0; w.timer = 0;
if (deadline.has_value()) { if (deadline.has_value()) {
const WaiterId id = w.id; const WaiterId id = w.id;
w.timer = add_timer(*deadline, [this, id] { auto timer_res = try_add_timer(
// Timeout: resume that waiter (if still parked) with timed_out. *deadline,
const auto it = [this, id] {
std::find_if(m_waiters.begin(), m_waiters.end(), const auto it = std::find_if(
[id](const Waiter& x) { return x.id == id; }); m_waiters.begin(), m_waiters.end(),
if (it == m_waiters.end()) { [id](const Waiter& x) { return x.id == id; });
return; if (it == m_waiters.end()) {
return;
}
if (it->timed_out != nullptr) {
*it->timed_out = true;
}
auto cont2 = it->cont;
m_waiters.erase(it);
active_executor().post_completion(cont2);
},
scope);
if (timer_res) {
w.timer = *timer_res;
} else {
// Fail safe rather than hanging forever if timer table is
// saturated.
if (timed_out != nullptr) {
*timed_out = true;
} }
if (it->timed_out != nullptr) { active_executor().post_completion(cont);
*it->timed_out = true; return w.id;
} }
auto cont2 = it->cont;
m_waiters.erase(it);
m_executor.post(cont2);
});
} }
m_waiters.push_back(std::move(w)); m_waiters.push_back(std::move(w));
return m_waiters.back().id;
} }
ExecutionContext::TimerId ExecutionContext::add_timer( void ExecutionContext::cancel_waiter(WaiterId id)
std::chrono::steady_clock::time_point deadline,
std::function<void()>
on_fire)
{ {
const auto it =
std::find_if(m_waiters.begin(), m_waiters.end(),
[id](const Waiter& x) { return x.id == id; });
if (it == m_waiters.end()) {
return;
}
cancel_timer(it->timer);
if (it->cancelled != nullptr) {
*it->cancelled = true;
} else if (it->timed_out != nullptr) {
*it->timed_out = true;
}
auto cont = it->cont;
m_waiters.erase(it);
if (cont) {
active_executor().post_completion(cont);
}
}
void ExecutionContext::cancel_scope(ScopeId scope)
{
if (scope == kNoScope) {
return;
}
std::vector<std::coroutine_handle<>> to_resume;
for (auto it = m_waiters.begin(); it != m_waiters.end();) {
if (it->scope == scope) {
cancel_timer(it->timer);
if (it->cancelled != nullptr) {
*it->cancelled = true;
} else if (it->timed_out != nullptr) {
*it->timed_out = true;
}
if (it->cont) {
to_resume.push_back(it->cont);
}
it = m_waiters.erase(it);
} else {
++it;
}
}
for (auto it = m_timers.begin(); it != m_timers.end();) {
if (it->second.scope == scope) {
it = m_timers.erase(it);
} else {
++it;
}
}
for (auto h : to_resume) {
active_executor().post_completion(h);
}
}
void ExecutionContext::purge_scope(ScopeId scope)
{
if (scope == kNoScope) {
return;
}
for (auto it = m_waiters.begin(); it != m_waiters.end();) {
if (it->scope == scope) {
cancel_timer(it->timer);
it = m_waiters.erase(it);
} else {
++it;
}
}
for (auto it = m_timers.begin(); it != m_timers.end();) {
if (it->second.scope == scope) {
it = m_timers.erase(it);
} else {
++it;
}
}
}
Void::Result::Result<ExecutionContext::TimerId>
ExecutionContext::try_add_timer(
Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire, ScopeId scope)
{
if (m_limits.max_timers > 0 && m_timers.size() >= m_limits.max_timers) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"ExecutionContext::try_add_timer: max_timers reached"));
}
const TimerId id = m_next_timer++; const TimerId id = m_next_timer++;
m_timers.emplace(id, Timer{deadline, std::move(on_fire)}); m_timers.emplace(id, Timer{deadline, std::move(on_fire), scope});
return id; return id;
} }
ExecutionContext::TimerId
ExecutionContext::add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope)
{
auto r = try_add_timer(deadline, std::move(on_fire), scope);
return r ? *r : 0;
}
void ExecutionContext::cancel_timer(TimerId id) void ExecutionContext::cancel_timer(TimerId id)
{ {
if (id != 0) { if (id != 0) {
@@ -84,10 +327,10 @@ namespace Void::Fsm::Detail
} }
} }
std::optional<std::chrono::steady_clock::time_point> std::optional<Time::MonotonicClock::time_point>
ExecutionContext::next_deadline() const ExecutionContext::next_deadline() const
{ {
std::optional<std::chrono::steady_clock::time_point> next; std::optional<Time::MonotonicClock::time_point> next;
for (const auto& [id, timer] : m_timers) { for (const auto& [id, timer] : m_timers) {
if (!next.has_value() || timer.deadline < *next) { if (!next.has_value() || timer.deadline < *next) {
next = timer.deadline; next = timer.deadline;
@@ -101,7 +344,7 @@ namespace Void::Fsm::Detail
if (m_timers.empty()) { if (m_timers.empty()) {
return; return;
} }
const auto now = std::chrono::steady_clock::now(); const auto now = m_clock->now();
std::vector<std::function<void()>> due; std::vector<std::function<void()>> due;
for (auto it = m_timers.begin(); it != m_timers.end();) { for (auto it = m_timers.begin(); it != m_timers.end();) {
if (it->second.deadline <= now) { if (it->second.deadline <= now) {
@@ -120,20 +363,36 @@ namespace Void::Fsm::Detail
void ExecutionContext::deliver(EventEnvelope& env) void ExecutionContext::deliver(EventEnvelope& env)
{ {
// Route to the first parked waiter (FIFO) that wants this type — lets
// it receive the event without ever sitting in a buffer.
for (auto it = m_waiters.begin(); it != m_waiters.end(); ++it) { for (auto it = m_waiters.begin(); it != m_waiters.end(); ++it) {
if (it->wants(*env.type)) { if (it->wants(*env.type)) {
*it->slot = std::move(env); *it->slot = std::move(env);
cancel_timer(it->timer); cancel_timer(it->timer);
auto cont = it->cont; auto cont = it->cont;
m_waiters.erase(it); m_waiters.erase(it);
m_executor.post(cont); active_executor().post_completion(cont);
return; return;
} }
} }
// Otherwise buffer for a later await. if (m_limits.max_deferred_events > 0 &&
m_buffers[std::type_index{*env.type}].push_back(std::move(env.value)); m_buffered_events >= m_limits.max_deferred_events) {
Void::Log::warn("Fsm",
"dropping deferred event: max_deferred_events reached");
return;
}
m_buffered_events += 1;
m_buffered_bytes += env.bytes;
m_buffers[std::type_index{*env.type}].push_back(
BufferedEvent{std::move(env.value), env.bytes});
}
void ExecutionContext::drain_control_queue()
{
while (auto fn = m_control_queue.try_pop()) {
m_queued_control.fetch_sub(1, std::memory_order_acq_rel);
if (*fn) {
(*fn)();
}
}
} }
void ExecutionContext::set_paused(bool paused) void ExecutionContext::set_paused(bool paused)
@@ -144,22 +403,81 @@ namespace Void::Fsm::Detail
std::size_t ExecutionContext::pump() std::size_t ExecutionContext::pump()
{ {
drain_control_queue();
if (m_paused.load(std::memory_order_acquire)) { if (m_paused.load(std::memory_order_acquire)) {
return 0; return 0;
} }
++m_dispatch_turn;
std::size_t work = 0; std::size_t work = 0;
std::size_t events_this_turn = 0;
const auto turn_start = m_clock->now();
fire_due_timers(); fire_due_timers();
while (auto env = m_queue.try_pop()) {
while (events_this_turn < m_limits.max_events_per_turn) {
if (m_limits.max_turn_duration.count() > 0 &&
events_this_turn > 0 &&
(m_clock->now() - turn_start) >= m_limits.max_turn_duration) {
break;
}
auto env = m_queue.try_pop();
if (!env) {
break;
}
m_queued_events.fetch_sub(1, std::memory_order_acq_rel);
m_queued_bytes.fetch_sub(env->bytes, std::memory_order_acq_rel);
deliver(*env); deliver(*env);
++events_this_turn;
++work; ++work;
} }
work += m_executor.drain(); m_last_turn_events = events_this_turn;
drain_control_queue();
if (m_external_executor == nullptr) {
work += m_executor.drain();
}
fire_due_timers(); fire_due_timers();
drain_control_queue();
return work; return work;
} }
void ExecutionContext::run_external_pump_step()
{
if (m_done.load(std::memory_order_acquire)) {
m_pump_scheduled.store(false, std::memory_order_release);
return;
}
m_pump_scheduled.store(false, std::memory_order_seq_cst);
(void)pump();
if (!m_done.load(std::memory_order_acquire) &&
(!m_control_queue.empty() ||
(!m_paused.load(std::memory_order_acquire) && !m_queue.empty()))) {
schedule_external_pump();
}
}
void ExecutionContext::schedule_external_pump() noexcept
{
if (m_external_executor == nullptr ||
m_done.load(std::memory_order_acquire)) {
return;
}
auto weak = weak_from_this();
if (weak.expired()) {
return;
}
if (!m_pump_scheduled.exchange(true, std::memory_order_acq_rel)) {
Async::spawn(*m_external_executor,
external_pump_task(std::move(weak)));
}
}
void ExecutionContext::wake() noexcept void ExecutionContext::wake() noexcept
{ {
if (m_external_executor != nullptr) {
schedule_external_pump();
}
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) { if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
m_wakeup.release(); m_wakeup.release();
} }
@@ -204,22 +522,25 @@ namespace Void::Fsm::Detail
const bool paused = m_paused.load(std::memory_order_acquire); const bool paused = m_paused.load(std::memory_order_acquire);
if (!paused) { if (!paused) {
pump(); pump();
} else {
drain_control_queue();
} }
if (m_done.load(std::memory_order_acquire)) { if (m_done.load(std::memory_order_acquire)) {
return; return;
} }
m_sleeping.store(true, std::memory_order_release); m_sleeping.store(true, std::memory_order_release);
// Queued events only count as wakeable work when not paused. if ((!paused && !m_queue.empty()) || !m_control_queue.empty() ||
if ((!paused && !m_queue.empty()) ||
m_done.load(std::memory_order_acquire)) { m_done.load(std::memory_order_acquire)) {
m_sleeping.store(false, std::memory_order_release); m_sleeping.store(false, std::memory_order_release);
continue; continue;
} }
// Park until woken (post/resume/finish), or — when running — until
// the earliest timer is due. Paused: no timers, wait to resume.
if (const auto deadline = next_deadline(); if (const auto deadline = next_deadline();
!paused && deadline.has_value()) { !paused && deadline.has_value()) {
(void)m_wakeup.try_acquire_until(*deadline); if (m_clock == &Time::SystemMonotonicClock::instance()) {
(void)m_wakeup.try_acquire_until(*deadline);
} else {
(void)m_wakeup.try_acquire_for(std::chrono::milliseconds{1});
}
} else { } else {
m_wakeup.acquire(); m_wakeup.acquire();
} }
+1 -1
View File
@@ -1,3 +1,3 @@
void_add_module(Fsm void_add_module(Fsm
INTERNAL_DEPS Async Core Data Functional Log Service INTERNAL_DEPS Async Core Data Functional Time Log Service
) )
+1009 -108
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+34
View File
@@ -260,6 +260,21 @@ namespace Void::Net
return find_header(headers, name); return find_header(headers, name);
} }
ServerResponse ServerResponse::from_file(std::filesystem::path path,
std::string content_type,
std::uint16_t status)
{
if (content_type.empty()) {
content_type = std::string{content_type_for(path)};
}
return ServerResponse{
.status = status,
.headers = {Header{"Content-Type", std::move(content_type)}},
.body = {},
.file_body = std::move(path),
};
}
std::optional<std::string_view> std::optional<std::string_view>
ServerResponse::header(std::string_view name) const noexcept ServerResponse::header(std::string_view name) const noexcept
{ {
@@ -334,6 +349,25 @@ namespace Void::Net
return std::optional<ServerResponse>{std::move(*response)}; return std::optional<ServerResponse>{std::move(*response)};
} }
std::vector<Method> Router::allowed_methods(std::string_view path) const
{
if (path.empty() || !path.starts_with('/')) {
return {};
}
const auto segments = split_path(path_only(path));
std::vector<Method> methods;
{
std::shared_lock lock{mutex_};
for (const auto& route : routes_) {
if (match_route(route.segments, segments).has_value() &&
std::ranges::find(methods, route.method) == methods.end()) {
methods.push_back(route.method);
}
}
}
return methods;
}
std::size_t Router::size() const std::size_t Router::size() const
{ {
std::shared_lock lock{mutex_}; std::shared_lock lock{mutex_};
+10
View File
@@ -9,3 +9,13 @@ void_add_module(Net
OpenSSL::Crypto OpenSSL::Crypto
Threads::Threads Threads::Threads
) )
if(VOID_ENABLE_TSAN AND TARGET Void_Net)
# Boost.Asio 1.84's std_fenced_block calls std::atomic_thread_fence, which
# GCC warns is unsupported under -fsanitize=thread (-Werror=tsan). Keep
# hardware fences intact and scope the diagnostic suppression solely to
# Http.cpp so HttpServer.cpp and all other TUs keep full -Werror=tsan.
set_source_files_properties("${CMAKE_CURRENT_LIST_DIR}/Http.cpp"
PROPERTIES COMPILE_OPTIONS "$<$<CXX_COMPILER_ID:GNU>:-Wno-tsan>"
)
endif()
+1647
View File
File diff suppressed because it is too large. Load diff
+174 -158
View File
@@ -187,10 +187,7 @@ namespace Void::Plugin
} }
// Copy to a fresh-inode temp path so dlopen does not return the // Copy to a fresh-inode temp path so dlopen does not return the
// already-mapped image when the file is replaced in place. The name // already-mapped image when the file is replaced in place.
// must be unique per copy: glibc dedupes dlopen by pathname, so
// reusing a temp name would hand back the previously mapped (old)
// image no matter what bytes the file now holds.
std::expected<std::filesystem::path, LoadError> std::expected<std::filesystem::path, LoadError>
hotswap_copy(const std::filesystem::path& path) hotswap_copy(const std::filesystem::path& path)
{ {
@@ -213,9 +210,10 @@ namespace Void::Plugin
// ── PluginManager ───────────────────────────────────────────────────── // ── PluginManager ─────────────────────────────────────────────────────
PluginManager::PluginManager(Options options) PluginManager::PluginManager(Options options)
: m_options(options), m_watcher(FileSystem::FileWatcherOptions{ : m_options(std::move(options)),
.poll_interval = options.poll_interval, m_watcher(FileSystem::FileWatcherOptions{
.debounce_polls = options.debounce_polls}) .poll_interval = m_options.poll_interval,
.debounce_polls = m_options.debounce_polls})
{ {
} }
@@ -227,6 +225,13 @@ namespace Void::Plugin
return it == m_plugins.end() ? nullptr : it->second.get(); return it == m_plugins.end() ? nullptr : it->second.get();
} }
std::shared_ptr<PluginManager::Entry>
PluginManager::find_shared(std::string_view name) const
{
const auto it = m_plugins.find(std::string{name});
return it == m_plugins.end() ? nullptr : it->second;
}
std::expected<std::string, LoadError> std::expected<std::string, LoadError>
PluginManager::load(const std::filesystem::path& path) PluginManager::load(const std::filesystem::path& path)
{ {
@@ -244,8 +249,6 @@ namespace Void::Plugin
} }
auto inst = open_instance(load_path, m_options.dlclose_on_swap); auto inst = open_instance(load_path, m_options.dlclose_on_swap);
if (m_options.copy_on_load) { if (m_options.copy_on_load) {
// The mapping keeps the unlinked inode alive; the registry
// keeps addressing the original path for watch/reload.
std::filesystem::remove(load_path, ec); std::filesystem::remove(load_path, ec);
} }
if (!inst.has_value()) { if (!inst.has_value()) {
@@ -278,15 +281,24 @@ namespace Void::Plugin
return std::unexpected{LoadError::ActivationFailed}; return std::unexpected{LoadError::ActivationFailed};
} }
std::lock_guard lock(m_mutex); std::shared_ptr<Entry> replaced_entry;
auto entry = std::make_unique<Entry>(); {
entry->path = path; std::lock_guard lock(m_mutex);
entry->current.store(std::move(*inst), std::memory_order_release); auto entry = std::make_shared<Entry>();
Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})", entry->path = path;
path.string(), name, entry->current.store(std::move(*inst), std::memory_order_release);
entry->current.load(std::memory_order_relaxed) Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})",
->info.plugin_version); path.string(), name,
m_plugins.insert_or_assign(name, std::move(entry)); entry->current.load(std::memory_order_relaxed)
->info.plugin_version);
auto it = m_plugins.find(name);
if (it != m_plugins.end()) {
replaced_entry = std::move(it->second);
it->second = std::move(entry);
} else {
m_plugins.emplace(name, std::move(entry));
}
}
return name; return name;
} }
@@ -323,195 +335,199 @@ namespace Void::Plugin
std::expected<void, LoadError> PluginManager::unload(std::string_view name) std::expected<void, LoadError> PluginManager::unload(std::string_view name)
{ {
std::lock_guard lock(m_mutex); std::shared_ptr<Entry> removed;
auto* entry = find(name); {
if (entry == nullptr) { std::lock_guard lock(m_mutex);
return std::unexpected{LoadError::UnknownPlugin}; auto it = m_plugins.find(std::string{name});
if (it == m_plugins.end()) {
return std::unexpected{LoadError::UnknownPlugin};
}
m_watcher.unwatch(it->second->path);
removed = std::move(it->second);
m_plugins.erase(it);
} }
m_watcher.unwatch(entry->path);
// Erasing drops the registry's reference; outstanding handles keep
// the instance (and its mapped .so) alive until they drop.
m_plugins.erase(std::string{name});
Void::Log::info("Plugin.Manager", "unloaded '{}'", name); Void::Log::info("Plugin.Manager", "unloaded '{}'", name);
return {}; return {};
} }
PluginHandle PluginManager::acquire(std::string_view name) const PluginHandle PluginManager::acquire(std::string_view name) const
{ {
std::lock_guard lock(m_mutex); std::shared_ptr<Entry> entry;
auto* entry = find(name); {
if (entry == nullptr) { std::lock_guard lock(m_mutex);
entry = find_shared(name);
}
if (!entry) {
return PluginHandle{}; return PluginHandle{};
} }
// One atomic load pins the instance; it survives any later swap.
return PluginHandle{entry->current.load(std::memory_order_acquire)}; return PluginHandle{entry->current.load(std::memory_order_acquire)};
} }
std::expected<void, LoadError> PluginManager::reload(std::string_view name) std::expected<void, LoadError> PluginManager::reload(std::string_view name)
{ {
std::vector<std::function<void(std::string_view)>> callbacks; std::shared_ptr<Entry> entry;
{ {
std::lock_guard lock(m_mutex); std::lock_guard lock(m_mutex);
auto* entry = find(name); entry = find_shared(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
}
auto result = reload_locked(*entry, name, entry->path);
if (!result.has_value()) {
return result;
}
callbacks = reload_callbacks_locked();
} }
for (const auto& cb : callbacks) { if (!entry) {
cb(name); return std::unexpected{LoadError::UnknownPlugin};
} }
return {}; return reload_entry_unlocked(entry, name, std::nullopt);
} }
std::expected<void, LoadError> std::expected<void, LoadError>
PluginManager::replace(std::string_view name, PluginManager::replace(std::string_view name,
const std::filesystem::path& newPath) const std::filesystem::path& newPath)
{ {
std::vector<std::function<void(std::string_view)>> callbacks; std::shared_ptr<Entry> entry;
bool restartWatcher = false;
{ {
std::lock_guard lock(m_mutex); std::lock_guard lock(m_mutex);
auto* entry = find(name); entry = find_shared(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
}
std::error_code error;
if (!std::filesystem::is_regular_file(newPath, error)) {
return std::unexpected{LoadError::FileNotFound};
}
auto result = reload_locked(*entry, name, newPath);
if (!result) {
return result;
}
restartWatcher = entry->watched;
if (restartWatcher) {
m_watcher.unwatch(entry->path);
}
entry->path = newPath;
callbacks = reload_callbacks_locked();
} }
if (!entry) {
return std::unexpected{LoadError::UnknownPlugin};
}
std::error_code error;
if (!std::filesystem::is_regular_file(newPath, error)) {
return std::unexpected{LoadError::FileNotFound};
}
return reload_entry_unlocked(entry, name, newPath);
}
std::expected<void, LoadError> PluginManager::reload_entry_unlocked(
const std::shared_ptr<Entry>& entry, std::string_view name,
const std::optional<std::filesystem::path>& newPath)
{
std::vector<std::function<void(std::string_view)>> callbacks;
bool restartWatcher = false;
std::shared_ptr<detail::Instance> retired_old;
{
// Serialize reloads per plugin entry WITHOUT holding m_mutex, so
// validators, config providers, and concurrent acquire() callers can
// reenter PluginManager without deadlocking.
std::lock_guard reload_lk{entry->reload_mutex};
std::filesystem::path sourcePath;
{
std::lock_guard lock(m_mutex);
if (find(name) != entry.get()) {
return std::unexpected{LoadError::UnknownPlugin};
}
sourcePath = newPath.has_value() ? *newPath : entry->path;
}
auto tmp = hotswap_copy(sourcePath);
if (!tmp.has_value()) {
return std::unexpected{tmp.error()};
}
auto next = open_instance(*tmp, m_options.dlclose_on_swap);
std::error_code ec;
std::filesystem::remove(*tmp, ec);
if (!next.has_value()) {
Void::Log::warn("Plugin.Manager",
"reload '{}' failed: {}; keeping old", name,
to_string(next.error()));
return std::unexpected{next.error()};
}
if ((*next)->plugin->name() != name) {
Void::Log::warn("Plugin.Manager",
"replace '{}' rejected: candidate reports '{}'",
name, (*next)->plugin->name());
return std::unexpected{LoadError::NameMismatch};
}
if (m_options.candidate_validator &&
!m_options.candidate_validator(PluginHandle{*next})) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: binary validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.config_provider && (*next)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
(*next)->configure((*next)->plugin, config.c_str());
}
auto old = entry->current.load(std::memory_order_acquire);
if (old) {
if (!transfer_state(*old, **next)) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: state rejected", name);
return std::unexpected{LoadError::StateRejected};
}
}
try {
(*next)->plugin->on_load();
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if ((*next)->ready != nullptr &&
(*next)->ready((*next)->plugin) != 0) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: activation failed", name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.instance_validator &&
!m_options.instance_validator(*(*next)->plugin, (*next)->info)) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: host validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
{
std::lock_guard lock(m_mutex);
if (find(name) != entry.get()) {
return std::unexpected{LoadError::UnknownPlugin};
}
retired_old = entry->current.exchange(
std::move(*next), std::memory_order_acq_rel);
if (newPath.has_value()) {
restartWatcher = entry->watched;
if (restartWatcher) {
m_watcher.unwatch(entry->path);
}
entry->path = *newPath;
}
callbacks = reload_callbacks_locked();
}
}
// Drop old instance and invoke observers strictly outside all locks.
retired_old.reset();
if (restartWatcher) { if (restartWatcher) {
watch(name); watch(name);
} }
for (const auto& callback : callbacks) {
callback(name);
}
return {};
}
std::expected<void, LoadError>
PluginManager::reload_locked(Entry& entry, std::string_view name,
const std::filesystem::path& sourcePath)
{
// Copy to a fresh inode so dlopen loads the new bytes instead of
// returning the still-open handle for this path. The caller must
// have installed the new file via atomic rename (a fresh inode of
// its own) — overwriting the mapped file in place corrupts the
// running instance's mapping (SIGBUS).
auto tmp = hotswap_copy(sourcePath);
if (!tmp.has_value()) {
return std::unexpected{tmp.error()};
}
auto next = open_instance(*tmp, m_options.dlclose_on_swap);
std::error_code ec;
std::filesystem::remove(*tmp, ec);
if (!next.has_value()) {
Void::Log::warn("Plugin.Manager",
"reload '{}' failed: {}; keeping old", name,
to_string(next.error()));
return std::unexpected{next.error()};
}
if ((*next)->plugin->name() != name) {
Void::Log::warn("Plugin.Manager",
"replace '{}' rejected: candidate reports '{}'",
name, (*next)->plugin->name());
return std::unexpected{LoadError::NameMismatch};
}
if (m_options.candidate_validator &&
!m_options.candidate_validator(PluginHandle{*next})) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: binary validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.config_provider && (*next)->configure != nullptr) {
const std::string config = m_options.config_provider(name);
(*next)->configure((*next)->plugin, config.c_str());
}
// Transfer state with both instances alive (transactional).
auto old = entry.current.load(std::memory_order_acquire);
if (old) {
if (!transfer_state(*old, **next)) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: state rejected", name);
return std::unexpected{LoadError::StateRejected};
}
}
try {
(*next)->plugin->on_load();
} catch (...) {
return std::unexpected{LoadError::ActivationFailed};
}
if ((*next)->ready != nullptr && (*next)->ready((*next)->plugin) != 0) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: activation failed", name);
return std::unexpected{LoadError::ActivationFailed};
}
if (m_options.instance_validator &&
!m_options.instance_validator(*(*next)->plugin, (*next)->info)) {
Void::Log::warn("Plugin.Manager",
"reload '{}' aborted: host validation failed",
name);
return std::unexpected{LoadError::ActivationFailed};
}
// Atomic swap. The old instance keeps living while any acquired
// handle still pins it; it is destroyed when the last one drops.
entry.current.store(std::move(*next), std::memory_order_release);
Void::Log::info("Plugin.Manager", "reloaded '{}'", name); Void::Log::info("Plugin.Manager", "reloaded '{}'", name);
for (const auto& cb : callbacks) {
cb(name);
}
return {}; return {};
} }
void PluginManager::watch(std::string_view name) void PluginManager::watch(std::string_view name)
{ {
std::shared_ptr<Entry> entry;
std::filesystem::path path; std::filesystem::path path;
{ {
std::lock_guard lock(m_mutex); std::lock_guard lock(m_mutex);
auto* entry = find(name); entry = find_shared(name);
if (entry == nullptr) { if (!entry) {
return; return;
} }
path = entry->path; path = entry->path;
entry->watched = true; entry->watched = true;
} }
const std::string name_str{name}; const std::string name_str{name};
m_watcher.watch(path, [this, name_str]( m_watcher.watch(path, [this, entry, name_str](
const FileSystem::FileWatcher::Event& e) { const FileSystem::FileWatcher::Event& e) {
if (!e.exists) { if (!e.exists) {
return; return;
} }
std::vector<std::function<void(std::string_view)>> callbacks; (void)reload_entry_unlocked(entry, name_str, std::nullopt);
{
std::lock_guard lock(m_mutex);
auto* entry = find(name_str);
if (entry == nullptr) {
return;
}
if (!reload_locked(*entry, name_str, entry->path).has_value()) {
return;
}
callbacks = reload_callbacks_locked();
}
for (const auto& cb : callbacks) {
cb(name_str);
}
}); });
} }
+1 -1
View File
@@ -1,4 +1,4 @@
void_add_module(Plugin void_add_module(Plugin
INTERNAL_DEPS Functional System Data LogState Text Service INTERNAL_DEPS Core Functional System Data Time Async LogState Text Service
DEPS_UNIX dl DEPS_UNIX dl
) )
+944
View File
@@ -0,0 +1,944 @@
#include <Void/Service/Registry.hpp>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <exception>
#include <functional>
#include <queue>
#include <string_view>
#include <unordered_set>
namespace Void::Service
{
namespace detail
{
struct RetentionState {
mutable std::mutex mu{};
std::condition_variable cv{};
std::vector<RetentionEntry> entries{};
void notify_release() noexcept
{
std::lock_guard lk{mu};
cv.notify_all();
}
};
namespace
{
struct TokenGuard {
std::weak_ptr<RetentionState> state{};
~TokenGuard()
{
if (auto s = state.lock()) {
s->notify_release();
}
}
};
std::shared_ptr<const void>
make_retention_token(const std::shared_ptr<RetentionState>& state,
PublicationEpoch epoch,
std::string label)
{
auto tok = std::make_shared<TokenGuard>(TokenGuard{state});
{
std::lock_guard lk{state->mu};
std::erase_if(state->entries, [](const RetentionEntry& e) {
return e.token.expired();
});
state->entries.push_back(
RetentionEntry{epoch, tok, std::move(label)});
}
return tok;
}
bool has_in_parent_chain(const SnapshotData& snap,
std::type_index key,
std::size_t max_levels,
std::size_t depth = 0)
{
if (depth > max_levels) {
return false;
}
if (snap.services.contains(key)) {
return true;
}
if (snap.parent_snap) {
return has_in_parent_chain(*snap.parent_snap, key,
max_levels, depth + 1);
}
return false;
}
} // namespace
} // namespace detail
ServiceRegistry::ServiceRegistry()
: ServiceRegistry(ServiceLimits{},
Void::Time::SystemMonotonicClock::instance())
{
}
ServiceRegistry::ServiceRegistry(const ServiceRegistry* parent)
: ServiceRegistry(ServiceLimits{},
Void::Time::SystemMonotonicClock::instance())
{
if (parent != nullptr) {
auto snap = std::make_shared<detail::SnapshotData>();
snap->live_parent = parent;
m_active_snapshot = std::move(snap);
}
}
ServiceRegistry::ServiceRegistry(ServiceLimits limits,
const Void::Time::MonotonicClock& clock)
: m_limits(limits), m_clock(&clock),
m_retention_state(std::make_shared<detail::RetentionState>())
{
m_active_snapshot = std::make_shared<detail::SnapshotData>();
}
ServiceRegistry::~ServiceRegistry()
{
// Detach the active snapshot under m_snapshot_mu with m_stopping=true
// before destroying providers, so a provider destructor reentering the
// registry cannot increment the use_count of a half-destroyed SnapshotData.
std::shared_ptr<const detail::SnapshotData> last_snap;
{
std::lock_guard snap_lk{m_snapshot_mu};
m_stopping = true;
last_snap = std::move(m_active_snapshot);
}
last_snap.reset();
}
Void::Result::Result<std::unique_ptr<ServiceRegistry>>
ServiceRegistry::from_parent_snapshot(
ServiceSnapshot parent, ServiceLimits limits,
const Void::Time::MonotonicClock& clock)
{
if (!parent) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry: parent snapshot must not be empty"));
}
std::size_t depth = 1;
const detail::SnapshotData* cur = parent.m_data.get();
while (cur->parent_snap != nullptr) {
++depth;
if (depth > limits.max_parent_levels) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::overloaded,
"ServiceRegistry: parent snapshot nesting exceeds max_parent_levels"));
}
cur = cur->parent_snap.get();
}
auto reg = std::make_unique<ServiceRegistry>(limits, clock);
auto snap = std::make_shared<detail::SnapshotData>();
snap->parent_snap = std::move(parent.m_data);
reg->m_active_snapshot = std::move(snap);
return reg;
}
void ServiceRegistry::refresh_parent(const ServiceRegistry& parent)
{
auto parent_snap = parent.snapshot();
std::shared_ptr<const detail::SnapshotData> old_snap;
{
std::lock_guard write_lk{m_write_mu};
auto next = std::make_shared<detail::SnapshotData>(*m_active_snapshot);
next->parent_snap = parent_snap.m_data;
next->live_parent = nullptr;
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return;
}
old_snap = std::exchange(m_active_snapshot, std::move(next));
}
// old_snap released here outside all locks.
}
ServiceSnapshot ServiceRegistry::snapshot() const
{
std::lock_guard snap_lk{m_snapshot_mu};
return ServiceSnapshot{m_active_snapshot, m_limits.max_parent_levels};
}
std::shared_ptr<const detail::SnapshotData>
ServiceRegistry::acquire_snapshot() const
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return nullptr;
}
return m_active_snapshot;
}
void ServiceRegistry::provide_erased(std::type_index key,
std::shared_ptr<void> impl,
const void* object_key,
IService* service)
{
std::shared_ptr<const detail::SnapshotData> old_snap;
{
std::lock_guard write_lk{m_write_mu};
if (m_stopping) {
return;
}
auto next =
std::make_shared<detail::SnapshotData>(*m_active_snapshot);
next->epoch = ++m_epoch;
if (!next->services.contains(key)) {
next->legacy_order.push_back(key);
}
next->services.insert_or_assign(
key, detail::SnapshotEntry{std::move(impl), service, {}});
// Rebuild lifecycle list in legacy registration order (deduping
// shared object instances if multiple interfaces point to one
// IService).
next->lifecycle_nodes.clear();
std::unordered_set<const void*> seen_objs;
for (const auto& k : next->legacy_order) {
const auto it = next->services.find(k);
if (it == next->services.end() || it->second.service == nullptr) {
continue;
}
const void* obj = static_cast<const void*>(it->second.service);
if (!seen_objs.insert(obj).second) {
continue;
}
next->lifecycle_nodes.push_back(detail::LifecycleNode{
.id = std::string{it->second.service->service_name()},
.object_key = obj,
.owner = it->second.impl,
.service = it->second.service,
.managed = dynamic_cast<IManagedService*>(it->second.service),
.seq = next->lifecycle_nodes.size(),
.dep_indices = {},
});
}
(void)object_key;
{
std::lock_guard snap_lk{m_snapshot_mu};
old_snap = std::exchange(m_active_snapshot, std::move(next));
}
}
// old_snap (and any replaced provider whose external refs reached 0)
// destroys here AFTER releasing all registry locks.
}
bool ServiceRegistry::remove_erased(std::type_index key)
{
std::shared_ptr<const detail::SnapshotData> old_snap;
bool removed = false;
{
std::lock_guard write_lk{m_write_mu};
if (m_stopping || !m_active_snapshot->services.contains(key)) {
return false;
}
auto next =
std::make_shared<detail::SnapshotData>(*m_active_snapshot);
next->epoch = ++m_epoch;
removed = next->services.erase(key) > 0;
std::erase(next->legacy_order, key);
next->lifecycle_nodes.clear();
std::unordered_set<const void*> seen_objs;
for (const auto& k : next->legacy_order) {
const auto it = next->services.find(k);
if (it == next->services.end() || it->second.service == nullptr) {
continue;
}
const void* obj = static_cast<const void*>(it->second.service);
if (!seen_objs.insert(obj).second) {
continue;
}
next->lifecycle_nodes.push_back(detail::LifecycleNode{
.id = std::string{it->second.service->service_name()},
.object_key = obj,
.owner = it->second.impl,
.service = it->second.service,
.managed = dynamic_cast<IManagedService*>(it->second.service),
.seq = next->lifecycle_nodes.size(),
.dep_indices = {},
});
}
{
std::lock_guard snap_lk{m_snapshot_mu};
old_snap = std::exchange(m_active_snapshot, std::move(next));
}
}
return removed;
}
void ServiceRegistry::start_all()
{
auto snap = acquire_snapshot();
if (!snap) {
return;
}
// Snapshot copied; callbacks invoke strictly outside registry locks.
for (const auto& node : snap->lifecycle_nodes) {
if (node.service != nullptr) {
node.service->on_start();
}
}
}
void ServiceRegistry::stop_all()
{
std::shared_ptr<const detail::SnapshotData> snap;
{
std::lock_guard snap_lk{m_snapshot_mu};
snap = m_active_snapshot;
}
if (!snap) {
return;
}
for (auto it = snap->lifecycle_nodes.rbegin();
it != snap->lifecycle_nodes.rend(); ++it) {
if (it->service != nullptr) {
it->service->on_stop();
}
}
}
std::size_t ServiceRegistry::size() const
{
std::lock_guard snap_lk{m_snapshot_mu};
return m_active_snapshot ? m_active_snapshot->services.size() : 0;
}
std::size_t ServiceRegistry::prune_and_count_retained_locked()
{
std::lock_guard lk{m_retention_state->mu};
std::erase_if(m_retention_state->entries,
[](const detail::RetentionEntry& e) {
return e.token.expired();
});
return m_retention_state->entries.size();
}
std::size_t ServiceRegistry::retained_generation_count() const
{
std::lock_guard lk{m_retention_state->mu};
std::size_t live = 0;
for (const auto& e : m_retention_state->entries) {
if (!e.token.expired()) {
++live;
}
}
return live;
}
PublicationEpoch ServiceRegistry::epoch() const noexcept
{
std::lock_guard snap_lk{m_snapshot_mu};
return m_epoch;
}
bool ServiceRegistry::is_stopping() const noexcept
{
std::lock_guard snap_lk{m_snapshot_mu};
return m_stopping;
}
std::size_t ServiceRegistry::add_observer(ObserverCallback cb)
{
std::lock_guard lk{m_observer_mu};
const std::size_t id = m_next_observer_id++;
m_observers.emplace_back(id, std::move(cb));
return id;
}
void ServiceRegistry::remove_observer(std::size_t id)
{
std::lock_guard lk{m_observer_mu};
std::erase_if(m_observers,
[id](const auto& pair) { return pair.first == id; });
}
void ServiceRegistry::notify_observers(const ServiceObservation& obs)
{
std::vector<ObserverCallback> copy;
{
std::lock_guard lk{m_observer_mu};
copy.reserve(m_observers.size());
for (const auto& [_, cb] : m_observers) {
if (cb) {
copy.push_back(cb);
}
}
}
for (const auto& cb : copy) {
try {
cb(obs);
} catch (...) {
}
}
}
Void::Result::Result<PreparedPublication>
ServiceRegistry::prepare_batch(ProviderSet set, ExpectedEpoch expected)
{
std::shared_ptr<const detail::SnapshotData> current_snap;
PublicationEpoch current_epoch = 0;
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::prepare_batch: registry is stopping"));
}
current_epoch = m_epoch;
current_snap = m_active_snapshot;
}
if (expected.has_value() && *expected != current_epoch) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::conflict,
"ServiceRegistry::prepare_batch: expected epoch mismatch"));
}
const auto& items = set.items();
if (items.size() > m_limits.max_staged_changes ||
items.size() > m_limits.max_providers) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::overloaded,
"ServiceRegistry::prepare_batch: staged provider limit exceeded"));
}
if (m_limits.max_retained_generations > 0 &&
retained_generation_count() >= m_limits.max_retained_generations) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::retention_limit,
"ServiceRegistry::prepare_batch: retained generation limit reached"));
}
auto staged = std::make_shared<detail::SnapshotData>();
staged->parent_snap = current_snap ? current_snap->parent_snap : nullptr;
staged->live_parent = current_snap ? current_snap->live_parent : nullptr;
// Validate interfaces, IDs, nulls, edge caps, and coalesce shared-object
// lifecycle aliases into single nodes.
std::unordered_map<std::type_index, std::size_t> iface_to_node;
std::unordered_map<const void*, std::size_t> obj_to_node;
std::unordered_map<std::string, const void*> id_to_obj;
std::vector<detail::LifecycleNode> raw_nodes;
std::size_t total_edges = 0;
for (const auto& item : items) {
if (!item.owner || item.object_key == nullptr) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry::prepare_batch: null service provider"));
}
if (staged->services.contains(item.interface_type)) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::duplicate_interface,
"ServiceRegistry::prepare_batch: duplicate interface in batch"));
}
const void* canonical_obj =
item.service != nullptr
? static_cast<const void*>(item.service)
: item.object_key;
if (!item.id.empty()) {
const auto [it, inserted] =
id_to_obj.emplace(item.id, canonical_obj);
if (!inserted && it->second != canonical_obj) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::conflict,
"ServiceRegistry::prepare_batch: conflicting service id '" +
item.id + "'"));
}
}
staged->services.emplace(
item.interface_type,
detail::SnapshotEntry{item.owner, item.service, item.id});
staged->legacy_order.push_back(item.interface_type);
total_edges += item.required_deps.size() + item.optional_deps.size();
if (total_edges > m_limits.max_dependency_edges) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::overloaded,
"ServiceRegistry::prepare_batch: dependency edge limit exceeded"));
}
auto [oit, o_inserted] =
obj_to_node.emplace(canonical_obj, raw_nodes.size());
if (o_inserted) {
std::string node_id = item.id;
if (node_id.empty() && item.service != nullptr) {
node_id = std::string{item.service->service_name()};
}
raw_nodes.push_back(detail::LifecycleNode{
.id = std::move(node_id),
.object_key = canonical_obj,
.owner = item.owner,
.service = item.service,
.managed = item.managed,
.seq = raw_nodes.size(),
.dep_indices = {},
});
}
iface_to_node.emplace(item.interface_type, oit->second);
}
// Build DAG edges: dep_idx -> dependent_idx.
const std::size_t n = raw_nodes.size();
std::vector<std::vector<std::size_t>> adj(n);
std::vector<std::size_t> indegree(n, 0);
std::unordered_set<std::uint64_t> edge_dedup;
for (const auto& item : items) {
const std::size_t u = iface_to_node.at(item.interface_type);
auto add_dep = [&](std::type_index dep_iface,
bool required) -> Void::Result::Result<void> {
const auto dit = iface_to_node.find(dep_iface);
if (dit == iface_to_node.end()) {
bool in_parent = false;
if (staged->parent_snap) {
in_parent = detail::has_in_parent_chain(
*staged->parent_snap, dep_iface,
m_limits.max_parent_levels);
}
if (!in_parent && staged->live_parent != nullptr) {
if (auto ps = staged->live_parent->acquire_snapshot()) {
in_parent = ps->services.contains(dep_iface);
}
}
if (required && !in_parent) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::missing_dependency,
"ServiceRegistry::prepare_batch: missing required dependency"));
}
return {};
}
const std::size_t dep = dit->second;
if (dep == u) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::cycle_detected,
"ServiceRegistry::prepare_batch: self-dependency cycle"));
}
const std::uint64_t edge_key =
(static_cast<std::uint64_t>(dep) << 32) |
static_cast<std::uint64_t>(u);
if (edge_dedup.insert(edge_key).second) {
adj[dep].push_back(u);
++indegree[u];
}
return {};
};
for (const auto& dep : item.required_deps) {
if (auto r = add_dep(dep, true); !r) {
return Void::Result::fail(std::move(r).error());
}
}
for (const auto& dep : item.optional_deps) {
if (auto r = add_dep(dep, false); !r) {
return Void::Result::fail(std::move(r).error());
}
}
}
// Deterministic Kahn topological sort breaking ties by registration seq.
std::priority_queue<std::size_t, std::vector<std::size_t>,
std::greater<std::size_t>>
ready;
for (std::size_t i = 0; i < n; ++i) {
if (indegree[i] == 0) {
ready.push(i);
}
}
std::vector<detail::LifecycleNode> sorted;
sorted.reserve(n);
while (!ready.empty()) {
const std::size_t u = ready.top();
ready.pop();
sorted.push_back(std::move(raw_nodes[u]));
for (const std::size_t v : adj[u]) {
if (--indegree[v] == 0) {
ready.push(v);
}
}
}
if (sorted.size() != n) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::cycle_detected,
"ServiceRegistry::prepare_batch: dependency cycle detected"));
}
staged->lifecycle_nodes = std::move(sorted);
PreparedPublication prep;
prep.expected_epoch = expected;
prep.snapshot = std::move(staged);
prep.valid = true;
prep.started = false;
prep.aborted = false;
return prep;
}
Void::Result::Result<void> ServiceRegistry::rollback_started_nodes(
const std::vector<detail::LifecycleNode>& nodes, std::size_t count,
const Void::Result::Error& primary_error)
{
std::string stop_errs;
for (std::size_t i = count; i > 0; --i) {
const auto& node = nodes[i - 1];
if (node.managed != nullptr) {
auto sr = node.managed->stop_checked();
if (!sr) {
if (!stop_errs.empty()) stop_errs += "; ";
stop_errs += sr.error().message();
}
} else if (node.service != nullptr) {
try {
node.service->on_stop();
} catch (const std::exception& ex) {
if (!stop_errs.empty()) stop_errs += "; ";
stop_errs += ex.what();
} catch (...) {
if (!stop_errs.empty()) stop_errs += "; ";
stop_errs += "unknown stop exception";
}
}
}
if (stop_errs.empty()) {
return Void::Result::fail(primary_error);
}
return Void::Result::fail(make_service_error(
static_cast<ServiceErrorCode>(primary_error.code().value),
primary_error.message() + " (rollback stop errors: " + stop_errs +
")"));
}
Void::Result::Result<void>
ServiceRegistry::start_staged(PreparedPublication& prepared,
Async::OperationOptions options)
{
if (!prepared.valid || !prepared.snapshot || prepared.aborted) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry::start_staged: invalid or aborted publication"));
}
if (prepared.started) {
return {};
}
const auto& nodes = prepared.snapshot->lifecycle_nodes;
for (std::size_t i = 0; i < nodes.size(); ++i) {
if (options.stop.stop_requested()) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::cancelled,
"ServiceRegistry::start_staged: cancelled during startup"));
}
if (Async::is_deadline_expired(options, *m_clock)) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::timeout,
"ServiceRegistry::start_staged: deadline expired during startup"));
}
const auto& node = nodes[i];
if (node.managed != nullptr) {
auto sr = node.managed->start_checked();
if (!sr) {
node.managed->abort_start();
prepared.aborted = true;
return rollback_started_nodes(nodes, i, sr.error());
}
auto rr = node.managed->check_readiness();
if (!rr) {
node.managed->abort_start();
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::not_ready,
rr.error().message()));
}
} else if (node.service != nullptr) {
try {
node.service->on_start();
} catch (const std::exception& ex) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::start_failed,
ex.what()));
} catch (...) {
prepared.aborted = true;
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::start_failed,
"ServiceRegistry: service on_start threw"));
}
}
}
prepared.started = true;
return {};
}
Void::Result::Result<PublicationEpoch>
ServiceRegistry::publish(PreparedPublication&& prepared)
{
if (!prepared.valid || !prepared.snapshot || prepared.aborted) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServiceRegistry::publish: invalid or aborted publication"));
}
PublicationEpoch new_epoch = 0;
std::size_t provider_count = 0;
std::size_t retained = 0;
std::shared_ptr<const detail::SnapshotData> old_snap;
{
std::lock_guard write_lk{m_write_mu};
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::publish: registry is stopping"));
}
if (prepared.expected_epoch.has_value() &&
*prepared.expected_epoch != m_epoch) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::conflict,
"ServiceRegistry::publish: expected epoch conflict"));
}
}
if (m_limits.max_retained_generations > 0 &&
prune_and_count_retained_locked() >=
m_limits.max_retained_generations) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::retention_limit,
"ServiceRegistry::publish: retained generation limit reached"));
}
new_epoch = ++m_epoch;
prepared.snapshot->epoch = new_epoch;
prepared.snapshot->gen_token = detail::make_retention_token(
m_retention_state, new_epoch,
"generation#" + std::to_string(new_epoch));
provider_count = prepared.snapshot->services.size();
{
std::lock_guard snap_lk{m_snapshot_mu};
if (m_stopping) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::publish: registry is stopping"));
}
old_snap = std::exchange(m_active_snapshot,
std::move(prepared.snapshot));
}
retained = prune_and_count_retained_locked();
m_started = prepared.started;
}
prepared.valid = false;
// Retire old snapshot strictly outside locks, then notify observers.
old_snap.reset();
notify_observers(ServiceObservation{
.epoch = new_epoch,
.provider_count = provider_count,
.retained_generations = retained,
.duration_ns = 0,
.rollback = false,
.detail = "published",
});
return new_epoch;
}
Void::Result::Result<PublicationEpoch>
ServiceRegistry::start_and_publish(ProviderSet set,
ExpectedEpoch expected,
Async::OperationOptions options)
{
const auto t0 = m_clock->now();
auto prep = prepare_batch(std::move(set), expected);
if (!prep) {
return Void::Result::fail(std::move(prep).error());
}
auto staged = std::move(*prep);
if (auto sr = start_staged(staged, options); !sr) {
const auto dt = static_cast<std::uint64_t>(
std::max<std::int64_t>(0, (m_clock->now() - t0).count()));
notify_observers(ServiceObservation{
.epoch = epoch(),
.provider_count = 0,
.retained_generations = retained_generation_count(),
.duration_ns = dt,
.rollback = true,
.detail = sr.error().message(),
});
return Void::Result::fail(std::move(sr).error());
}
auto snapshot_copy = staged.snapshot;
auto pub = publish(std::move(staged));
if (!pub) {
return Void::Result::fail(
rollback_started_nodes(snapshot_copy->lifecycle_nodes,
snapshot_copy->lifecycle_nodes.size(),
pub.error())
.error());
}
return pub;
}
Void::Result::Result<void>
ServiceRegistry::start(Async::OperationOptions options)
{
auto snap = acquire_snapshot();
if (!snap) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry::start: registry is stopping"));
}
const auto& nodes = snap->lifecycle_nodes;
for (std::size_t i = 0; i < nodes.size(); ++i) {
if (options.stop.stop_requested()) {
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::cancelled,
"ServiceRegistry::start: cancelled"));
}
if (Async::is_deadline_expired(options, *m_clock)) {
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::timeout,
"ServiceRegistry::start: timed out"));
}
const auto& node = nodes[i];
if (node.managed != nullptr) {
auto sr = node.managed->start_checked();
if (!sr) {
node.managed->abort_start();
return rollback_started_nodes(nodes, i, sr.error());
}
auto rr = node.managed->check_readiness();
if (!rr) {
node.managed->abort_start();
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::not_ready,
rr.error().message()));
}
} else if (node.service != nullptr) {
try {
node.service->on_start();
} catch (const std::exception& ex) {
return rollback_started_nodes(
nodes, i,
make_service_error(ServiceErrorCode::start_failed,
ex.what()));
} catch (...) {
return rollback_started_nodes(
nodes, i,
make_service_error(
ServiceErrorCode::start_failed,
"ServiceRegistry::start: on_start threw"));
}
}
}
std::lock_guard write_lk{m_write_mu};
m_started = true;
return {};
}
Void::Result::Result<ShutdownReport>
ServiceRegistry::close_and_join(Async::OperationOptions options)
{
std::shared_ptr<const detail::SnapshotData> active_to_stop;
{
std::lock_guard snap_lk{m_snapshot_mu};
m_stopping = true;
active_to_stop = std::exchange(
m_active_snapshot, std::make_shared<detail::SnapshotData>());
}
ShutdownReport report;
if (active_to_stop) {
for (auto it = active_to_stop->lifecycle_nodes.rbegin();
it != active_to_stop->lifecycle_nodes.rend(); ++it) {
const auto& node = *it;
const std::string label =
!node.id.empty() ? node.id : std::string{"<service>"};
if (node.managed != nullptr) {
auto sr = node.managed->stop_checked();
if (!sr) {
report.stop_errors.push_back(std::move(sr).error());
} else {
report.stopped_services.push_back(label);
}
} else if (node.service != nullptr) {
try {
node.service->on_stop();
report.stopped_services.push_back(label);
} catch (const std::exception& ex) {
report.stop_errors.push_back(make_service_error(
ServiceErrorCode::stop_failed, ex.what()));
} catch (...) {
report.stop_errors.push_back(make_service_error(
ServiceErrorCode::stop_failed,
"ServiceRegistry::close_and_join: on_stop threw"));
}
}
}
}
active_to_stop.reset();
// Check retained generation pins; wait up to deadline only when using the
// real monotonic clock and an explicit deadline.
const bool can_wait_deadline =
options.deadline.has_value() &&
m_clock == &Void::Time::SystemMonotonicClock::instance();
std::unique_lock lk{m_retention_state->mu};
auto collect_live = [&]() {
std::erase_if(m_retention_state->entries,
[](const detail::RetentionEntry& e) {
return e.token.expired();
});
return m_retention_state->entries.empty();
};
if (!collect_live() && can_wait_deadline && !options.stop.stop_requested()) {
while (!collect_live() && !options.stop.stop_requested()) {
const auto now = m_clock->now();
if (now >= *options.deadline) {
break;
}
const auto rem = *options.deadline - now;
m_retention_state->cv.wait_for(
lk, std::chrono::duration_cast<std::chrono::milliseconds>(
rem));
}
}
for (const auto& entry : m_retention_state->entries) {
if (!entry.token.expired()) {
report.incomplete_owners.push_back(entry.label);
}
}
return report;
}
} // namespace Void::Service
+2 -1
View File
@@ -1,3 +1,4 @@
void_add_module(Service void_add_module(Service
INTERNAL_DEPS Core Functional LogState INTERNAL_DEPS Core Functional Time Async LogState
EXCLUDE_HEADERS Void/Service/PluginService.hpp
) )
+4
View File
@@ -0,0 +1,4 @@
void_add_module(ServicePlugin
INTERNAL_DEPS Service Plugin LogState
EXTRA_HEADERS Void/Service/PluginService.hpp
)
+833
View File
@@ -0,0 +1,833 @@
#include <Void/System/DirectoryWatcher.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <deque>
#include <filesystem>
#include <format>
#include <map>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#if defined(__linux__)
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
#if defined(__linux__)
namespace
{
constexpr std::uint32_t kWatchMask =
IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_FROM |
IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_EXCL_UNLINK |
IN_ONLYDIR;
[[nodiscard]] bool is_subpath_or_equal(const std::filesystem::path& candidate,
const std::filesystem::path& prefix)
{
const std::string c = candidate.lexically_normal().generic_string();
const std::string p = prefix.lexically_normal().generic_string();
if (c == p) {
return true;
}
if (p.empty()) {
return false;
}
const std::size_t plen = p.size();
return c.size() > plen && c.compare(0, plen, p) == 0 && c[plen] == '/';
}
[[nodiscard]] std::filesystem::path
rebase_path(const std::filesystem::path& p,
const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
const std::string ps = p.lexically_normal().generic_string();
const std::string os = old_prefix.lexically_normal().generic_string();
if (ps == os) {
return new_prefix;
}
if (ps.size() > os.size() && ps.compare(0, os.size(), os) == 0 &&
ps[os.size()] == '/') {
return new_prefix / std::filesystem::path{ps.substr(os.size() + 1U)};
}
return p;
}
} // namespace
struct DirectoryWatcher::Impl {
struct PendingMove {
std::filesystem::path path{};
bool is_directory{false};
std::chrono::steady_clock::time_point expires_at{};
};
Void::System::OwnedFd inotify_fd{};
Void::System::OwnedFd wake_fd{};
std::filesystem::path root{};
DirectoryWatcherOptions options{};
mutable std::mutex mutex{};
std::unordered_map<int, std::filesystem::path> wd_to_path{};
std::map<std::filesystem::path, int> path_to_wd{};
std::unordered_map<std::uint32_t, PendingMove> pending_moves{};
std::deque<DirectoryEvent> queue{};
bool rescan_emitted{false};
~Impl() noexcept
{
std::lock_guard lock{mutex};
for (const auto& [wd, _] : wd_to_path) {
if (inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
wd_to_path.clear();
path_to_wd.clear();
}
[[nodiscard]] bool should_ignore(const std::filesystem::path& p,
bool is_dir) const
{
if (options.ignore) {
return options.ignore(p, is_dir);
}
return false;
}
void push_event_locked(DirectoryEvent ev)
{
if (ev.kind == DirectoryEventKind::RescanRequired) {
if (rescan_emitted) {
return;
}
rescan_emitted = true;
queue.push_back(std::move(ev));
return;
}
if (queue.size() >= options.max_queued_events) {
if (!rescan_emitted) {
rescan_emitted = true;
queue.push_back(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher event queue full",
});
}
return;
}
queue.push_back(std::move(ev));
}
void remove_watch_by_wd_locked(int wd, bool call_rm)
{
auto it = wd_to_path.find(wd);
if (it == wd_to_path.end()) {
return;
}
path_to_wd.erase(it->second);
wd_to_path.erase(it);
if (call_rm && inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
void remove_subtree_watches_locked(const std::filesystem::path& prefix)
{
std::vector<int> wds;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, prefix)) {
wds.push_back(wd);
}
}
for (int wd : wds) {
remove_watch_by_wd_locked(wd, true);
}
}
void rewrite_subtree_watches_locked(const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
std::vector<std::pair<int, std::filesystem::path>> updates;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, old_prefix)) {
updates.emplace_back(wd, rebase_path(p, old_prefix, new_prefix));
}
}
for (const auto& [wd, new_p] : updates) {
auto old_it = wd_to_path.find(wd);
if (old_it != wd_to_path.end()) {
path_to_wd.erase(old_it->second);
old_it->second = new_p;
path_to_wd[new_p] = wd;
}
}
}
void attach_single_dir_locked(const std::filesystem::path& dir_path)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
if (path_to_wd.contains(norm)) {
return;
}
if (wd_to_path.size() >= options.max_watches) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher max_watches exceeded",
});
return;
}
const int wd =
::inotify_add_watch(inotify_fd.get(), norm.c_str(), kWatchMask);
if (wd < 0) {
const int err = errno;
if (err == ENOSPC || err == ENOMEM) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = std::format(
"inotify_add_watch exhausted watches (errno={})", err),
});
}
return;
}
// inotify_add_watch may return an existing wd if directory inode aliased.
if (auto existing = wd_to_path.find(wd); existing != wd_to_path.end()) {
if (existing->second != norm) {
path_to_wd.erase(existing->second);
existing->second = norm;
}
} else {
wd_to_path.emplace(wd, norm);
}
path_to_wd[norm] = wd;
}
void attach_subtree_locked(const std::filesystem::path& dir_path,
bool emit_existing_children)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
std::error_code ec;
const auto st = std::filesystem::symlink_status(norm, ec);
if (ec || std::filesystem::is_symlink(st) ||
!std::filesystem::is_directory(st)) {
return;
}
attach_single_dir_locked(norm);
std::vector<std::filesystem::path> stack{norm};
while (!stack.empty()) {
const std::filesystem::path cur = std::move(stack.back());
stack.pop_back();
ec.clear();
std::filesystem::directory_iterator it{
cur,
std::filesystem::directory_options::skip_permission_denied,
ec};
if (ec) {
continue;
}
for (const auto& entry : it) {
std::error_code st_ec;
const auto est = entry.symlink_status(st_ec);
if (st_ec || std::filesystem::is_symlink(est)) {
continue;
}
const bool is_dir = std::filesystem::is_directory(est);
const std::filesystem::path ep =
entry.path().lexically_normal();
if (should_ignore(ep, is_dir)) {
continue;
}
if (emit_existing_children) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = ep,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if (is_dir) {
attach_single_dir_locked(ep);
stack.push_back(ep);
}
}
}
}
void flush_expired_moves_locked(std::chrono::steady_clock::time_point now,
bool force_all)
{
for (auto it = pending_moves.begin(); it != pending_moves.end();) {
if (force_all || now >= it->second.expires_at) {
const auto p = it->second.path;
const bool is_dir = it->second.is_directory;
if (is_dir) {
remove_subtree_watches_locked(p);
}
if (!should_ignore(p, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = p,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
it = pending_moves.erase(it);
} else {
++it;
}
}
}
void process_inotify_event_locked(const struct inotify_event* ev)
{
if ((ev->mask & IN_Q_OVERFLOW) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "inotify kernel event queue overflow (IN_Q_OVERFLOW)",
});
return;
}
if ((ev->mask & IN_IGNORED) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
return;
}
const auto dir_it = wd_to_path.find(ev->wd);
if (dir_it == wd_to_path.end()) {
return;
}
const std::filesystem::path base = dir_it->second;
const bool is_dir = (ev->mask & IN_ISDIR) != 0U;
if ((ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) != 0U && ev->len == 0U) {
if (base == root) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "watched root directory deleted or moved",
});
remove_watch_by_wd_locked(ev->wd, false);
} else if ((ev->mask & IN_DELETE_SELF) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
}
return;
}
const std::string name =
(ev->len > 0U && ev->name[0] != '\0') ? std::string{ev->name}
: std::string{};
const std::filesystem::path full_path =
name.empty() ? base : (base / name).lexically_normal();
if ((ev->mask & IN_MOVED_FROM) != 0U) {
if (ev->cookie != 0U) {
pending_moves.insert_or_assign(
ev->cookie,
PendingMove{
.path = full_path,
.is_directory = is_dir,
.expires_at = std::chrono::steady_clock::now() +
options.rename_pair_window,
});
} else {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
if (!should_ignore(full_path, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
return;
}
if ((ev->mask & IN_MOVED_TO) != 0U) {
if (ev->cookie != 0U) {
if (auto mit = pending_moves.find(ev->cookie);
mit != pending_moves.end()) {
const std::filesystem::path old_path =
std::move(mit->second.path);
pending_moves.erase(mit);
const bool old_ignored = should_ignore(old_path, is_dir);
const bool new_ignored = should_ignore(full_path, is_dir);
if (is_dir) {
if (new_ignored) {
remove_subtree_watches_locked(old_path);
} else {
rewrite_subtree_watches_locked(old_path, full_path);
attach_subtree_locked(full_path, false);
}
}
if (!old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Renamed,
.path = full_path,
.old_path = old_path,
.is_directory = is_dir,
.detail = {},
});
} else if (!old_ignored && new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = old_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
} else if (old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
return;
}
}
if (should_ignore(full_path, is_dir)) {
return;
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
return;
}
if (should_ignore(full_path, is_dir)) {
return;
}
if ((ev->mask & IN_CREATE) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
}
if ((ev->mask & IN_DELETE) != 0U) {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & (IN_MODIFY | IN_CLOSE_WRITE)) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Modified,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & IN_ATTRIB) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::AttributeChanged,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
drain_inotify_locked()
{
alignas(struct inotify_event) std::array<char, 16384> buf{};
for (;;) {
const ssize_t n =
::read(inotify_fd.get(), buf.data(), buf.size());
if (n > 0) {
ssize_t offset = 0;
while (offset < n) {
const auto* ev =
reinterpret_cast<const struct inotify_event*>(
buf.data() + offset);
process_inotify_event_locked(ev);
offset += static_cast<ssize_t>(
sizeof(struct inotify_event) + ev->len);
}
continue;
}
if (n == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher: read(inotify) failed",
err)};
}
return {};
}
void drain_wake_locked() noexcept
{
std::uint64_t val = 0;
while (::read(wake_fd.get(), &val, sizeof(val)) > 0 ||
(errno == EINTR)) {
}
}
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path& root,
DirectoryWatcherOptions options)
{
if (root.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::create: root cannot be empty")};
}
std::error_code ec;
const auto st = std::filesystem::status(root, ec);
if (ec || !std::filesystem::is_directory(st)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::not_found,
std::format(
"FileSystem::DirectoryWatcher::create: '{}' is not a directory",
root.string()))};
}
const int ifd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (ifd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: inotify_init1 failed",
err)};
}
Void::System::OwnedFd owned_ifd{ifd};
const int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (efd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: eventfd failed",
err)};
}
Void::System::OwnedFd owned_efd{efd};
auto impl = std::make_unique<Impl>();
impl->inotify_fd = std::move(owned_ifd);
impl->wake_fd = std::move(owned_efd);
impl->root = std::filesystem::weakly_canonical(root, ec);
if (ec || impl->root.empty()) {
impl->root = root.lexically_normal();
}
impl->options = std::move(options);
{
std::lock_guard lock{impl->mutex};
impl->attach_subtree_locked(impl->root, false);
}
return DirectoryWatcher{std::move(impl)};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds timeout)
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::poll: moved-from watcher")};
}
const auto start = std::chrono::steady_clock::now();
const auto end_time = start + std::max(std::chrono::milliseconds{0}, timeout);
int ifd = -1;
int efd = -1;
{
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
timeout.count() <= 0);
if (!impl_->queue.empty() && impl_->pending_moves.empty()) {
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
ifd = impl_->inotify_fd.get();
efd = impl_->wake_fd.get();
}
if (timeout.count() > 0) {
for (;;) {
const auto now = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point wait_until = end_time;
{
std::lock_guard lock{impl_->mutex};
for (const auto& [_, pm] : impl_->pending_moves) {
wait_until = std::min(wait_until, pm.expires_at);
}
}
if (now >= wait_until) {
std::lock_guard lock{impl_->mutex};
impl_->flush_expired_moves_locked(now, false);
if (now >= end_time ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
continue;
}
const auto rem_ms = std::max<long long>(
1,
std::chrono::duration_cast<std::chrono::milliseconds>(
wait_until - now)
.count());
std::array<struct pollfd, 2> pfds{{
{ifd, POLLIN, 0},
{efd, POLLIN, 0},
}};
const int rc =
::poll(pfds.data(), pfds.size(), static_cast<int>(rem_ms));
if (rc < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::poll: poll failed",
err)};
}
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
const bool woken = (pfds[1].revents & POLLIN) != 0;
if (woken) {
impl_->drain_wake_locked();
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
false);
if (woken ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
}
}
std::lock_guard lock{impl_->mutex};
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::rescan: moved-from watcher")};
}
std::lock_guard lock{impl_->mutex};
for (const auto& [wd, _] : impl_->wd_to_path) {
(void)::inotify_rm_watch(impl_->inotify_fd.get(), wd);
}
impl_->wd_to_path.clear();
impl_->path_to_wd.clear();
impl_->pending_moves.clear();
impl_->queue.clear();
impl_->rescan_emitted = false;
impl_->attach_subtree_locked(impl_->root, false);
return {};
}
void DirectoryWatcher::wake() noexcept
{
if (!impl_ || !impl_->wake_fd.valid()) {
return;
}
const std::uint64_t one = 1;
while (::write(impl_->wake_fd.get(), &one, sizeof(one)) < 0 &&
errno == EINTR) {
}
}
void DirectoryWatcher::simulate_overflow_for_test()
{
if (!impl_) {
return;
}
{
std::lock_guard lock{impl_->mutex};
impl_->push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = impl_->root,
.old_path = {},
.is_directory = true,
.detail = "simulated IN_Q_OVERFLOW",
});
}
wake();
}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept
{
if (!impl_) {
return 0;
}
std::lock_guard lock{impl_->mutex};
return impl_->wd_to_path.size();
}
int DirectoryWatcher::native_handle() const noexcept
{
return impl_ ? impl_->inotify_fd.get() : -1;
}
#else
struct DirectoryWatcher::Impl {
std::filesystem::path root{};
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path&,
DirectoryWatcherOptions)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: inotify watcher is Linux-only")};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
void DirectoryWatcher::wake() noexcept {}
void DirectoryWatcher::simulate_overflow_for_test() {}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept { return 0; }
int DirectoryWatcher::native_handle() const noexcept { return -1; }
#endif
} // namespace Void::FileSystem
+192 -54
View File
@@ -40,6 +40,7 @@ Child::Child(Child&&) noexcept = default;
Child& Child::operator=(Child&&) noexcept = default; Child& Child::operator=(Child&&) noexcept = default;
bool Child::valid() const noexcept { return false; } bool Child::valid() const noexcept { return false; }
bool Child::running() const noexcept { return false; } bool Child::running() const noexcept { return false; }
bool Child::process_group_alive() const noexcept { return false; }
long long Child::pid() const noexcept { return -1; } long long Child::pid() const noexcept { return -1; }
long long Child::pgid() const noexcept { return -1; } long long Child::pgid() const noexcept { return -1; }
bool Child::owns_process_group() const noexcept { return false; } bool Child::owns_process_group() const noexcept { return false; }
@@ -142,6 +143,13 @@ Void::Result::Result<void, Void::Result::Error> reexec(
return Void::Result::fail("Process::reexec: not implemented on Windows"); return Void::Result::fail("Process::reexec: not implemented on Windows");
} }
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: not supported on Windows")};
}
} // namespace Void::Process } // namespace Void::Process
#else // POSIX #else // POSIX
@@ -150,6 +158,9 @@ Void::Result::Result<void, Void::Result::Error> reexec(
#include <fcntl.h> #include <fcntl.h>
#include <poll.h> #include <poll.h>
#include <signal.h> #include <signal.h>
#if defined(__linux__) && __has_include(<sys/prctl.h>)
#include <sys/prctl.h>
#endif
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/syscall.h> #include <sys/syscall.h>
#include <sys/wait.h> #include <sys/wait.h>
@@ -468,26 +479,102 @@ void write_child_failure(int err_fd, int phase, int err) noexcept
return st; return st;
} }
[[nodiscard]] bool is_process_group_alive(pid_t pgid) noexcept
{
if (pgid <= 0) {
return false;
}
for (;;) {
if (::kill(-pgid, 0) == 0) {
return true;
}
if (errno == EINTR) {
continue;
}
return errno == EPERM;
}
}
void reap_group_nonblocking(pid_t pid,
pid_t pgid,
bool owns_group,
bool& reaped,
ExitStatus& cached,
int& out_errno) noexcept
{
out_errno = 0;
if (!reaped && pid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(pid, &raw, WNOHANG);
if (w == pid) {
cached = decode_wait_status(raw);
reaped = true;
break;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped = true;
break;
}
out_errno = errno;
break;
}
}
if (owns_group && pgid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(-pgid, &raw, WNOHANG);
if (w > 0) {
if (w == pid && !reaped) {
cached = decode_wait_status(raw);
reaped = true;
}
continue;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
break;
}
}
}
[[nodiscard]] bool signal_target(pid_t pid, [[nodiscard]] bool signal_target(pid_t pid,
pid_t pgid, pid_t pgid,
bool owns_group, bool owns_group,
bool leader_reaped,
int sig, int sig,
int& out_errno) noexcept int& out_errno) noexcept
{ {
bool delivered = false;
out_errno = 0;
if (owns_group && pgid > 0) { if (owns_group && pgid > 0) {
if (::kill(-pgid, sig) == 0) { if (::kill(-pgid, sig) == 0) {
return true; delivered = true;
} } else {
out_errno = errno; out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) { if (out_errno != ESRCH && out_errno != EPERM) {
return false; return false;
}
} }
} }
if (::kill(pid, sig) == 0) { if (!leader_reaped && pid > 0) {
return true; if (::kill(pid, sig) == 0) {
delivered = true;
} else {
out_errno = errno;
}
} }
out_errno = errno; return delivered;
return false;
} }
[[nodiscard]] std::optional<std::string> [[nodiscard]] std::optional<std::string>
@@ -706,6 +793,13 @@ Child& Child::operator=(Child&& other) noexcept
bool Child::valid() const noexcept { return pid_ > 0; } bool Child::valid() const noexcept { return pid_ > 0; }
bool Child::running() const noexcept { return pid_ > 0 && !reaped_; } bool Child::running() const noexcept { return pid_ > 0 && !reaped_; }
bool Child::process_group_alive() const noexcept
{
if (owns_group_ && pgid_ > 0) {
return is_process_group_alive(static_cast<pid_t>(pgid_));
}
return running();
}
long long Child::pid() const noexcept { return pid_; } long long Child::pid() const noexcept { return pid_; }
long long Child::pgid() const noexcept { return pgid_; } long long Child::pgid() const noexcept { return pgid_; }
bool Child::owns_process_group() const noexcept { return owns_group_; } bool Child::owns_process_group() const noexcept { return owns_group_; }
@@ -738,7 +832,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
Void::System::SystemErrorCode::invalid_argument, Void::System::SystemErrorCode::invalid_argument,
"Process::Child::send_signal: invalid child")}; "Process::Child::send_signal: invalid child")};
} }
if (reaped_) { if (reaped_ && (!owns_group_ || !process_group_alive())) {
return std::unexpected{Void::System::make_system_error( return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy, Void::System::SystemErrorCode::busy,
"Process::Child::send_signal: child already reaped")}; "Process::Child::send_signal: child already reaped")};
@@ -747,6 +841,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
if (!signal_target(static_cast<pid_t>(pid_), if (!signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_), static_cast<pid_t>(pgid_),
owns_group_, owns_group_,
reaped_,
sig, sig,
err)) { err)) {
return std::unexpected{Void::System::make_system_error( return std::unexpected{Void::System::make_system_error(
@@ -798,35 +893,37 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
Void::System::SystemErrorCode::invalid_argument, Void::System::SystemErrorCode::invalid_argument,
"Process::Child::terminate: invalid child")}; "Process::Child::terminate: invalid child")};
} }
if (reaped_) {
const pid_t target_pid = static_cast<pid_t>(pid_);
const pid_t target_pgid = static_cast<pid_t>(pgid_);
const bool group_owned = owns_group_ && target_pgid > 0;
auto group_finished = [&]() noexcept -> bool {
int reap_err = 0;
reap_group_nonblocking(
target_pid, target_pgid, group_owned, reaped_, cached_status_, reap_err);
if (!reaped_) {
return false;
}
return !group_owned || !is_process_group_alive(target_pgid);
};
if (group_finished()) {
return cached_status_; return cached_status_;
} }
const auto effective_grace = const auto effective_grace =
(grace.count() >= 0) ? grace : kill_grace_; (grace.count() >= 0) ? grace : kill_grace_;
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
}
int sig_err = 0; int sig_err = 0;
(void)signal_target(static_cast<pid_t>(pid_), (void)signal_target(
static_cast<pid_t>(pgid_), target_pid, target_pgid, group_owned, reaped_, SIGTERM, sig_err);
owns_group_,
SIGTERM,
sig_err);
const auto grace_deadline = const auto grace_deadline =
std::chrono::steady_clock::now() + effective_grace; std::chrono::steady_clock::now() + effective_grace;
while (std::chrono::steady_clock::now() < grace_deadline) { while (std::chrono::steady_clock::now() < grace_deadline) {
auto polled = try_wait(); if (group_finished()) {
if (!polled.has_value()) { return cached_status_;
return std::unexpected{polled.error()};
}
if (polled->has_value()) {
return **polled;
} }
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>( const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
grace_deadline - std::chrono::steady_clock::now()); grace_deadline - std::chrono::steady_clock::now());
@@ -834,38 +931,61 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
break; break;
} }
std::this_thread::sleep_for( std::this_thread::sleep_for(
std::min(rem, std::chrono::milliseconds{10})); std::min(rem, std::chrono::milliseconds{5}));
} }
if (auto polled = try_wait(); !polled.has_value()) { if (group_finished()) {
return std::unexpected{polled.error()}; return cached_status_;
} else if (polled->has_value()) {
return **polled;
} }
(void)signal_target(static_cast<pid_t>(pid_), (void)signal_target(
static_cast<pid_t>(pgid_), target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err);
owns_group_,
SIGKILL,
sig_err);
int raw = 0; if (!reaped_) {
for (;;) { int raw = 0;
const pid_t w = ::waitpid(static_cast<pid_t>(pid_), &raw, 0); for (;;) {
if (w == static_cast<pid_t>(pid_)) { const pid_t w = ::waitpid(target_pid, &raw, 0);
cached_status_ = decode_wait_status(raw); if (w == target_pid) {
reaped_ = true; cached_status_ = decode_wait_status(raw);
return cached_status_; reaped_ = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped_ = true;
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
} }
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
} }
if (group_owned) {
const auto kill_ceiling =
std::chrono::steady_clock::now() + std::chrono::seconds{5};
while (!group_finished()) {
if (std::chrono::steady_clock::now() >= kill_ceiling) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::Child::terminate: process group members failed "
"to exit after SIGKILL")};
}
(void)signal_target(target_pid,
target_pgid,
group_owned,
reaped_,
SIGKILL,
sig_err);
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
return cached_status_;
} }
Void::Result::Result<ExitStatus, Void::Result::Error> Child::wait_blocking( Void::Result::Result<ExitStatus, Void::Result::Error> Child::wait_blocking(
@@ -950,7 +1070,7 @@ void Child::reset_and_reap() noexcept
stdin_.reset(); stdin_.reset();
stdout_.reset(); stdout_.reset();
stderr_.reset(); stderr_.reset();
if (pid_ > 0 && !reaped_) { if (pid_ > 0 && (!reaped_ || process_group_alive())) {
(void)terminate(kill_grace_); (void)terminate(kill_grace_);
} }
pid_ = -1; pid_ = -1;
@@ -1643,6 +1763,24 @@ Void::Result::Result<void, Void::Result::Error>
err)}; err)};
} }
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
#if defined(__linux__) && defined(PR_SET_CHILD_SUBREAPER)
if (::prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::enable_subreaper: prctl(PR_SET_CHILD_SUBREAPER) failed",
err)};
}
return {};
#else
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: PR_SET_CHILD_SUBREAPER unavailable on this platform")};
#endif
}
} // namespace Void::Process } // namespace Void::Process
#endif // _WIN32 #endif // _WIN32
+59
View File
@@ -133,6 +133,9 @@ if(_all_generated)
if(TARGET OpenSSL::Crypto) if(TARGET OpenSSL::Crypto)
target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto) target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto)
endif() endif()
if(TARGET OpenSSL::SSL)
target_link_libraries(VoidTests PRIVATE OpenSSL::SSL)
endif()
if(TARGET SQLite3::SQLite3) if(TARGET SQLite3::SQLite3)
target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3) target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3)
endif() endif()
@@ -252,4 +255,60 @@ if(TARGET VoidTests AND TARGET Void::Plugin)
) )
add_dependencies(VoidTests VoidServicePluginV1 VoidServicePluginV2) add_dependencies(VoidTests VoidServicePluginV1 VoidServicePluginV2)
endif() endif()
enable_language(C)
function(_void_add_cabi_fixture target_name source_file)
add_library(${target_name} SHARED "${CMAKE_CURRENT_SOURCE_DIR}/plugins/${source_file}")
target_include_directories(${target_name} PRIVATE "${CMAKE_SOURCE_DIR}/include")
set_target_properties(${target_name} PROPERTIES
C_STANDARD 11
C_STANDARD_REQUIRED ON
C_EXTENSIONS OFF
VOID_TESTING_NO_AUTO_SCAN TRUE)
if(VOID_WARNINGS_AS_ERRORS)
target_compile_options(${target_name} PRIVATE -Wall -Wextra -Wpedantic -Werror)
endif()
find_package(Threads QUIET)
if(TARGET Threads::Threads)
target_link_libraries(${target_name} PRIVATE Threads::Threads)
endif()
if(VOID_ENABLE_ASAN)
target_compile_options(${target_name} PRIVATE -fsanitize=address -fno-omit-frame-pointer)
target_link_options(${target_name} PRIVATE -fsanitize=address)
endif()
if(VOID_ENABLE_UBSAN)
target_compile_options(${target_name} PRIVATE -fsanitize=undefined)
target_link_options(${target_name} PRIVATE -fsanitize=undefined)
endif()
if(VOID_ENABLE_TSAN)
target_compile_options(${target_name} PRIVATE -fsanitize=thread)
target_link_options(${target_name} PRIVATE -fsanitize=thread)
endif()
foreach(_def IN LISTS ARGN)
target_compile_definitions(${target_name} PRIVATE "${_def}")
endforeach()
add_dependencies(VoidTests ${target_name})
endfunction()
_void_add_cabi_fixture(VoidCAbiPluginV1 CAbiPluginV1.c)
_void_add_cabi_fixture(VoidCAbiPluginV2 CAbiPluginV2.c)
_void_add_cabi_fixture(VoidCAbiBadTrunc CAbiBadPlugin.c "BAD_MODE=1")
_void_add_cabi_fixture(VoidCAbiBadMajor CAbiBadPlugin.c "BAD_MODE=2")
_void_add_cabi_fixture(VoidCAbiBadReserved CAbiBadPlugin.c "BAD_MODE=3")
_void_add_cabi_fixture(VoidCAbiDepA CAbiDepPlugin.c "DEP_MODE=1")
_void_add_cabi_fixture(VoidCAbiDepB CAbiDepPlugin.c "DEP_MODE=2")
_void_add_cabi_fixture(VoidCAbiCycA CAbiDepPlugin.c "DEP_MODE=3")
_void_add_cabi_fixture(VoidCAbiCycB CAbiDepPlugin.c "DEP_MODE=4")
target_compile_definitions(VoidTests PRIVATE
"VOID_CABI_V1_PATH=\"$<TARGET_FILE:VoidCAbiPluginV1>\""
"VOID_CABI_V2_PATH=\"$<TARGET_FILE:VoidCAbiPluginV2>\""
"VOID_CABI_BAD_TRUNC_PATH=\"$<TARGET_FILE:VoidCAbiBadTrunc>\""
"VOID_CABI_BAD_MAJOR_PATH=\"$<TARGET_FILE:VoidCAbiBadMajor>\""
"VOID_CABI_BAD_RESERVED_PATH=\"$<TARGET_FILE:VoidCAbiBadReserved>\""
"VOID_CABI_DEP_A_PATH=\"$<TARGET_FILE:VoidCAbiDepA>\""
"VOID_CABI_DEP_B_PATH=\"$<TARGET_FILE:VoidCAbiDepB>\""
"VOID_CABI_CYC_A_PATH=\"$<TARGET_FILE:VoidCAbiCycA>\""
"VOID_CABI_CYC_B_PATH=\"$<TARGET_FILE:VoidCAbiCycB>\""
)
endif() endif()
+54
View File
@@ -194,6 +194,57 @@ int mode_ignore_sigterm(int argc, char** argv)
return 0; return 0;
} }
int mode_grandchild_ignore_sigterm(int argc, char** argv)
{
if (argc < 3) {
return usage_error("grandchild-ignore-sigterm requires <marker_file>");
}
const char* marker_path = argv[2];
int ready_p[2]{-1, -1};
if (::pipe(ready_p) != 0) {
return 1;
}
const pid_t gc = ::fork();
if (gc < 0) {
(void)::close(ready_p[0]);
(void)::close(ready_p[1]);
return 1;
}
if (gc == 0) {
(void)::close(ready_p[0]);
std::signal(SIGTERM, SIG_IGN);
const int mfd = ::open(marker_path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
if (mfd < 0) {
(void)::close(ready_p[1]);
::_exit(1);
}
static constexpr char kTick[] = "tick\n";
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
static constexpr char kReady[] = "ready\n";
(void)write_all_fd(STDOUT_FILENO, kReady, sizeof(kReady) - 1);
const char one = '1';
(void)write_all_fd(ready_p[1], &one, 1);
(void)::close(ready_p[1]);
(void)::close(STDIN_FILENO);
(void)::close(STDOUT_FILENO);
(void)::close(STDERR_FILENO);
for (int iter = 0; iter < 500; ++iter) {
std::this_thread::sleep_for(std::chrono::milliseconds{10});
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
}
(void)::close(mfd);
::_exit(0);
}
(void)::close(ready_p[1]);
char dummy = 0;
bool eof = false;
(void)read_exact_fd(ready_p[0], &dummy, 1, eof);
(void)::close(ready_p[0]);
::_exit(0);
}
int mode_simultaneous_io(int argc, char** argv) int mode_simultaneous_io(int argc, char** argv)
{ {
if (argc != 3) { if (argc != 3) {
@@ -485,6 +536,9 @@ int main(int argc, char** argv)
if (mode == "ignore-sigterm") { if (mode == "ignore-sigterm") {
return mode_ignore_sigterm(argc, argv); return mode_ignore_sigterm(argc, argv);
} }
if (mode == "grandchild-ignore-sigterm") {
return mode_grandchild_ignore_sigterm(argc, argv);
}
if (mode == "simultaneous-io") { if (mode == "simultaneous-io") {
return mode_simultaneous_io(argc, argv); return mode_simultaneous_io(argc, argv);
} }
+5 -2
View File
@@ -50,8 +50,11 @@ namespace
struct Work : State { struct Work : State {
Task<StateKey> run() Task<StateKey> run()
{ {
auto& svc = service<VoidTest::ICalc>(); auto svc = acquire_service<VoidTest::ICalc>();
const int total = svc.accumulate(1); if (!svc) {
co_return next<Work>();
}
const int total = (*svc)->accumulate(1);
if (total >= 500) { if (total >= 500) {
co_return succeed(total); co_return succeed(total);
} }
+5 -1
View File
@@ -12,8 +12,12 @@ int main()
.content = {std::byte{'h'}, std::byte{'i'}}, .content = {std::byte{'h'}, std::byte{'i'}},
}, },
}}; }};
Void::Archive::CreationOptions opts;
opts.compression = Void::Archive::has_libarchive_backend()
? Void::Archive::ArchiveCompression::Zstd
: Void::Archive::ArchiveCompression::None;
Void::Archive::VectorByteSink sink; Void::Archive::VectorByteSink sink;
if (!Void::Archive::create_archive(sink, entries).has_value()) { if (!Void::Archive::create(sink, entries, opts).has_value()) {
return 1; return 1;
} }
Void::Archive::SpanByteSource src{sink.bytes()}; Void::Archive::SpanByteSource src{sink.bytes()};
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidConfigurationAsyncOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS ConfigurationAsync)
add_executable(void_configuration_async_only_consumer main.cpp)
target_link_libraries(void_configuration_async_only_consumer PRIVATE Void::ConfigurationAsync)
target_compile_features(void_configuration_async_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME ConfigurationAsyncOnlyConsumer COMMAND void_configuration_async_only_consumer)
@@ -0,0 +1,20 @@
#include <Void/Async/Executor.hpp>
#include <Void/Configuration/ReloadController.hpp>
#include <string>
struct AsyncCfg {
std::string mode{"ok"};
};
int main()
{
Void::Async::ManualExecutor exec;
Void::Configuration::SourceSet ss;
ss.add_defaults_map("d", {{"mode", "fast"}});
auto schema = Void::Configuration::Schema<AsyncCfg>::from_reflection();
auto ctrl = Void::Configuration::ReloadController<AsyncCfg>::create(
schema, std::move(ss), {.executor = &exec});
if (!ctrl) return 1;
return (*ctrl)->current().values->mode == "fast" ? 0 : 2;
}
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidConfigurationOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Configuration)
add_executable(void_configuration_only_consumer main.cpp)
target_link_libraries(void_configuration_only_consumer PRIVATE Void::Configuration)
target_compile_features(void_configuration_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME ConfigurationOnlyConsumer COMMAND void_configuration_only_consumer)
+21
View File
@@ -0,0 +1,21 @@
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Configuration/Schema.hpp>
#include <string>
struct MinimalCfg {
[[= Void::Configuration::Required{}]] std::string name;
[[= Void::Configuration::IntRange{1, 100}]] int workers{4};
};
int main()
{
Void::Configuration::SourceSet ss;
ss.add_defaults_map("def", {{"name", "svc"}, {"workers", "8"}});
auto schema = Void::Configuration::Schema<MinimalCfg>::from_reflection();
auto merged = Void::Configuration::load_sources(ss, schema.limits());
if (!merged) return 1;
auto val = Void::Configuration::validate<MinimalCfg>(*merged, schema);
return val && val->value.name == "svc" && val->value.workers == 8 ? 0 : 2;
}
+23 -13
View File
@@ -9,23 +9,33 @@ int main()
if (!digest.has_value() || digest->size() != 32) { if (!digest.has_value() || digest->size() != 32) {
return 1; return 1;
} }
auto key = Void::Crypto::Ed25519PrivateKey::generate(); auto b2 = Void::Crypto::blake2b256("abc");
if (!key.has_value()) { if (!b2.has_value() || b2->size() != 32) {
return 2; return 6;
}
auto pub = key->public_key();
if (!pub.has_value()) {
return 3;
} }
const std::array<std::byte, 4> msg{std::byte{1}, std::byte{2}, std::byte{3}, const std::array<std::byte, 4> msg{std::byte{1}, std::byte{2}, std::byte{3},
std::byte{4}}; std::byte{4}};
auto sig = Void::Crypto::sign_ed25519(msg, *key); auto mac = Void::Crypto::hmac_sha256(msg, msg);
if (!sig.has_value()) { if (!mac.has_value() || mac->size() != Void::Crypto::HmacSha256Size) {
return 4; return 7;
} }
auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub); if (Void::Crypto::has_openssl_backend()) {
if (!ok.has_value() || !*ok) { auto key = Void::Crypto::Ed25519PrivateKey::generate();
return 5; if (!key.has_value()) {
return 2;
}
auto pub = key->public_key();
if (!pub.has_value()) {
return 3;
}
auto sig = Void::Crypto::sign_ed25519(msg, *key);
if (!sig.has_value()) {
return 4;
}
auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub);
if (!ok.has_value() || !*ok) {
return 5;
}
} }
return 0; return 0;
} }
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidFsmOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Fsm)
add_executable(void_fsm_only_consumer main.cpp)
target_link_libraries(void_fsm_only_consumer PRIVATE Void::Fsm)
target_compile_features(void_fsm_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME FsmOnlyConsumer COMMAND void_fsm_only_consumer)
+47
View File
@@ -0,0 +1,47 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Fsm/Fsm.hpp>
#include <Void/Fsm/Orchestrator.hpp>
#include <Void/Time/Clock.hpp>
#include <optional>
struct ConsumerMachine : public Void::Fsm::Machine<ConsumerMachine> {
using Success = int;
struct States {
struct Start : State {
Void::Coro::Task<Void::Fsm::StateKey> run()
{
co_return succeed(42);
}
};
};
};
Void::Coro::Task<void> drive_consumer_fsm(
Void::Fsm::ExecutionBinding binding,
std::optional<Void::Result::Result<ConsumerMachine::Outcome<>>>* out)
{
ConsumerMachine fsm;
*out = co_await fsm.run(binding);
}
int main()
{
if (!Void::Fsm::terminal(Void::Fsm::Status::Faulted)) {
return 1;
}
Void::Async::ManualExecutor exec;
Void::Time::ManualClock clock;
std::optional<Void::Result::Result<ConsumerMachine::Outcome<>>> out;
Void::Async::spawn(
exec,
drive_consumer_fsm(
{.executor = &exec, .clock = &clock}, &out));
(void)exec.drain();
if (!out.has_value() || !out->has_value() || !out->value().has_value()) {
return 2;
}
return out->value().value() == 42 ? 0 : 3;
}
+63
View File
@@ -237,6 +237,69 @@ if(_has_storage)
run_consumer(StorageOnly "${install_prefix}" "StorageOnly" ${_no_external_deps}) run_consumer(StorageOnly "${install_prefix}" "StorageOnly" ${_no_external_deps})
endif() endif()
has_modules(_has_service Service Core Functional Time Async LogState)
if(_has_service)
run_consumer(ServiceOnly "${install_prefix}" "ServiceOnly" ${_no_external_deps})
endif()
has_modules(_has_service_plugin ServicePlugin Service Plugin Functional System Data LogState Text Time Async Core)
if(_has_service_plugin)
run_consumer(ServicePluginOnly "${install_prefix}" "ServicePluginOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_plugin Plugin Core Functional System Data Time Async LogState Text Service)
if(_has_plugin)
run_consumer(PluginOnly "${install_prefix}" "PluginOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_configuration Configuration Core Functional System Data Time LogState)
if(_has_configuration)
run_consumer(ConfigurationOnly "${install_prefix}" "ConfigurationOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_configuration_async ConfigurationAsync Configuration SystemAsync Async Time Functional LogState)
if(_has_configuration_async)
run_consumer(ConfigurationAsyncOnly "${install_prefix}" "ConfigurationAsyncOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_fsm Fsm Async Core Data Functional Time Log Service)
if(_has_fsm)
run_consumer(FsmOnly "${install_prefix}" "FsmOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_net Net Functional Text)
if(_has_net)
run_consumer(NetOnly "${install_prefix}" "NetOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
# Foundation consumer with Core-formatting bridge and zero external packages. # Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation) if(_has_foundation)
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidNetOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Net)
add_executable(void_net_only_consumer main.cpp)
target_link_libraries(void_net_only_consumer PRIVATE Void::Net)
target_compile_features(void_net_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME NetOnlyConsumer COMMAND void_net_only_consumer)
+31
View File
@@ -0,0 +1,31 @@
#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <string>
int main()
{
Void::Net::HttpServer server;
if (!server
.add_route(Void::Net::Method::Get, "/ping",
[](const Void::Net::ServerRequest&) {
return Void::Result::ok(Void::Net::ServerResponse{
.status = 200, .body = "pong"});
})
.has_value()) {
return 1;
}
if (!server.start().has_value() || server.bound_port() == 0) {
return 2;
}
auto client = Void::Net::HttpClient::secure();
if (!client.verify_tls()) {
return 3;
}
auto resp = client.get(server.base_url() + "/ping");
server.shutdown();
if (!resp.has_value() || resp->status != 200 || resp->body != "pong") {
return 4;
}
return 0;
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidPluginOnlyConsumer LANGUAGES C CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Plugin)
add_executable(void_plugin_only_consumer main.cpp)
target_link_libraries(void_plugin_only_consumer PRIVATE Void::Plugin)
target_compile_features(void_plugin_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME PluginOnlyConsumer COMMAND void_plugin_only_consumer)
+18
View File
@@ -0,0 +1,18 @@
#include <Void/Plugin/CAbi.h>
#include <Void/Plugin/CAbiAdapter.hpp>
#include <Void/Plugin/Host.hpp>
#include <Void/Plugin/Manager.hpp>
#include <cstring>
int main()
{
Void::Plugin::PluginHostLimits limits{};
Void::Plugin::CModuleHost host{limits};
const auto loaded = host.acquire("missing");
void_module_api_v1 api{};
api.struct_size = sizeof(api);
api.abi_major = VOID_CABI_MAJOR_V1;
api.abi_minor = VOID_CABI_MINOR_V1;
return !loaded && api.abi_major == 1u ? 0 : 1;
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidServiceOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Service)
add_executable(void_service_only_consumer main.cpp)
target_link_libraries(void_service_only_consumer PRIVATE Void::Service)
target_compile_features(void_service_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME ServiceOnlyConsumer COMMAND void_service_only_consumer)
+36
View File
@@ -0,0 +1,36 @@
#include <Void/Service/Registry.hpp>
#include <Void/Service/Service.hpp>
#include <Void/Service/Types.hpp>
#include <memory>
#include <string_view>
namespace
{
struct ICounter {
virtual ~ICounter() = default;
virtual int value() const = 0;
};
struct Counter final : Void::Service::IManagedService, ICounter {
std::string_view service_name() const override { return "counter"; }
int value() const override { return 42; }
};
} // namespace
int main()
{
Void::Service::ServiceRegistry reg;
Void::Service::ProviderSet set;
set.add<ICounter>("counter", std::make_shared<Counter>());
auto ep = reg.start_and_publish(std::move(set));
if (!ep) {
return 1;
}
auto handle = reg.acquire<ICounter>();
if (!handle || (*handle)->value() != 42 || handle->generation() != *ep) {
return 2;
}
auto report = reg.close_and_join();
return report && !report->clean() ? 0 : 3; // handle still held until return
}
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidServicePluginOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS ServicePlugin)
add_executable(void_service_plugin_only_consumer main.cpp)
target_link_libraries(void_service_plugin_only_consumer PRIVATE Void::ServicePlugin)
target_compile_features(void_service_plugin_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME ServicePluginOnlyConsumer COMMAND void_service_plugin_only_consumer)
+12
View File
@@ -0,0 +1,12 @@
#include <Void/Service/PluginService.hpp>
int main()
{
Void::Plugin::PluginManager plugins;
Void::Service::ServiceRegistry registry;
Void::Service::PluginServiceBinding<Void::Service::IService> binding{
plugins, registry, "missing"};
auto direct = Void::Service::acquire_plugin_service<Void::Service::IService>(
plugins, "missing");
return !binding.bind() && !direct.has_value() ? 0 : 1;
}
@@ -0,0 +1,12 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
VOID_TEST(NativeGxx, from_dir_a_first)
{
Void::Testing::expect_eq(10 + 5, 15);
}
VOID_TEST(NativeGxx, duplicate_name_test)
{
Void::Testing::expect(true);
}
@@ -0,0 +1,12 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
VOID_TEST(NativeGxx, from_dir_b_first)
{
Void::Testing::expect_eq(6 * 7, 42);
}
VOID_TEST(NativeGxx, duplicate_name_test)
{
Void::Testing::expect_eq(1, 1);
}
+78
View File
@@ -0,0 +1,78 @@
#include <Void/Plugin/CAbi.h>
#include <stdint.h>
#include <string.h>
#ifndef BAD_MODE
#define BAD_MODE 1
#endif
static int32_t stub_get_info(void_module_info_v1* out)
{
if (out == NULL) return VOID_STATUS_INVALID_ARGUMENT;
memset(out, 0, sizeof(*out));
out->struct_size = (uint32_t)sizeof(void_module_info_v1);
out->module_id = "cabi.bad";
out->version = "1.0.0";
return VOID_STATUS_OK;
}
static int32_t stub_create(const void_host_api_v1* h, void_module_handle** out)
{
(void)h;
if (out != NULL) *out = NULL;
return VOID_STATUS_INTERNAL;
}
static int32_t stub_activate(void_module_handle* h, void_bytes_v1 c, void_error_detail_v1* e)
{
(void)h; (void)c; (void)e;
return VOID_STATUS_OK;
}
static int32_t stub_readiness(void_module_handle* h, uint32_t* r, void_error_detail_v1* e)
{
(void)h; (void)r; (void)e;
return VOID_STATUS_OK;
}
static int32_t stub_stop(void_module_handle* h)
{
(void)h;
return VOID_STATUS_OK;
}
static void stub_destroy(void_module_handle* h) { (void)h; }
int32_t void_module_query_v1(uint32_t host_struct_size,
void_module_api_v1* out_api)
{
(void)host_struct_size;
if (out_api == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
memset(out_api, 0, sizeof(*out_api));
out_api->struct_size = (uint32_t)sizeof(void_module_api_v1);
out_api->abi_major = VOID_CABI_MAJOR_V1;
out_api->abi_minor = VOID_CABI_MINOR_V1;
out_api->reserved = 0;
out_api->get_info = stub_get_info;
out_api->create = stub_create;
out_api->activate = stub_activate;
out_api->readiness = stub_readiness;
out_api->request_stop = stub_stop;
out_api->deactivate = stub_stop;
out_api->destroy = stub_destroy;
#if BAD_MODE == 1
/* Truncated struct_size */
out_api->struct_size = 16u;
#elif BAD_MODE == 2
/* Unsupported abi_major */
out_api->abi_major = 99u;
#elif BAD_MODE == 3
/* Non-zero reserved */
out_api->reserved = 1u;
#endif
return VOID_STATUS_OK;
}
+104
View File
@@ -0,0 +1,104 @@
#include <Void/Plugin/CAbi.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifndef DEP_MODE
#define DEP_MODE 1
#endif
struct void_module_handle {
int dummy;
};
#if DEP_MODE == 2
static const void_dependency_v1 kDeps[] = {
{.module_id = "cabi.dep.a", .version_range = "^1.0.0", .optional_dep = 0},
};
#elif DEP_MODE == 3
static const void_dependency_v1 kDeps[] = {
{.module_id = "cabi.cyc.b", .version_range = "^1.0.0", .optional_dep = 0},
};
#elif DEP_MODE == 4
static const void_dependency_v1 kDeps[] = {
{.module_id = "cabi.cyc.a", .version_range = "^1.0.0", .optional_dep = 0},
};
#endif
static int32_t dep_get_info(void_module_info_v1* out)
{
if (out == NULL) return VOID_STATUS_INVALID_ARGUMENT;
memset(out, 0, sizeof(*out));
out->struct_size = (uint32_t)sizeof(void_module_info_v1);
#if DEP_MODE == 1
out->module_id = "cabi.dep.a";
out->version = "1.0.0";
out->activation_policy = VOID_POLICY_RESTART_REQUIRED;
#elif DEP_MODE == 2
out->module_id = "cabi.dep.b";
out->version = "1.0.0";
out->activation_policy = VOID_POLICY_RELOADABLE;
out->dependencies = kDeps;
out->dependency_count = 1u;
#elif DEP_MODE == 3
out->module_id = "cabi.cyc.a";
out->version = "1.0.0";
out->dependencies = kDeps;
out->dependency_count = 1u;
#elif DEP_MODE == 4
out->module_id = "cabi.cyc.b";
out->version = "1.0.0";
out->dependencies = kDeps;
out->dependency_count = 1u;
#endif
return VOID_STATUS_OK;
}
static int32_t dep_create(const void_host_api_v1* h, void_module_handle** out)
{
(void)h;
*out = (struct void_module_handle*)calloc(1, sizeof(struct void_module_handle));
return *out ? VOID_STATUS_OK : VOID_STATUS_EXHAUSTED;
}
static int32_t dep_activate(void_module_handle* h, void_bytes_v1 c, void_error_detail_v1* e)
{
(void)h; (void)c; (void)e;
return VOID_STATUS_OK;
}
static int32_t dep_readiness(void_module_handle* h, uint32_t* r, void_error_detail_v1* e)
{
(void)h; (void)e;
*r = 1u;
return VOID_STATUS_OK;
}
static int32_t dep_stop(void_module_handle* h)
{
(void)h;
return VOID_STATUS_OK;
}
static void dep_destroy(void_module_handle* h) { free(h); }
int32_t void_module_query_v1(uint32_t host_struct_size,
void_module_api_v1* out_api)
{
if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) {
return VOID_STATUS_INVALID_ARGUMENT;
}
memset(out_api, 0, sizeof(*out_api));
out_api->struct_size = (uint32_t)sizeof(void_module_api_v1);
out_api->abi_major = VOID_CABI_MAJOR_V1;
out_api->abi_minor = VOID_CABI_MINOR_V1;
out_api->get_info = dep_get_info;
out_api->create = dep_create;
out_api->activate = dep_activate;
out_api->readiness = dep_readiness;
out_api->request_stop = dep_stop;
out_api->deactivate = dep_stop;
out_api->destroy = dep_destroy;
return VOID_STATUS_OK;
}
+491
View File
@@ -0,0 +1,491 @@
#define _POSIX_C_SOURCE 200809L
#include <Void/Plugin/CAbi.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct cabi_calc_v1 {
uint32_t (*version)(void_module_handle* h);
int32_t (*accumulate)(void_module_handle* h, int32_t delta);
} cabi_calc_v1;
struct void_operation_handle {
void_module_handle* owner;
pthread_t worker;
int worker_started;
atomic_int cancelled;
uint32_t op_kind;
int32_t delta;
void_async_complete_fn cb;
void* cb_ctx;
};
struct void_module_handle {
void_host_api_v1 host;
atomic_int total;
atomic_int quiescing;
int fail_quiesce;
int fail_resume;
int ckpt_fail;
int ckpt_oversized;
int ready;
pthread_mutex_t ops_mu;
struct void_operation_handle* ops[64];
size_t ops_count;
};
static const void_interface_id_v1 kCalcIfaceId = {
{0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01}};
static void free_c_str(void* ctx, const char* msg)
{
(void)ctx;
free((void*)msg);
}
static void free_c_bytes(void* ctx, const uint8_t* data, uint64_t size)
{
(void)ctx;
(void)size;
free((void*)data);
}
static void set_err(void_error_detail_v1* out_err,
int32_t status,
const char* text)
{
if (out_err == NULL || out_err->struct_size < sizeof(void_error_detail_v1)) {
return;
}
out_err->status = status;
if (text != NULL) {
size_t n = strlen(text);
char* copy = (char*)malloc(n + 1);
if (copy != NULL) {
memcpy(copy, text, n + 1);
out_err->message = copy;
out_err->release = free_c_str;
out_err->release_ctx = NULL;
}
}
}
static int cfg_has(void_bytes_v1 cfg, const char* needle)
{
if (cfg.data == NULL || cfg.size == 0) {
return 0;
}
size_t nlen = strlen(needle);
if (cfg.size < nlen) {
return 0;
}
for (uint64_t i = 0; i + nlen <= cfg.size; ++i) {
if (memcmp(cfg.data + i, needle, nlen) == 0) {
return 1;
}
}
return 0;
}
static int32_t cabi_get_info(void_module_info_v1* out_info)
{
if (out_info == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
memset(out_info, 0, sizeof(*out_info));
out_info->struct_size = (uint32_t)sizeof(void_module_info_v1);
out_info->module_id = "cabi.calc";
out_info->version = "1.0.0";
out_info->activation_policy = VOID_POLICY_RELOADABLE;
out_info->state_schema_version = 1;
out_info->dependencies = NULL;
out_info->dependency_count = 0;
return VOID_STATUS_OK;
}
static int32_t cabi_create(const void_host_api_v1* host_api,
void_module_handle** out_handle)
{
if (out_handle == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
*out_handle = NULL;
if (host_api == NULL || host_api->struct_size < sizeof(void_host_api_v1)) {
return VOID_STATUS_INVALID_ARGUMENT;
}
struct void_module_handle* h =
(struct void_module_handle*)calloc(1, sizeof(*h));
if (h == NULL) {
return VOID_STATUS_EXHAUSTED;
}
h->host = *host_api;
atomic_init(&h->total, 0);
atomic_init(&h->quiescing, 0);
h->ready = 1;
pthread_mutex_init(&h->ops_mu, NULL);
*out_handle = h;
return VOID_STATUS_OK;
}
static int32_t cabi_activate(void_module_handle* h,
void_bytes_v1 config,
void_error_detail_v1* out_err)
{
if (h == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
if (cfg_has(config, "fail_activate")) {
set_err(out_err, VOID_STATUS_INTERNAL, "V1 activation rejected");
return VOID_STATUS_INTERNAL;
}
h->ready = cfg_has(config, "not_ready") ? 0 : 1;
h->fail_quiesce = cfg_has(config, "quiesce_fail");
h->fail_resume = cfg_has(config, "quiesce_fail_resume_fail");
if (h->fail_resume) {
h->fail_quiesce = 1;
}
h->ckpt_fail = cfg_has(config, "ckpt_fail");
h->ckpt_oversized = cfg_has(config, "ckpt_oversized");
return VOID_STATUS_OK;
}
static int32_t cabi_readiness(void_module_handle* h,
uint32_t* out_ready,
void_error_detail_v1* out_err)
{
if (h == NULL || out_ready == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
*out_ready = h->ready ? 1u : 0u;
if (!h->ready) {
set_err(out_err, VOID_STATUS_NOT_READY, "V1 not ready");
}
return VOID_STATUS_OK;
}
static int32_t cabi_quiesce(void_module_handle* h,
const void_op_options_v1* opts,
void_error_detail_v1* out_err)
{
(void)opts;
if (h == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
atomic_store(&h->quiescing, 1);
if (h->fail_quiesce) {
set_err(out_err, VOID_STATUS_QUIESCING, "V1 quiesce refused");
return VOID_STATUS_QUIESCING;
}
return VOID_STATUS_OK;
}
static int32_t cabi_resume(void_module_handle* h, void_error_detail_v1* out_err)
{
if (h == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
if (h->fail_resume) {
set_err(out_err, VOID_STATUS_INTERNAL, "V1 resume failed");
return VOID_STATUS_INTERNAL;
}
atomic_store(&h->quiescing, 0);
return VOID_STATUS_OK;
}
static int32_t cabi_checkpoint(void_module_handle* h,
const void_op_options_v1* opts,
void_owned_bytes_v1* out_state,
void_error_detail_v1* out_err)
{
(void)opts;
if (h == NULL || out_state == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
memset(out_state, 0, sizeof(*out_state));
if (h->ckpt_fail) {
set_err(out_err, VOID_STATUS_INTERNAL, "V1 checkpoint error");
return VOID_STATUS_INTERNAL;
}
if (h->ckpt_oversized) {
uint8_t* dummy = (uint8_t*)malloc(16);
out_state->data = dummy;
out_state->size = UINT64_C(8) * UINT64_C(1024) * UINT64_C(1024);
out_state->release = free_c_bytes;
out_state->release_ctx = NULL;
return VOID_STATUS_OK;
}
char buf[64];
int n = snprintf(buf, sizeof(buf), "v1:%d", atomic_load(&h->total));
if (n <= 0) {
return VOID_STATUS_INTERNAL;
}
uint8_t* copy = (uint8_t*)malloc((size_t)n);
if (copy == NULL) {
return VOID_STATUS_EXHAUSTED;
}
memcpy(copy, buf, (size_t)n);
out_state->data = copy;
out_state->size = (uint64_t)n;
out_state->release = free_c_bytes;
out_state->release_ctx = NULL;
return VOID_STATUS_OK;
}
static int32_t cabi_restore(void_module_handle* h,
void_bytes_v1 state,
void_error_detail_v1* out_err)
{
(void)h;
(void)state;
(void)out_err;
return VOID_STATUS_OK;
}
static uint32_t iface_get_version(void_module_handle* h)
{
(void)h;
return 1u;
}
static int32_t iface_accumulate(void_module_handle* h, int32_t delta)
{
if (h == NULL) {
return -1;
}
if (atomic_load(&h->quiescing) != 0 && delta != 0) {
return -1;
}
return atomic_fetch_add(&h->total, delta) + delta;
}
static const cabi_calc_v1 kCalcTable = {iface_get_version, iface_accumulate};
static int32_t cabi_query_interface(void_module_handle* h,
const void_interface_id_v1* iface_id,
uint32_t min_major,
uint32_t min_table_size,
void_interface_view_v1* out_view)
{
if (h == NULL || iface_id == NULL || out_view == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
if (memcmp(iface_id->bytes, kCalcIfaceId.bytes, 16) != 0) {
return VOID_STATUS_NOT_FOUND;
}
if (min_major != 1u || min_table_size > sizeof(cabi_calc_v1)) {
return VOID_STATUS_UNSUPPORTED;
}
out_view->struct_size = (uint32_t)sizeof(void_interface_view_v1);
out_view->major = 1u;
out_view->minor = 0u;
out_view->table_size = (uint32_t)sizeof(cabi_calc_v1);
out_view->function_table = &kCalcTable;
return VOID_STATUS_OK;
}
static void cabi_release_interface(void_module_handle* h,
const void_interface_id_v1* iface_id,
const void_interface_view_v1* view)
{
(void)h;
(void)iface_id;
(void)view;
}
static void* async_worker(void* arg)
{
struct void_operation_handle* op = (struct void_operation_handle*)arg;
int pinned = 0;
if (op->op_kind == 3u && op->owner->host.acquire_activity_pin != NULL) {
if (op->owner->host.acquire_activity_pin(
op->owner->host.host_ctx, op->owner->host.generation) ==
VOID_STATUS_OK) {
pinned = 1;
}
}
struct timespec ts = {.tv_sec = 0, .tv_nsec = 2000000};
for (int i = 0; i < 10; ++i) {
if (atomic_load(&op->cancelled) != 0) {
op->cb(op->cb_ctx, VOID_STATUS_CANCELLED, NULL);
if (pinned) {
op->owner->host.release_activity_pin(
op->owner->host.host_ctx, op->owner->host.generation);
}
return NULL;
}
nanosleep(&ts, NULL);
}
int32_t val = atomic_fetch_add(&op->owner->total, op->delta) + op->delta;
uint8_t buf[4];
memcpy(buf, &val, sizeof(val));
void_bytes_v1 res = {.data = buf, .size = sizeof(buf)};
op->cb(op->cb_ctx, VOID_STATUS_OK, &res);
if (pinned) {
op->owner->host.release_activity_pin(op->owner->host.host_ctx,
op->owner->host.generation);
}
return NULL;
}
static int32_t cabi_submit_async(void_module_handle* h,
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)
{
(void)out_err;
if (h == NULL || cb == NULL || out_op == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
*out_op = NULL;
if (opts != NULL && opts->stop_requested) {
return VOID_STATUS_CANCELLED;
}
int32_t delta = 0;
if (payload.data != NULL && payload.size >= 4) {
memcpy(&delta, payload.data, 4);
}
struct void_operation_handle* op =
(struct void_operation_handle*)calloc(1, sizeof(*op));
if (op == NULL) {
return VOID_STATUS_EXHAUSTED;
}
op->owner = h;
op->op_kind = op_kind;
op->delta = delta;
op->cb = cb;
op->cb_ctx = cb_ctx;
atomic_init(&op->cancelled, 0);
if (op_kind == 2u) {
int32_t val = atomic_fetch_add(&h->total, delta) + delta;
uint8_t buf[4];
memcpy(buf, &val, sizeof(val));
void_bytes_v1 res = {.data = buf, .size = sizeof(buf)};
*out_op = op;
cb(cb_ctx, VOID_STATUS_OK, &res);
return VOID_STATUS_OK;
}
pthread_mutex_lock(&h->ops_mu);
if (h->ops_count < 64) {
h->ops[h->ops_count++] = op;
}
pthread_mutex_unlock(&h->ops_mu);
op->worker_started = 1;
*out_op = op;
if (pthread_create(&op->worker, NULL, async_worker, op) != 0) {
op->worker_started = 0;
*out_op = NULL;
free(op);
return VOID_STATUS_INTERNAL;
}
return VOID_STATUS_OK;
}
static int32_t cabi_cancel_async(void_module_handle* h, void_operation_handle* op)
{
(void)h;
if (op == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
atomic_store(&op->cancelled, 1);
return VOID_STATUS_OK;
}
static void cabi_release_async(void_module_handle* h, void_operation_handle* op)
{
if (op == NULL) {
return;
}
if (op->worker_started) {
pthread_join(op->worker, NULL);
op->worker_started = 0;
}
if (h != NULL) {
pthread_mutex_lock(&h->ops_mu);
for (size_t i = 0; i < h->ops_count; ++i) {
if (h->ops[i] == op) {
h->ops[i] = h->ops[h->ops_count - 1];
--h->ops_count;
break;
}
}
pthread_mutex_unlock(&h->ops_mu);
}
free(op);
}
static int32_t cabi_request_stop(void_module_handle* h)
{
if (h == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
atomic_store(&h->quiescing, 1);
pthread_mutex_lock(&h->ops_mu);
for (size_t i = 0; i < h->ops_count; ++i) {
if (h->ops[i] != NULL) {
atomic_store(&h->ops[i]->cancelled, 1);
}
}
pthread_mutex_unlock(&h->ops_mu);
return VOID_STATUS_OK;
}
static int32_t cabi_deactivate(void_module_handle* h)
{
return cabi_request_stop(h);
}
static void cabi_destroy(void_module_handle* h)
{
if (h == NULL) {
return;
}
pthread_mutex_destroy(&h->ops_mu);
free(h);
}
int32_t void_module_query_v1(uint32_t host_struct_size,
void_module_api_v1* out_api)
{
if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) {
return VOID_STATUS_INVALID_ARGUMENT;
}
memset(out_api, 0, sizeof(*out_api));
out_api->struct_size = (uint32_t)sizeof(void_module_api_v1);
out_api->abi_major = VOID_CABI_MAJOR_V1;
out_api->abi_minor = VOID_CABI_MINOR_V1;
out_api->reserved = 0;
out_api->capabilities = VOID_CAP_STATELESS_RELOAD |
VOID_CAP_STATEFUL_CHECKPOINT | VOID_CAP_ASYNC_OPS |
VOID_CAP_SERVICE_INTERFACES;
out_api->get_info = cabi_get_info;
out_api->create = cabi_create;
out_api->activate = cabi_activate;
out_api->readiness = cabi_readiness;
out_api->quiesce = cabi_quiesce;
out_api->resume = cabi_resume;
out_api->checkpoint = cabi_checkpoint;
out_api->restore = cabi_restore;
out_api->query_interface = cabi_query_interface;
out_api->release_interface = cabi_release_interface;
out_api->submit_async = cabi_submit_async;
out_api->cancel_async = cabi_cancel_async;
out_api->release_async = cabi_release_async;
out_api->request_stop = cabi_request_stop;
out_api->deactivate = cabi_deactivate;
out_api->destroy = cabi_destroy;
return VOID_STATUS_OK;
}
+357
View File
@@ -0,0 +1,357 @@
#include <Void/Plugin/CAbi.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef struct cabi_calc_v1 {
uint32_t (*version)(void_module_handle* h);
int32_t (*accumulate)(void_module_handle* h, int32_t delta);
} cabi_calc_v1;
struct void_module_handle {
void_host_api_v1 host;
atomic_int total;
int ready;
};
static const void_interface_id_v1 kCalcIfaceId = {
{0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01}};
static void free_c_str(void* ctx, const char* msg)
{
(void)ctx;
free((void*)msg);
}
static void free_c_bytes(void* ctx, const uint8_t* data, uint64_t size)
{
(void)ctx;
(void)size;
free((void*)data);
}
static void set_err(void_error_detail_v1* out_err,
int32_t status,
const char* text)
{
if (out_err == NULL || out_err->struct_size < sizeof(void_error_detail_v1)) {
return;
}
out_err->status = status;
if (text != NULL) {
size_t n = strlen(text);
char* copy = (char*)malloc(n + 1);
if (copy != NULL) {
memcpy(copy, text, n + 1);
out_err->message = copy;
out_err->release = free_c_str;
out_err->release_ctx = NULL;
}
}
}
static int cfg_has(void_bytes_v1 cfg, const char* needle)
{
if (cfg.data == NULL || cfg.size == 0) {
return 0;
}
size_t nlen = strlen(needle);
if (cfg.size < nlen) {
return 0;
}
for (uint64_t i = 0; i + nlen <= cfg.size; ++i) {
if (memcmp(cfg.data + i, needle, nlen) == 0) {
return 1;
}
}
return 0;
}
static int32_t cabi_v2_get_info(void_module_info_v1* out_info)
{
if (out_info == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
memset(out_info, 0, sizeof(*out_info));
out_info->struct_size = (uint32_t)sizeof(void_module_info_v1);
out_info->module_id = "cabi.calc";
out_info->version = "2.0.0";
out_info->activation_policy = VOID_POLICY_RELOADABLE;
out_info->state_schema_version = 2;
return VOID_STATUS_OK;
}
static int32_t cabi_v2_create(const void_host_api_v1* host_api,
void_module_handle** out_handle)
{
if (out_handle == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
*out_handle = NULL;
if (host_api == NULL || host_api->struct_size < sizeof(void_host_api_v1)) {
return VOID_STATUS_INVALID_ARGUMENT;
}
struct void_module_handle* h =
(struct void_module_handle*)calloc(1, sizeof(*h));
if (h == NULL) {
return VOID_STATUS_EXHAUSTED;
}
h->host = *host_api;
atomic_init(&h->total, 0);
h->ready = 1;
*out_handle = h;
return VOID_STATUS_OK;
}
static int32_t cabi_v2_activate(void_module_handle* h,
void_bytes_v1 config,
void_error_detail_v1* out_err)
{
if (h == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
if (cfg_has(config, "fail_activate")) {
set_err(out_err, VOID_STATUS_INTERNAL, "V2 activation failed");
return VOID_STATUS_INTERNAL;
}
h->ready = cfg_has(config, "not_ready") ? 0 : 1;
return VOID_STATUS_OK;
}
static int32_t cabi_v2_readiness(void_module_handle* h,
uint32_t* out_ready,
void_error_detail_v1* out_err)
{
if (h == NULL || out_ready == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
*out_ready = h->ready ? 1u : 0u;
if (!h->ready) {
set_err(out_err, VOID_STATUS_NOT_READY, "V2 not ready");
}
return VOID_STATUS_OK;
}
static int32_t cabi_v2_quiesce(void_module_handle* h,
const void_op_options_v1* opts,
void_error_detail_v1* out_err)
{
(void)h;
(void)opts;
(void)out_err;
return VOID_STATUS_OK;
}
static int32_t cabi_v2_resume(void_module_handle* h,
void_error_detail_v1* out_err)
{
(void)h;
(void)out_err;
return VOID_STATUS_OK;
}
static int32_t cabi_v2_checkpoint(void_module_handle* h,
const void_op_options_v1* opts,
void_owned_bytes_v1* out_state,
void_error_detail_v1* out_err)
{
(void)opts;
(void)out_err;
if (h == NULL || out_state == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
char buf[64];
int val = atomic_load(&h->total);
int len = 0;
if (val == 0) {
memcpy(buf, "v2:0", 4);
len = 4;
} else {
/* Decimal conversion without stdio overhead. */
char rev[32];
int rlen = 0;
int neg = val < 0;
unsigned u = neg ? (unsigned)(-val) : (unsigned)val;
while (u > 0) {
rev[rlen++] = (char)('0' + (u % 10u));
u /= 10u;
}
buf[len++] = 'v';
buf[len++] = '2';
buf[len++] = ':';
if (neg) {
buf[len++] = '-';
}
while (rlen > 0) {
buf[len++] = rev[--rlen];
}
}
uint8_t* copy = (uint8_t*)malloc((size_t)len);
if (copy == NULL) {
return VOID_STATUS_EXHAUSTED;
}
memcpy(copy, buf, (size_t)len);
out_state->data = copy;
out_state->size = (uint64_t)len;
out_state->release = free_c_bytes;
out_state->release_ctx = NULL;
return VOID_STATUS_OK;
}
static int32_t cabi_v2_restore(void_module_handle* h,
void_bytes_v1 state,
void_error_detail_v1* out_err)
{
if (h == NULL || state.data == NULL || state.size < 4) {
set_err(out_err, VOID_STATUS_STATE_REJECTED, "V2 invalid checkpoint");
return VOID_STATUS_STATE_REJECTED;
}
if (memcmp(state.data, "v1:", 3) != 0 &&
memcmp(state.data, "v2:", 3) != 0) {
set_err(out_err, VOID_STATUS_STATE_REJECTED, "V2 unknown checkpoint header");
return VOID_STATUS_STATE_REJECTED;
}
char buf[64];
size_t n = (size_t)(state.size - 3);
if (n >= sizeof(buf)) {
return VOID_STATUS_STATE_REJECTED;
}
memcpy(buf, state.data + 3, n);
buf[n] = '\0';
int val = atoi(buf);
atomic_store(&h->total, val);
return VOID_STATUS_OK;
}
static uint32_t iface_v2_version(void_module_handle* h)
{
(void)h;
return 2u;
}
static int32_t iface_v2_accumulate(void_module_handle* h, int32_t delta)
{
if (h == NULL) {
return -1;
}
return atomic_fetch_add(&h->total, delta) + delta;
}
static const cabi_calc_v1 kCalcV2 = {iface_v2_version, iface_v2_accumulate};
static int32_t cabi_v2_query_interface(void_module_handle* h,
const void_interface_id_v1* iface_id,
uint32_t min_major,
uint32_t min_table_size,
void_interface_view_v1* out_view)
{
if (h == NULL || iface_id == NULL || out_view == NULL) {
return VOID_STATUS_INVALID_ARGUMENT;
}
if (memcmp(iface_id->bytes, kCalcIfaceId.bytes, 16) != 0) {
return VOID_STATUS_NOT_FOUND;
}
if (min_major != 1u || min_table_size > sizeof(cabi_calc_v1)) {
return VOID_STATUS_UNSUPPORTED;
}
out_view->struct_size = (uint32_t)sizeof(void_interface_view_v1);
out_view->major = 1u;
out_view->minor = 1u;
out_view->table_size = (uint32_t)sizeof(cabi_calc_v1);
out_view->function_table = &kCalcV2;
return VOID_STATUS_OK;
}
static void cabi_v2_release_interface(void_module_handle* h,
const void_interface_id_v1* iface_id,
const void_interface_view_v1* view)
{
(void)h;
(void)iface_id;
(void)view;
}
static int32_t cabi_v2_submit_async(void_module_handle* h,
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)
{
(void)h;
(void)op_kind;
(void)payload;
(void)opts;
(void)cb;
(void)cb_ctx;
(void)out_op;
(void)out_err;
return VOID_STATUS_UNSUPPORTED;
}
static int32_t cabi_v2_cancel_async(void_module_handle* h,
void_operation_handle* op)
{
(void)h;
(void)op;
return VOID_STATUS_UNSUPPORTED;
}
static void cabi_v2_release_async(void_module_handle* h,
void_operation_handle* op)
{
(void)h;
(void)op;
}
static int32_t cabi_v2_request_stop(void_module_handle* h)
{
(void)h;
return VOID_STATUS_OK;
}
static int32_t cabi_v2_deactivate(void_module_handle* h)
{
(void)h;
return VOID_STATUS_OK;
}
static void cabi_v2_destroy(void_module_handle* h) { free(h); }
int32_t void_module_query_v1(uint32_t host_struct_size,
void_module_api_v1* out_api)
{
if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) {
return VOID_STATUS_INVALID_ARGUMENT;
}
memset(out_api, 0, sizeof(*out_api));
out_api->struct_size = (uint32_t)sizeof(void_module_api_v1);
out_api->abi_major = VOID_CABI_MAJOR_V1;
out_api->abi_minor = VOID_CABI_MINOR_V1;
out_api->reserved = 0;
out_api->capabilities = VOID_CAP_STATELESS_RELOAD |
VOID_CAP_STATEFUL_CHECKPOINT |
VOID_CAP_SERVICE_INTERFACES;
out_api->get_info = cabi_v2_get_info;
out_api->create = cabi_v2_create;
out_api->activate = cabi_v2_activate;
out_api->readiness = cabi_v2_readiness;
out_api->quiesce = cabi_v2_quiesce;
out_api->resume = cabi_v2_resume;
out_api->checkpoint = cabi_v2_checkpoint;
out_api->restore = cabi_v2_restore;
out_api->query_interface = cabi_v2_query_interface;
out_api->release_interface = cabi_v2_release_interface;
out_api->submit_async = cabi_v2_submit_async;
out_api->cancel_async = cabi_v2_cancel_async;
out_api->release_async = cabi_v2_release_async;
out_api->request_stop = cabi_v2_request_stop;
out_api->deactivate = cabi_v2_deactivate;
out_api->destroy = cabi_v2_destroy;
return VOID_STATUS_OK;
}
+101 -14
View File
@@ -3,8 +3,10 @@
#include <Void/Testing/Assert.hpp> #include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp> #include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array> #include <array>
#include <atomic> #include <atomic>
#include <cstring>
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <memory> #include <memory>
@@ -13,23 +15,95 @@
#include <string_view> #include <string_view>
#include <system_error> #include <system_error>
#include <thread> #include <thread>
#include <vector>
#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
namespace namespace
{ {
enum class FixtureEntryType { Regular, Directory, Symlink };
struct ArchiveEntry { struct ArchiveEntry {
std::string_view path; std::string_view path;
std::string_view contents; std::string_view contents;
unsigned int type{AE_IFREG}; FixtureEntryType type{FixtureEntryType::Regular};
std::string_view link; std::string_view link;
}; };
void write_archive(const std::filesystem::path &path, void write_octal(std::span<char> dst, std::uint64_t val)
std::span<const ArchiveEntry>
entries)
{ {
dst.back() = '\0';
std::size_t pos = dst.size() - 1;
while (pos > 0) {
--pos;
dst[pos] = static_cast<char>('0' + (val & 7ULL));
val >>= 3ULL;
}
}
void write_raw_tar(const std::filesystem::path& path,
std::span<const ArchiveEntry> entries)
{
std::ofstream out{path, std::ios::binary | std::ios::trunc};
Void::Testing::require(out.is_open());
for (const auto& spec : entries) {
std::array<char, 512> hdr{};
std::memcpy(hdr.data(), spec.path.data(),
std::min<std::size_t>(spec.path.size(), 100));
const std::uint32_t perm =
spec.type == FixtureEntryType::Directory ? 0755U : 0644U;
write_octal(std::span{hdr}.subspan(100, 8), perm);
write_octal(std::span{hdr}.subspan(108, 8), 0);
write_octal(std::span{hdr}.subspan(116, 8), 0);
const std::uint64_t sz =
spec.type == FixtureEntryType::Regular ? spec.contents.size()
: 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), sz);
write_octal(std::span{hdr}.subspan(136, 12), 0);
std::fill(hdr.begin() + 148, hdr.begin() + 156, ' ');
hdr[156] = spec.type == FixtureEntryType::Directory
? '5'
: (spec.type == FixtureEntryType::Symlink ? '2' : '0');
if (!spec.link.empty()) {
std::memcpy(hdr.data() + 157, spec.link.data(),
std::min<std::size_t>(spec.link.size(), 100));
}
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = '0';
hdr[264] = '0';
std::uint32_t sum = 0;
for (const char ch : hdr) {
sum += static_cast<unsigned char>(ch);
}
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = ' ';
out.write(hdr.data(), hdr.size());
if (spec.type == FixtureEntryType::Regular && !spec.contents.empty()) {
out.write(spec.contents.data(),
static_cast<std::streamsize>(spec.contents.size()));
const std::size_t rem = spec.contents.size() % 512U;
if (rem != 0) {
std::array<char, 512> pad{};
out.write(pad.data(),
static_cast<std::streamsize>(512U - rem));
}
}
}
std::array<char, 1024> eof{};
out.write(eof.data(), eof.size());
out.close();
Void::Testing::require(out.good());
}
void write_archive(const std::filesystem::path& path,
std::span<const ArchiveEntry> entries)
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using Writer = std::unique_ptr<archive, decltype(&archive_write_free)>; using Writer = std::unique_ptr<archive, decltype(&archive_write_free)>;
using Entry = using Entry =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>; std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
@@ -47,14 +121,21 @@ namespace
writer.get(), path.c_str()) == ARCHIVE_OK); writer.get(), path.c_str()) == ARCHIVE_OK);
#endif #endif
for (const auto &specification : entries) { for (const auto& specification : entries) {
Entry entry{archive_entry_new(), &archive_entry_free}; Entry entry{archive_entry_new(), &archive_entry_free};
const std::string entryPath{specification.path}; const std::string entryPath{specification.path};
archive_entry_set_pathname(entry.get(), entryPath.c_str()); archive_entry_set_pathname(entry.get(), entryPath.c_str());
archive_entry_set_filetype(entry.get(), specification.type); const unsigned int ae_type =
specification.type == FixtureEntryType::Directory
? AE_IFDIR
: (specification.type == FixtureEntryType::Symlink
? AE_IFLNK
: AE_IFREG);
archive_entry_set_filetype(entry.get(), ae_type);
archive_entry_set_perm( archive_entry_set_perm(
entry.get(), specification.type == AE_IFDIR ? 0755 : 0644); entry.get(),
if (specification.type == AE_IFREG) { specification.type == FixtureEntryType::Directory ? 0755 : 0644);
if (specification.type == FixtureEntryType::Regular) {
archive_entry_set_size( archive_entry_set_size(
entry.get(), entry.get(),
static_cast<la_int64_t>(specification.contents.size())); static_cast<la_int64_t>(specification.contents.size()));
@@ -78,18 +159,22 @@ namespace
ARCHIVE_OK); ARCHIVE_OK);
} }
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK); Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
#else
write_raw_tar(path, entries);
#endif
} }
void write_archive(const std::filesystem::path &path, void write_archive(const std::filesystem::path& path,
std::string_view entryPath, std::string_view contents, std::string_view entryPath, std::string_view contents,
unsigned int type = AE_IFREG, std::string_view link = {}) FixtureEntryType type = FixtureEntryType::Regular,
std::string_view link = {})
{ {
const std::array entries{ArchiveEntry{entryPath, contents, type, link}}; const std::array entries{ArchiveEntry{entryPath, contents, type, link}};
write_archive(path, entries); write_archive(path, entries);
} }
[[nodiscard]] bool [[nodiscard]] bool
extraction_file_visible(const std::filesystem::path &destination) extraction_file_visible(const std::filesystem::path& destination)
{ {
std::error_code error; std::error_code error;
if (std::filesystem::exists(destination / "anchor", error)) { if (std::filesystem::exists(destination / "anchor", error)) {
@@ -129,8 +214,9 @@ Void::Testing::Test archive_accepts_explicit_directory_entries()
Void::FileSystem::TempDir temporary{"void_archive_"}; Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "directory.tar.zst"; const auto source = temporary / "directory.tar.zst";
const auto destination = temporary / "output"; const auto destination = temporary / "output";
const std::array entries{ArchiveEntry{"bin/", {}, AE_IFDIR}, const std::array entries{
ArchiveEntry{"bin/tool", "payload"}}; ArchiveEntry{"bin/", {}, FixtureEntryType::Directory},
ArchiveEntry{"bin/tool", "payload"}};
write_archive(source, entries); write_archive(source, entries);
auto extracted = Void::Archive::extract(source, destination); auto extracted = Void::Archive::extract(source, destination);
@@ -154,7 +240,8 @@ Void::Testing::Test archive_rejects_traversal_and_links()
Void::Testing::expect( Void::Testing::expect(
!std::filesystem::exists(temporary.path() / "escape")); !std::filesystem::exists(temporary.path() / "escape"));
const auto symlink = temporary / "symlink.tar.zst"; const auto symlink = temporary / "symlink.tar.zst";
write_archive(symlink, "link", {}, AE_IFLNK, "/tmp/escape"); write_archive(symlink, "link", {}, FixtureEntryType::Symlink,
"/tmp/escape");
Void::Testing::expect( Void::Testing::expect(
!Void::Archive::extract(symlink, temporary / "out2").has_value()); !Void::Archive::extract(symlink, temporary / "out2").has_value());
const auto trailingFile = temporary / "trailing-file.tar.zst"; const auto trailingFile = temporary / "trailing-file.tar.zst";
+227 -16
View File
@@ -3,12 +3,16 @@
#include <Void/Testing/Assert.hpp> #include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp> #include <Void/Testing/Test.hpp>
#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
#include <algorithm>
#include <array> #include <array>
#include <chrono> #include <chrono>
#include <cstddef> #include <cstddef>
#include <cstring>
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <memory> #include <memory>
@@ -16,6 +20,8 @@
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <sys/stat.h> #include <sys/stat.h>
#include <thread>
#include <tuple>
#include <vector> #include <vector>
namespace namespace
@@ -39,6 +45,72 @@ namespace
std::istreambuf_iterator<char>{}}; std::istreambuf_iterator<char>{}};
} }
void write_octal(std::span<std::byte> dst, std::uint64_t val)
{
dst.back() = std::byte{0};
std::size_t pos = dst.size() - 1;
while (pos > 0) {
--pos;
dst[pos] = static_cast<std::byte>('0' + (val & 7ULL));
val >>= 3ULL;
}
}
std::vector<std::byte> make_raw_tar_ustar(
std::span<const std::tuple<std::string_view, std::string_view, char,
std::string_view>>
entries)
{
std::vector<std::byte> out;
for (const auto& [path, content, typeflag, link] : entries) {
std::array<std::byte, 512> hdr{};
std::memcpy(hdr.data(), path.data(),
std::min<std::size_t>(path.size(), 100));
write_octal(std::span{hdr}.subspan(100, 8),
typeflag == '5' ? 0755ULL : 0644ULL);
write_octal(std::span{hdr}.subspan(108, 8), 0);
write_octal(std::span{hdr}.subspan(116, 8), 0);
const std::uint64_t sz = (typeflag == '0') ? content.size() : 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), sz);
write_octal(std::span{hdr}.subspan(136, 12), 0);
std::fill(hdr.begin() + 148, hdr.begin() + 156, std::byte{' '});
hdr[156] = static_cast<std::byte>(typeflag);
if (!link.empty()) {
std::memcpy(hdr.data() + 157, link.data(),
std::min<std::size_t>(link.size(), 100));
}
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = std::byte{'0'};
hdr[264] = std::byte{'0'};
std::uint32_t sum = 0;
for (const std::byte b : hdr) {
sum += static_cast<std::uint8_t>(b);
}
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = std::byte{' '};
out.insert(out.end(), hdr.begin(), hdr.end());
if (typeflag == '0' && !content.empty()) {
const auto cb =
std::as_bytes(std::span{content.data(), content.size()});
out.insert(out.end(), cb.begin(), cb.end());
const std::size_t rem = content.size() % 512U;
if (rem != 0) {
out.resize(out.size() + (512U - rem), std::byte{0});
}
}
}
out.resize(out.size() + 1024U, std::byte{0});
return out;
}
ArchiveCompression default_test_compression() noexcept
{
return has_libarchive_backend() ? ArchiveCompression::Zstd
: ArchiveCompression::None;
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
std::vector<std::byte> make_raw_tar( std::vector<std::byte> make_raw_tar(
std::span<const std::tuple<std::string_view, std::string_view, std::span<const std::tuple<std::string_view, std::string_view,
unsigned int, std::string_view>> unsigned int, std::string_view>>
@@ -95,6 +167,7 @@ namespace
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK); Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
return out; return out;
} }
#endif
} // namespace } // namespace
Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing() Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
@@ -116,7 +189,7 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
VectorByteSink sink_a; VectorByteSink sink_a;
VectorByteSink sink_b; VectorByteSink sink_b;
CreationOptions copts{.compression = ArchiveCompression::Zstd, CreationOptions copts{.compression = default_test_compression(),
.reproducible = true}; .reproducible = true};
Void::Testing::require(create_archive(sink_a, order_a, copts).has_value()); Void::Testing::require(create_archive(sink_a, order_a, copts).has_value());
Void::Testing::require(create_archive(sink_b, order_b, copts).has_value()); Void::Testing::require(create_archive(sink_b, order_b, copts).has_value());
@@ -173,8 +246,26 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
Void::Testing::expect(zero_entries.validate().has_value()); Void::Testing::expect(zero_entries.validate().has_value());
} }
// 4. File-as-parent conflict rejected cleanly (both orderings). // 4. File-as-parent conflict rejected cleanly (pure USTAR works with and
// without LibArchive; additionally exercise zstd when LibArchive exists).
{ {
const std::array<
std::tuple<std::string_view, std::string_view, char,
std::string_view>,
2>
conflict_ustar{{
{"foo", "file-bytes", '0', ""},
{"foo/child", "nested", '0', ""},
}};
const auto raw_ustar = make_raw_tar_ustar(conflict_ustar);
SpanByteSource src{raw_ustar};
auto listed = list_entries(src, {}, false);
Void::Testing::require(!listed.has_value());
Void::Testing::expect_eq(
listed.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry));
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
const std::array< const std::array<
std::tuple<std::string_view, std::string_view, unsigned int, std::tuple<std::string_view, std::string_view, unsigned int,
std::string_view>, std::string_view>,
@@ -184,26 +275,27 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
{"foo/child", "nested", AE_IFREG, ""}, {"foo/child", "nested", AE_IFREG, ""},
}}; }};
const auto raw = make_raw_tar(conflict_entries); const auto raw = make_raw_tar(conflict_entries);
SpanByteSource src{raw}; SpanByteSource src_la{raw};
auto listed = list_entries(src, {}, false); auto listed_la = list_entries(src_la, {}, false);
Void::Testing::require(!listed.has_value()); Void::Testing::require(!listed_la.has_value());
Void::Testing::expect_eq( Void::Testing::expect_eq(
listed.error().code().value, listed_la.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry)); static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry));
#endif
} }
// 5. Normal vs forensic listing + sanitized diagnostics. // 5. Normal vs forensic listing + sanitized diagnostics.
{ {
const std::array< const std::array<
std::tuple<std::string_view, std::string_view, unsigned int, std::tuple<std::string_view, std::string_view, char,
std::string_view>, std::string_view>,
3> 3>
mixed{{ mixed_ustar{{
{"safe.txt", "ok", AE_IFREG, ""}, {"safe.txt", "ok", '0', ""},
{"bad\nlink", "", AE_IFLNK, "/etc/passwd"}, {"bad\nlink", "", '2', "/etc/passwd"},
{"../escape", "nope", AE_IFREG, ""}, {"../escape", "nope", '0', ""},
}}; }};
const auto raw = make_raw_tar(mixed); const auto raw = make_raw_tar_ustar(mixed_ustar);
SpanByteSource src1{raw}; SpanByteSource src1{raw};
Void::Testing::expect(!list_entries(src1, {}, false).has_value()); Void::Testing::expect(!list_entries(src1, {}, false).has_value());
@@ -226,10 +318,123 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
std::string{"a\\nb\\rc"}); std::string{"a\\nb\\rc"});
} }
Void::Testing::Test archive_create_formats_builtin_ustar_pax_and_gzip()
{
Void::FileSystem::TempDir tmp{"void_archive_formats_"};
// Built-in pure-C++ USTAR/PAX creation works regardless of LibArchive,
// handles long PAX paths (>120 bytes), custom canonical metadata, and
// produces byte-identical output across runs and entry permutations.
const std::string long_path =
"very/deep/nested/package/hierarchy/with/many/subdirectories/"
"extending/well/past/one/hundred/bytes/component/artifact.txt";
const std::array<CreateEntry, 3> entries_a{{
CreateEntry{.path = long_path,
.type = EntryType::RegularFile,
.executable = false,
.content = to_bytes("pax-long-path-content")},
CreateEntry{.path = "bin/tool",
.type = EntryType::RegularFile,
.executable = false,
.content = to_bytes("tool-bytes"),
.mode = 0755U},
CreateEntry{.path = "bin/", .type = EntryType::Directory},
}};
const std::array<CreateEntry, 3> entries_b{
entries_a[2], entries_a[0], entries_a[1]};
CreationOptions builtin_opts{
.compression = ArchiveCompression::None,
.reproducible = true,
.canonical_mtime = 1700000000,
.canonical_uid = 1000,
.canonical_gid = 1000,
.prefer_builtin_tar = true,
};
VectorByteSink raw1;
VectorByteSink raw2;
Void::Testing::require(create(raw1, entries_a, builtin_opts).has_value());
Void::Testing::require(create(raw2, entries_b, builtin_opts).has_value());
Void::Testing::expect_eq(raw1.bytes(), raw2.bytes());
const auto tar_file = tmp / "builtin.tar";
Void::Testing::require(create(tar_file, entries_a, builtin_opts).has_value());
auto extracted = extract(tar_file, tmp / "unpacked_tar");
Void::Testing::require(extracted.has_value());
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_tar" / long_path),
std::string{"pax-long-path-content"});
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_tar/bin/tool"),
std::string{"tool-bytes"});
struct stat st_tool{};
Void::Testing::require(::stat((tmp / "unpacked_tar/bin/tool").c_str(),
&st_tool) == 0);
Void::Testing::expect_eq(st_tool.st_mode & 0777, mode_t{0755});
// Staged extraction over built-in tar also succeeds (exercising
// LibArchive interop when LibArchive is linked, or built-in Reader when
// LibArchive is absent).
auto staged_tar = extract_staged(tar_file, tmp / "staged_tar");
Void::Testing::require(staged_tar.has_value());
auto pub_tar = staged_tar->publish("v1");
Void::Testing::require(pub_tar.has_value());
Void::Testing::expect_eq(
read_file_str(tmp / "staged_tar/v1" / long_path),
std::string{"pax-long-path-content"});
if (has_libarchive_backend()) {
CreationOptions gzip_opts{
.compression = ArchiveCompression::Gzip,
.reproducible = true,
.canonical_mtime = 1700000000,
};
VectorByteSink gz1;
VectorByteSink gz2;
Void::Testing::require(create(gz1, entries_a, gzip_opts).has_value());
std::this_thread::sleep_for(std::chrono::milliseconds{15});
Void::Testing::require(create(gz2, entries_b, gzip_opts).has_value());
Void::Testing::expect_eq(gz1.bytes(), gz2.bytes());
const auto gz_path = tmp / "bundle.tar.gz";
Void::Testing::require(
create(gz_path, entries_a, gzip_opts).has_value());
auto gz_ext = extract(gz_path, tmp / "unpacked_gz");
Void::Testing::require(gz_ext.has_value());
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_gz" / long_path),
std::string{"pax-long-path-content"});
auto gz_staged = extract_staged(gz_path, tmp / "staged_gz");
Void::Testing::require(gz_staged.has_value());
Void::Testing::require(gz_staged->publish("v1").has_value());
Void::Testing::expect_eq(
read_file_str(tmp / "staged_gz/v1/bin/tool"),
std::string{"tool-bytes"});
} else {
VectorByteSink unused;
auto zst_err =
create(unused, entries_a,
CreationOptions{.compression = ArchiveCompression::Zstd});
Void::Testing::require(!zst_err.has_value());
Void::Testing::expect_eq(
zst_err.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsupported_format));
auto gz_err =
create(unused, entries_a,
CreationOptions{.compression = ArchiveCompression::Gzip});
Void::Testing::require(!gz_err.has_value());
Void::Testing::expect_eq(
gz_err.error().code().value,
static_cast<std::int32_t>(ArchiveErrorCode::unsupported_format));
}
}
Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup() Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup()
{ {
Void::FileSystem::TempDir tmp{"void_archive_staged_"}; Void::FileSystem::TempDir tmp{"void_archive_staged_"};
const auto archive_path = tmp / "pkg.tar.zst"; const auto archive_path =
tmp / (has_libarchive_backend() ? "pkg.tar.zst" : "pkg.tar");
const auto parent_dir = tmp / "versions"; const auto parent_dir = tmp / "versions";
std::filesystem::create_directories(parent_dir); std::filesystem::create_directories(parent_dir);
@@ -243,7 +448,9 @@ Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup
.executable = false, .executable = false,
.content = to_bytes("key=val")}, .content = to_bytes("key=val")},
}}; }};
Void::Testing::require(create_archive(archive_path, entries).has_value()); const CreationOptions create_opts{.compression = default_test_compression()};
Void::Testing::require(
create_archive(archive_path, entries, create_opts).has_value());
// 1. Staged extraction + atomic no-replace publication + safe modes. // 1. Staged extraction + atomic no-replace publication + safe modes.
std::size_t progress_calls = 0; std::size_t progress_calls = 0;
@@ -344,7 +551,8 @@ Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes()
{ {
#ifdef VOID_ARCHIVE_WORKER_PATH #ifdef VOID_ARCHIVE_WORKER_PATH
Void::FileSystem::TempDir tmp{"void_archive_iso_"}; Void::FileSystem::TempDir tmp{"void_archive_iso_"};
const auto archive_path = tmp / "untrusted.tar.zst"; const auto archive_path =
tmp / (has_libarchive_backend() ? "untrusted.tar.zst" : "untrusted.tar");
const auto parent_dir = tmp / "out"; const auto parent_dir = tmp / "out";
std::filesystem::create_directories(parent_dir); std::filesystem::create_directories(parent_dir);
@@ -358,7 +566,10 @@ Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes()
.executable = false, .executable = false,
.content = to_bytes("verified-by-parent")}, .content = to_bytes("verified-by-parent")},
}}; }};
Void::Testing::require(create_archive(archive_path, entries).has_value()); Void::Testing::require(
create_archive(archive_path, entries,
CreationOptions{.compression = default_test_compression()})
.has_value());
IsolationOptions iso{}; IsolationOptions iso{};
iso.worker_executable = VOID_ARCHIVE_WORKER_PATH; iso.worker_executable = VOID_ARCHIVE_WORKER_PATH;
@@ -187,3 +187,89 @@ Void::Testing::Test argparse_help_contains_names()
Void::Testing::expect(h.find("--output") != std::string::npos); Void::Testing::expect(h.find("--output") != std::string::npos);
Void::Testing::expect(h.find("A description.") != std::string::npos); Void::Testing::expect(h.find("A description.") != std::string::npos);
} }
Void::Testing::Test argparse_subcommands_option_many_and_distinct_outcomes()
{
bool verbose = false;
std::vector<std::string> targets;
std::vector<std::string> profiles;
std::string compdb_mode;
bool build_selected = false;
bool use_selected = false;
Parser root{"vbs", "Void Build System"};
root.flag("--verbose", "-v", "verbose output", verbose);
auto& build_cmd =
root.subcommand("build", "Build project", [&] { build_selected = true; });
build_cmd.option_many("--target", "-t", "targets", targets);
build_cmd.option_many("--profile", "-p", "profiles", profiles);
auto& compdb_cmd = root.subcommand("compdb", "Compile database commands");
auto& use_cmd =
compdb_cmd.subcommand("use", "Select compdb", [&] { use_selected = true; });
use_cmd.positional("mode", "compdb mode", compdb_mode);
// 1. Subcommand + repeatable option_many
{
const Args a{{"vbs", "-v", "build", "--target", "app", "--target=lib",
"-p", "debug", "--profile", "release"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::require(res.ok());
Void::Testing::expect(verbose);
Void::Testing::expect(build_selected);
Void::Testing::expect(!use_selected);
Void::Testing::expect_eq(res.matched_command_path.size(), std::size_t{1});
Void::Testing::expect_eq(res.matched_command_path[0],
std::string{"build"});
Void::Testing::expect_eq(targets.size(), std::size_t{2});
Void::Testing::expect_eq(targets[0], std::string{"app"});
Void::Testing::expect_eq(targets[1], std::string{"lib"});
Void::Testing::expect_eq(profiles.size(), std::size_t{2});
Void::Testing::expect_eq(profiles[0], std::string{"debug"});
Void::Testing::expect_eq(profiles[1], std::string{"release"});
}
// 2. Nested subcommands ("vbs compdb use active")
{
build_selected = false;
use_selected = false;
const Args a{{"vbs", "compdb", "use", "active"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::require(res.ok());
Void::Testing::expect(!build_selected);
Void::Testing::expect(use_selected);
Void::Testing::expect_eq(res.matched_command_path.size(), std::size_t{2});
Void::Testing::expect_eq(res.matched_command_path[0],
std::string{"compdb"});
Void::Testing::expect_eq(res.matched_command_path[1], std::string{"use"});
Void::Testing::expect_eq(compdb_mode, std::string{"active"});
}
// 3. Help is ParseOutcome::Help (distinct from ParseOutcome::Error)
{
const Args a{{"vbs", "--help"}};
const auto res = root.parse_detailed(a.argc, a.argv);
Void::Testing::expect(res.is_help());
Void::Testing::expect(!res.is_error());
Void::Testing::expect(res.message.find("Commands:") != std::string::npos);
const Args sub_help{{"vbs", "build", "--help"}};
const auto sres = root.parse_detailed(sub_help.argc, sub_help.argv);
Void::Testing::expect(sres.is_help());
Void::Testing::expect(sres.message.find("--target") != std::string::npos);
}
// 4. Missing or unknown subcommand is ParseOutcome::Error without running callbacks
{
build_selected = false;
const Args missing_sub{{"vbs"}};
const auto mres = root.parse_detailed(missing_sub.argc, missing_sub.argv);
Void::Testing::expect(mres.is_error());
const Args bad_sub{{"vbs", "unknowncmd"}};
const auto bres = root.parse_detailed(bad_sub.argc, bad_sub.argv);
Void::Testing::expect(bres.is_error());
Void::Testing::expect(!build_selected);
}
}
@@ -0,0 +1,256 @@
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Configuration/Schema.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <cstdint>
#include <string>
#include <vector>
namespace
{
namespace C = Void::Configuration;
struct StrictServerConfig {
[[= C::Required{}]] std::string host{};
[[= C::IntRange{1, 65535}]] int port{8080};
[[= C::Secret{}]] std::string api_token{};
[[= C::RestartRequired{}]] std::string bind_interface{"0.0.0.0"};
[[= C::Deprecated{"use tls_min_version"}]] bool legacy_tls{false};
std::vector<int> shard_ids{};
std::optional<std::string> note{};
};
} // namespace
// @tag reflection
Void::Testing::Test config_schema_precedence_provenance_and_redaction()
{
C::SourceSet ss;
// Passed out of order on purpose: CLI must win over Env, which wins over
// File, which wins over Defaults.
ss.add_cli_args("cli", {"prog", "--host=cli.internal", "--port", "9090"});
ss.add_env_map("env",
{{"host", "env.internal"},
{"port", "7070"},
{"api_token", "super-secret-value-123"}});
ss.add_json_text(
"file.json",
R"({"host":"json.internal","port":6060,"shard_ids":[10,20]})");
ss.add_defaults_map("defaults",
{{"host", "def.internal"}, {"port", "8080"}});
auto schema = C::Schema<StrictServerConfig>::from_reflection();
auto merged = C::load_sources(ss, schema.limits(), schema.secret_keys());
Void::Testing::require(merged.has_value());
auto res = C::validate<StrictServerConfig>(*merged, schema);
Void::Testing::require(res.has_value());
Void::Testing::expect_eq(res->value.host, std::string{"cli.internal"});
Void::Testing::expect_eq(res->value.port, 9090);
Void::Testing::expect_eq(res->value.api_token,
std::string{"super-secret-value-123"});
Void::Testing::expect_eq(res->value.shard_ids.size(), std::size_t{2});
Void::Testing::expect_eq(res->value.shard_ids[0], 10);
Void::Testing::expect_eq(res->value.shard_ids[1], 20);
// Provenance tracks winning origin and shadowed origins with redaction flag.
const auto* host_prov = res->provenance->find("host");
Void::Testing::require(host_prov != nullptr);
Void::Testing::expect_eq(host_prov->winner.source, std::string{"cli"});
Void::Testing::expect_eq(host_prov->shadowed.size(), std::size_t{3});
const auto* tok_prov = res->provenance->find("api_token");
Void::Testing::require(tok_prov != nullptr);
Void::Testing::expect(tok_prov->redacted);
}
// @tag reflection
Void::Testing::Test config_schema_secret_redaction_and_bounds()
{
auto schema = C::Schema<StrictServerConfig>::from_reflection();
// Bad secret value (overflow / out-of-range) must redact secret value.
{
C::SourceSet ss;
ss.add_defaults_map("d", {{"host", "h"}});
// Force a scalar limit violation with secret key.
C::ConfigLimits tiny;
tiny.max_scalar_bytes = 8;
C::SourceSet big_sec;
big_sec.add_defaults_map(
"d", {{"host", "h"}, {"api_token", "VERY_SECRET_XYZ_TOKEN"}});
auto m = C::load_sources(big_sec, tiny, schema.secret_keys());
Void::Testing::expect(!m.has_value());
Void::Testing::expect(m.error().message().find("VERY_SECRET_XYZ") ==
std::string::npos);
Void::Testing::expect(m.error().message().find("[REDACTED]") !=
std::string::npos);
}
// Out-of-range port (0 or 70000) fails cleanly with range_error.
{
C::SourceSet ss;
ss.add_defaults_map("d", {{"host", "h"}, {"port", "70000"}});
auto m = C::load_sources(ss, schema.limits(), schema.secret_keys());
Void::Testing::require(m.has_value());
auto v = C::validate<StrictServerConfig>(*m, schema);
Void::Testing::expect(!v.has_value());
Void::Testing::expect_eq(
v.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::range_error));
}
// Exceeding max_source_bytes / max_nesting_depth rejected.
{
Void::FileSystem::TempDir tmp{"void_cfg_limits"};
const auto file = tmp.path() / "big.json";
std::string junk(256, 'a');
Void::Testing::require(
Void::FileSystem::write_file(file, "{\"host\":\"" + junk + "\"}")
.has_value());
C::ConfigLimits small_src;
small_src.max_source_bytes = 64;
C::SourceSet ss;
ss.add_json_file("f", file);
auto m = C::load_sources(ss, small_src);
Void::Testing::expect(!m.has_value());
Void::Testing::expect_eq(
m.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::limit_exceeded));
}
{
std::string nested;
for (int i = 0; i < 40; ++i) nested += "{\"a\":";
nested += "1";
for (int i = 0; i < 40; ++i) nested += "}";
C::SourceSet ss;
ss.add_json_text("deep", std::move(nested));
auto m = C::load_sources(ss);
Void::Testing::expect(!m.has_value());
Void::Testing::expect_eq(
m.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::limit_exceeded));
}
}
// @tag reflection
Void::Testing::Test config_schema_collisions_gaps_null_empty_and_constraints()
{
auto schema = C::Schema<StrictServerConfig>::from_reflection();
schema.add_constraint("no_root_interface_in_prod",
[](const StrictServerConfig& cfg)
-> Void::Result::Result<void> {
if (cfg.host == "prod" && cfg.port < 1024) {
return Void::Result::fail(
C::make_config_error(
C::ConfigErrorCode::constraint_failed,
"prod requires non-privileged port"));
}
return {};
});
// Dotted key vs nested path collision rejected.
{
C::SourceSet ss;
ss.add_json_text("coll",
R"({"a":{"b":"nested"},"a.b":"literal-dot"})");
auto m = C::load_sources(ss);
Void::Testing::expect(!m.has_value());
Void::Testing::expect_eq(
m.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::key_collision));
}
// Unknown key rejected by default.
{
C::SourceSet ss;
ss.add_defaults_map("d", {{"host", "h"}, {"typo_key", "1"}});
auto m = C::load_sources(ss);
Void::Testing::require(m.has_value());
auto v = C::validate<StrictServerConfig>(*m, schema);
Void::Testing::expect(!v.has_value());
Void::Testing::expect_eq(
v.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::unknown_key));
}
// Vector index gap rejected.
{
C::SourceSet ss;
ss.add_defaults_map("d", {{"host", "h"},
{"shard_ids.0", "1"},
{"shard_ids.2", "3"}});
auto m = C::load_sources(ss);
Void::Testing::require(m.has_value());
auto v = C::validate<StrictServerConfig>(*m, schema);
Void::Testing::expect(!v.has_value());
Void::Testing::expect_eq(
v.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::vector_gap));
}
// Null vs Empty vs Missing vs Removed distinction + no fallback on bad port.
{
C::SourceSet ss;
ss.add_json_text("j", R"({"host":"","port":null,"note":null})");
auto m = C::load_sources(ss);
Void::Testing::require(m.has_value());
Void::Testing::expect(m->state_of("host") == C::ValueState::Empty);
Void::Testing::expect(m->state_of("port") == C::ValueState::Null);
Void::Testing::expect(m->state_of("missing_x") == C::ValueState::Missing);
// null on non-optional int fails instead of falling back to 8080.
auto v = C::validate<StrictServerConfig>(*m, schema);
Void::Testing::expect(!v.has_value());
}
// Removed required field fails required validation.
{
C::SourceSet ss;
ss.add_defaults_map("d", {{"host", "h"}});
ss.add_removals("r", C::SourceKind::Environment, {"host"});
auto m = C::load_sources(ss);
Void::Testing::require(m.has_value());
Void::Testing::expect(m->state_of("host") == C::ValueState::Removed);
auto v = C::validate<StrictServerConfig>(*m, schema);
Void::Testing::expect(!v.has_value());
Void::Testing::expect_eq(
v.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::missing_required));
}
// Cross-field constraint + deprecated warning + restart_required diff.
{
C::SourceSet s1;
s1.add_defaults_map(
"d", {{"host", "prod"}, {"port", "80"}});
auto m1 = C::load_sources(s1);
auto v1 = C::validate<StrictServerConfig>(*m1, schema);
Void::Testing::expect(!v1.has_value());
Void::Testing::expect_eq(
v1.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::constraint_failed));
C::SourceSet s2;
s2.add_defaults_map("d", {{"host", "prod"},
{"port", "8443"},
{"legacy_tls", "true"},
{"bind_interface", "127.0.0.1"}});
C::SourceSet s3;
s3.add_defaults_map("d", {{"host", "prod"},
{"port", "8443"},
{"bind_interface", "10.0.0.1"}});
auto m2 = C::load_sources(s2);
auto m3 = C::load_sources(s3);
auto v2 = C::validate<StrictServerConfig>(*m2, schema);
Void::Testing::require(v2.has_value());
Void::Testing::expect(!v2->warnings.empty());
auto rr = C::detect_restart_required_changes(*m2, *m3, schema);
Void::Testing::expect_eq(rr.size(), std::size_t{1});
Void::Testing::expect_eq(rr[0], std::string{"bind_interface"});
}
}
@@ -0,0 +1,340 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Configuration/ReloadController.hpp>
#include <Void/System/AsyncWatcher.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <filesystem>
#include <memory>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <vector>
namespace void_cfg_async_test
{
namespace C = Void::Configuration;
struct AppSettings {
[[= C::Required{}]] std::string host{"localhost"};
[[= C::IntRange{1, 65535}]] int port{8080};
[[= C::RestartRequired{}]] std::string bind_addr{"0.0.0.0"};
};
template <typename T>
Void::Coro::Task<void> assign_task_result(Void::Coro::Task<T> task,
std::optional<T>* out)
{
*out = co_await task;
}
template <typename T>
T drive_task(Void::Async::ManualExecutor& exec, Void::Coro::Task<T> task)
{
std::optional<T> out;
Void::Async::spawn(exec, assign_task_result(std::move(task), &out));
(void)exec.drain();
return std::move(*out);
}
Void::Coro::Task<Void::Result::Result<C::PreparedChange>> make_resource_ok(
std::string label, std::atomic<int>* disposes)
{
auto view = std::make_shared<std::string>(std::move(label));
C::PreparedChange pc;
pc.view = view;
pc.declared_budget_bytes = 64;
pc.dispose_async =
[disposes]() -> Void::Coro::Task<Void::Result::Result<void>> {
if (disposes != nullptr) {
disposes->fetch_add(1, std::memory_order_relaxed);
}
co_return Void::Result::Result<void>{};
};
co_return pc;
}
Void::Coro::Task<Void::Result::Result<C::PreparedChange>> make_resource_fail()
{
co_return Void::Result::fail(C::make_config_error(
C::ConfigErrorCode::prepare_failed, "participant 2 prepare failed"));
}
Void::Coro::Task<Void::Result::Result<std::pair<
Void::Result::Result<C::ReloadReport>,
Void::Result::Result<C::ReloadReport>>>>
run_two_reloads_concurrent(
std::shared_ptr<C::ReloadController<AppSettings>> ctrl,
C::SourceSet s1, C::SourceSet s2)
{
auto t1 = ctrl->reload(std::move(s1));
auto t2 = ctrl->reload(std::move(s2));
auto r1 = co_await t1;
auto r2 = co_await t2;
co_return Void::Result::Result<
std::pair<Void::Result::Result<C::ReloadReport>,
Void::Result::Result<C::ReloadReport>>>{
std::pair{std::move(r1), std::move(r2)}};
}
} // namespace void_cfg_async_test
using namespace void_cfg_async_test;
// @tag reflection
Void::Testing::Test config_async_fallible_factory_and_participant_rollback()
{
auto schema = C::Schema<AppSettings>::from_reflection();
Void::Async::ManualExecutor exec;
// Invalid initial config fails controller creation cleanly.
{
C::SourceSet bad;
bad.add_defaults_map("d", {{"host", "h"}, {"port", "99999"}});
auto failed = C::ReloadController<AppSettings>::create(
schema, std::move(bad), {.executor = &exec});
Void::Testing::expect(!failed.has_value());
}
C::SourceSet init;
init.add_defaults_map("d", {{"host", "v1"}, {"port", "8080"}});
auto ctrl_res = C::ReloadController<AppSettings>::create(
schema, std::move(init), {.executor = &exec});
Void::Testing::require(ctrl_res.has_value());
auto ctrl = std::move(*ctrl_res);
std::atomic<int> disposals{0};
Void::Testing::require(
ctrl->register_participant(
"p1", 64,
[&](const C::Snapshot<AppSettings>&,
const std::shared_ptr<const AppSettings>& cand,
Void::Async::OperationOptions) {
return make_resource_ok(cand->host + ":" +
std::to_string(cand->port),
&disposals);
})
.has_value());
Void::Testing::require(
ctrl->register_participant(
"p2", 64,
[](const C::Snapshot<AppSettings>&,
const std::shared_ptr<const AppSettings>&,
Void::Async::OperationOptions) {
return make_resource_fail();
})
.has_value());
// Reload fails in p2 -> must dispose p1 and keep generation 1 intact.
{
C::SourceSet s2;
s2.add_defaults_map("d", {{"host", "v2"}, {"port", "9090"}});
auto r = drive_task(exec, ctrl->reload(std::move(s2)));
Void::Testing::expect(!r.has_value());
Void::Testing::expect_eq(disposals.load(), 1);
auto snap = ctrl->current();
Void::Testing::expect_eq(snap.generation, std::uint64_t{1});
Void::Testing::expect_eq(snap.values->host, std::string{"v1"});
}
// Unregister p2 and commit v2 with notification throw isolation +
// post-commit stop observation + restart-required check.
ctrl->unregister_participant("p2");
ctrl->on_committed(
[](const C::Snapshot<AppSettings>&, const C::ReloadReport&) {
throw std::runtime_error("observer failure");
});
std::stop_source ss;
Void::Testing::require(
ctrl->register_participant(
"p_stop", 64,
[&](const C::Snapshot<AppSettings>&,
const std::shared_ptr<const AppSettings>&,
Void::Async::OperationOptions)
-> Void::Coro::Task<Void::Result::Result<C::PreparedChange>> {
// Request stop only inside the second reload if flagged.
co_return co_await make_resource_ok("ok", nullptr);
})
.has_value());
{
C::SourceSet s2;
s2.add_defaults_map("d", {{"host", "v2"}, {"port", "9090"}});
auto r = drive_task(exec, ctrl->reload(std::move(s2)));
Void::Testing::require(r.has_value());
Void::Testing::expect(r->committed);
Void::Testing::expect_eq(r->generation, std::uint64_t{2});
Void::Testing::expect_eq(r->notification_errors.size(), std::size_t{1});
auto snap = ctrl->current();
auto view = snap.resource<std::string>("p1");
Void::Testing::require(view != nullptr);
Void::Testing::expect_eq(*view, std::string{"v2:9090"});
}
// Restart-required key change preserves generation 2 and reports pending.
{
C::SourceSet s_rr;
s_rr.add_defaults_map(
"d", {{"host", "v3"}, {"port", "9091"}, {"bind_addr", "127.0.0.1"}});
auto r = drive_task(exec, ctrl->reload(std::move(s_rr)));
Void::Testing::require(r.has_value());
Void::Testing::expect(!r->committed);
Void::Testing::expect(r->restart_required);
Void::Testing::expect_eq(r->generation, std::uint64_t{2});
Void::Testing::expect_eq(ctrl->current().values->host,
std::string{"v2"});
}
ctrl->close_and_join();
}
// @tag reflection
Void::Testing::Test config_async_retention_precommit_cancel_and_concurrent_order()
{
auto schema = C::Schema<AppSettings>::from_reflection();
Void::Async::ManualExecutor exec;
C::SourceSet init;
init.add_defaults_map("d", {{"host", "g1"}, {"port", "8001"}});
auto ctrl =
C::ReloadController<AppSettings>::create(schema, std::move(init),
{.executor = &exec})
.value();
std::vector<C::Snapshot<AppSettings>> pinned;
pinned.push_back(ctrl->current()); // gen 1
for (int i = 2; i <= 4; ++i) {
C::SourceSet s;
s.add_defaults_map("d", {{"host", "g" + std::to_string(i)},
{"port", std::to_string(8000 + i)}});
auto r = drive_task(exec, ctrl->reload(std::move(s)));
Void::Testing::require(r.has_value());
pinned.push_back(ctrl->current());
}
Void::Testing::expect_eq(ctrl->retained_generation_count(), std::size_t{4});
// 5th generation rejected while 4 snapshots remain pinned.
{
C::SourceSet s5;
s5.add_defaults_map("d", {{"host", "g5"}, {"port", "8005"}});
auto r5 = drive_task(exec, ctrl->reload(std::move(s5)));
Void::Testing::expect(!r5.has_value());
Void::Testing::expect_eq(
r5.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::retention_limit));
}
pinned.erase(pinned.begin()); // Drop gen 1 -> 3 live
// Pre-commit cancellation disposes candidate and preserves gen 4.
std::stop_source ss;
ss.request_stop();
{
C::SourceSet sc;
sc.add_defaults_map("d", {{"host", "cancel"}, {"port", "8006"}});
Void::Async::OperationOptions opts;
opts.stop = ss.get_token();
auto rc = drive_task(exec, ctrl->reload(std::move(sc), opts));
Void::Testing::expect(!rc.has_value());
Void::Testing::expect_eq(
rc.error().code().value,
static_cast<std::int32_t>(C::ConfigErrorCode::cancelled));
Void::Testing::expect_eq(ctrl->current().values->host,
std::string{"g4"});
}
// Concurrent reloads serialize cleanly within the retention budget.
pinned.clear();
{
C::SourceSet a, b;
a.add_defaults_map("d", {{"host", "c1"}, {"port", "8011"}});
b.add_defaults_map("d", {{"host", "c2"}, {"port", "8012"}});
auto both = drive_task(
exec, run_two_reloads_concurrent(ctrl, std::move(a), std::move(b)));
Void::Testing::require(both.has_value());
Void::Testing::require(both->first.has_value());
Void::Testing::require(both->second.has_value());
Void::Testing::expect(both->second->generation >
both->first->generation);
}
}
// @tag reflection
Void::Testing::Test config_async_watcher_coalescing_and_prepare_external()
{
Void::FileSystem::TempDir tmp{"void_cfg_async_watch"};
const auto cfg_path = tmp.path() / "app.json";
Void::Testing::require(
Void::FileSystem::write_file(cfg_path, R"({"host":"init","port":8080})")
.has_value());
auto schema = C::Schema<AppSettings>::from_reflection();
Void::Async::ManualExecutor exec;
Void::Time::ManualClock clock;
Void::SystemAsync::WatcherService watcher{
exec,
Void::SystemAsync::WatcherLimits{
.poll_interval = std::chrono::milliseconds{10},
.debounce_polls = 1},
clock};
auto build_sources = [&]() {
C::SourceSet ss;
ss.add_json_file("app", cfg_path);
return ss;
};
auto ctrl =
C::ReloadController<AppSettings>::create(schema, build_sources(),
{.clock = &clock,
.executor = &exec})
.value();
std::atomic<int> commits{0};
ctrl->on_committed([&](const C::Snapshot<AppSettings>&,
const C::ReloadReport&) {
commits.fetch_add(1, std::memory_order_relaxed);
});
Void::Testing::require(
ctrl->attach_watcher(watcher, {cfg_path}, build_sources, exec)
.has_value());
// Overwrite with invalid JSON first (must keep old), then valid edit.
Void::Testing::require(
Void::FileSystem::write_file(cfg_path, "{broken").has_value());
watcher.poll_once();
(void)exec.drain();
Void::Testing::expect_eq(ctrl->current().values->host,
std::string{"init"});
Void::Testing::require(
Void::FileSystem::write_file(cfg_path,
R"({"host":"watched","port":8099})")
.has_value());
watcher.poll_once();
(void)exec.drain();
Void::Testing::expect_eq(ctrl->current().values->host,
std::string{"watched"});
Void::Testing::expect_eq(ctrl->current().values->port, 8099);
Void::Testing::expect(commits.load() >= 1);
// Prepare-only external coordinator port leaves controller unchanged.
{
C::SourceSet ext;
ext.add_defaults_map("d", {{"host", "staged_ext"}, {"port", "8111"}});
auto prep = drive_task(exec, ctrl->prepare_external(std::move(ext)));
Void::Testing::require(prep.has_value());
Void::Testing::expect_eq(prep->values->host,
std::string{"staged_ext"});
Void::Testing::expect_eq(ctrl->current().values->host,
std::string{"watched"});
(void)drive_task(exec, prep->dispose_all());
}
ctrl->close_and_join();
Void::Testing::expect(watcher.shutdown().has_value());
}
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more