Author SHA1 Message Date
faumaray 9be51134e8 docs(workflow): record Wave 8 Service, Plugin, Configuration, and Fsm verification 2026-11-26 20:19:09 +03:00
faumaray cb988fa985 fix(test): hold owning ServiceHandle across hot-reload calls in FsmServiceHotReload 2026-11-26 17:10:54 +03:00
faumaray 1a54f3857e fix(plugin): use POSIX pthreads in C11 test fixture for TSan compatibility 2026-11-26 17:10:54 +03:00
faumaray 40b579d683 fix(fsm): publish terminal status after exit hooks and join worker before derived teardown 2026-11-26 17:10:54 +03:00
faumaray ef5312c4b3 feat(fsm): structured scopes, race-loser join, boundary checkpoints, and bounded supervision 2026-11-26 16:51:35 +03:00
faumaray 1dc51d5c43 feat(configuration): bounded schemas, provenance/redaction, and async transactional ReloadController 2026-11-26 16:30:30 +03:00
faumaray a24e086e47 feat(plugin): add CAbi.h v1, CModuleHost quiesce/reload/pins, and unlocked PluginManager staging 2026-11-26 16:16:29 +03:00
faumaray 1474a69ab1 feat(service): immutable snapshots, owning ServiceHandle, DAG lifecycle, and ServicePlugin split 2026-11-26 16:03:31 +03:00
faumaray 6b3dededac chore(wave8): reserve lifecycle error domains, support .h headers, add task specs 2026-11-26 15:57:01 +03:00
faumaray d83d0f4533 merge: Wave 7 P2 Sqlite, SqliteAsync, and Storage engine 2026-11-26 15:48:13 +03:00
faumaray 76ad7d1b39 docs(workflow): record Wave 7 verification evidence and tasks 2026-11-26 15:48:13 +03:00
faumaray 84e6fe81ed fix(sqlite): eliminate lock-order inversion between progress trampoline and interrupt_mu 2026-11-26 15:43:02 +03:00
faumaray fdf0da5ca8 feat(storage): implement original V1 durable Storage engine, tools, and async adapter 2026-11-26 15:32:43 +03:00
faumaray 427cc9a843 feat(sqlite): harden Sqlite lifecycle/transactions/migrations/ops and add SqliteAsync pool 2026-11-26 15:17:59 +03:00
faumaray 9925ea1764 docs(workflow): add Wave 7 task specs for Sqlite, SqliteAsync, and Storage 2026-11-25 21:15:10 +03:00
95 changed files with 24946 additions and 998 deletions

No files matched your search

+3 -1
View File
@@ -12,7 +12,9 @@ function(void_add_module MODULE_NAME)
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp")
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp"
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h")
foreach(_excl IN LISTS ARG_EXCLUDE_HEADERS)
list(REMOVE_ITEM HDR "${CMAKE_CURRENT_SOURCE_DIR}/include/${_excl}")
endforeach()
+28 -9
View File
@@ -1,9 +1,8 @@
# Workflow state
Updated: 2026-11-25.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave6b` (from `main`
at `acd77ee`, merged Waves 1–6A plus RFC 8259 decimal `StrictJson` and pushed
to `origin/main`).
Updated: 2026-11-26.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave8` (from `main`
at `d83d0f4`, merged Waves 1–7 and pushed to `origin/main`).
## Completed objective
@@ -302,10 +301,30 @@ while leaving local untracked files untouched.
`binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 333.32 ns,
`data_json_serialize_small_object` 165.99 ns.
### Wave 7 (P2 Persistence & Storage: `Sqlite`, `SqliteAsync`, and NEW Original `Storage` — `G-STORE` Gate)
- Task specs committed on `feat/roadmap-p2-wave7` (`9925ea1`): `tasks/M-SQLITE-01-05.md`, `tasks/S-STORAGE-01-06.md`.
- **`Void::Sqlite` & `Void::SqliteAsync`** (`427cc9a`, TSan lock-order fix `84e6fe8`): hardened `ConnectionState`, `open_database`/`OpenOptions` with checked WAL/FULL/`foreign_keys` pragmas and disabled extension loading, checked positional/named binds, borrowed lifetime owners, strict typed `RowView`/getters, `Transaction` (`sqlite3_get_autocommit`), `Savepoint`, `close()` busy guard, `migrate_checked` with `_void_schema_migrations`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, plus optional `Void::SqliteAsync` (`AsyncPool`, bounded workers, leased interrupt cleanup) and `SqliteOnly`/`SqliteAsyncOnly` installed consumers.
- **`Void::Storage` (`G-STORE` Gate)** (`fdf0da5`): built NEW original durable single-writer key-value storage engine with zero SQLite or external dependencies (`Crc32c`, `Types`, `FilePort`/`PosixFilePort`/`FaultInjectingFilePort`, V1 binary codecs `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1`, `Batch` with preconditions, `Engine` with bootstrap/recovery/tail-truncation/checkpoint/incremental compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance) and `StorageOnly` installed consumer.
- Integrated verification (`84e6fe8`): `VoidTests` 1,417 tests (1,414 passed, 3 intentionally skipped hardware/root checks, 0 failed across 43 modules in 21.06s), `ctest` 2/2 (all 28 installed consumers in 65.05s), Debug ASan+UBSan 1,417 tests (0 leaks, 0 UB in 36.47s), TSan (`SqliteAsync;Storage;Testing`) 19/19 in 15.38s with 0 warnings, and post-Wave-7 `VoidFoundationBench`.
### Wave 8 (P2 Lifecycle: `Service`, `ServicePlugin`, `Plugin`, `Configuration`, `ConfigurationAsync`, and `Fsm`)
- Task specs committed on `feat/roadmap-p2-wave8` (`6b3dede`): `tasks/M-SERVICE-01-05.md`, `tasks/M-PLUGIN-01-06.md`, `tasks/M-CONFIGURATION-01-05.md`, `tasks/M-FSM-01-05.md`; error domains `22..25` reserved in `Functional/Error.hpp` (`kServiceErrorDomain`, `kPluginErrorDomain`, `kConfigurationErrorDomain`, `kFsmErrorDomain`); `cmake/Module.cmake` updated to install `*.h` headers.
- **`Void::Service` & `Void::ServicePlugin`** (`1474a69`): immutable `ServiceSnapshot`, owning `ServiceHandle<I>`, transactional DAG `ProviderSet`/`prepare_batch`/`start_staged`/`publish`/`start_and_publish`/`close_and_join`, split `Void::ServicePlugin` helper target, and `ServiceOnly`/`ServicePluginOnly` installed consumers.
- **`Void::Plugin`** (`a24e086`, TSan pthread fixture fix `1a54f38`): pure-C11 `include/Void/Plugin/CAbi.h` v1 (`VOID_PLUGIN_ABI_VERSION`), `CModuleHost` (pins/quiesce/checkpoint/replace/degraded state/retention/byte budgets/dep topological batching), `CAbiAdapter`, unlocked `PluginManager` staging, 9 pure-C11 `-Werror` test fixtures, and `PluginOnly` installed consumer.
- **`Void::Configuration` & `Void::ConfigurationAsync`** (`1dc51d5`): `Bind.hpp` attributes (`Secret`, `RestartRequired`, `Deprecated`, `IntRange`, `RealRange`), bounded `Schema<T>` reflection/provenance/redaction/deprecation validation, async transactional `ReloadController<T>` + `Snapshot<T>` + `prepare_external` + coalescing `WatcherService`, and `ConfigurationOnly`/`ConfigurationAsyncOnly` installed consumers.
- **`Void::Fsm`** (`ef5312c`, TSan fixes `40b579d`, `cb988fa`): `terminal(Status)`/`TerminationReason`, `FsmErrorCode`/`kFsmErrorDomain = 25`, `FsmLimits`, `ExecutionBinding`, `Checkpoint`/`StateId`, hardened `Detail/Engine` (`MonotonicClock`, bounded `try_post`, `m_control_queue`, `ScopeId` waiter/timer tracking, 64-event/1ms turn budget), `Detail/Awaiter` (scope+user `stop_token` cancellation), `Machine::run`/`acquire_service`/`run_parallel_structured`/`run_parallel_any_structured`/`request_checkpoint`/`restore_checkpoint`, `Orchestrator` (`StopOnFault`/`BoundedRestart`, unlocked observers), `tests/standalone/Fsm/FsmHardening.cpp`, and `FsmOnly` installed consumer.
- Integrated verification (`cb988fa`, `-DVOID_WARNINGS_AS_ERRORS=ON`):
- Full RelWithDebInfo (`/tmp/void-w8-full`, 45 modules): `VoidTests` 1,437 tests (1,434 passed, 3 skipped, 0 failed, `20.99s`); `ctest` 2/2 (`77.11s`, all 34 installed consumers); `VoidFoundationBench` post-W8 (`rev=cb988fa98509`, `/tmp/void-w8-full/post-w8.json`): `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns.
- Full Debug ASan+UBSan (`/tmp/void-w8-asan`, 45 modules): `VoidTests` 1,437 tests (`37.13s`), 0 leaks, 0 UB.
- Debug TSan (`/tmp/void-w8-tsan`, `ServicePlugin;ConfigurationAsync;Fsm;Testing`, 20 modules): `VoidTests` 1,110 tests (1,107 passed, 3 skipped, 0 failed, `11.49s`), 0 data races.
## Ownership and next step
Waves 1–6B (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, and
`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`) are complete and
verified on `feat/roadmap-p2-wave6b`, ready to merge into `main`, push to `origin`, and
proceed continuously to **Wave 7 (`Sqlite`, `SqliteAsync`, and NEW original `Storage`
engine — `G-STORE` gate)**.
Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`,
`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`,
`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`, and
`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`) are complete
and merged to `main`, proceeding to the VoidBuildSystem upstream feature wave
(`VL-001`..`VL-013`) and P2 `Net`.
+16
View File
@@ -94,6 +94,22 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| M-ARCHIVE-01..05 | Hardened `Archive` (`kArchiveErrorDomain = 17`, streaming `Reader` + forensic listing, file-as-parent conflict rejection, exclusive `0700` `StagedTree` + bottom-up `fsync` + Linux `SYS_renameat2(RENAME_NOREPLACE)` atomic `publish()` with `PublicationOutcome::Unknown`, `cleanup_stale_staging`, reproducible `O_NOFOLLOW` `create_archive`, isolated `VoidArchiveWorker` extraction with rlimits + RSS check + parent inventory verification), `ArchiveOnly` consumer (`00d7478`) | [M-ARCHIVE-01-05](tasks/M-ARCHIVE-01-05.md) | VERIFIED | `Archive` 6 + `ArchiveHardening` 3 = 9/9 (`259.0ms`), `ctest` 2/2 (`5.76s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 9/9 (0 races) |
| M-UPDATE-01..06 | Hardened `Update` (`kUpdateErrorDomain = 20`, schema-3 verify-before-payload-parse fix, `StrictJsonProfile` integer-only option, non-forgeable `VerifiedSelection`, `VersionStore::pruneWithPins`, atomic checksummed `ReplayFloorStore`, Ed25519 `TrustStore` rotation/revocation, `ArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` halting with `RecoveryRequired`, `InstallCoordinator` with staged archive + `CleanupPending` + idempotent `reconcile`/`retry_cleanup`), `UpdateOnly` consumer (`47736cb`) | [M-UPDATE-01-06](tasks/M-UPDATE-01-06.md) | VERIFIED | `Update` 22 + `UpdateHardening` 3 = 25/25 (`1.91s`), `ctest` 2/2 (`10.64s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 25/25 (0 races) |
## Wave 7 — P2 Sqlite, SqliteAsync, and Storage (`feat/roadmap-p2-wave7`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| M-SQLITE-01..05 | Hardened `Sqlite` (`kSqliteErrorDomain = 21`, `ConnectionState`, `OpenOptions` checked WAL/FULL/FK pragmas & disabled extension loading, checked binds & borrowed lifetime owners, typed `RowView`, `Transaction` autocommit/busy guards, `Savepoint`, `migrate_checked`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, TSan lock-order fix outside `interrupt_mu`) + optional `SqliteAsync` (`AsyncPool`), `SqliteOnly` & `SqliteAsyncOnly` consumers (`427cc9a`, `84e6fe8`) | [M-SQLITE-01-05](tasks/M-SQLITE-01-05.md) | VERIFIED | Standalone `Sqlite` 14/14 (`426.5ms`), `ctest` 2/2 (`5.11s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) |
| S-STORAGE-01..06 | NEW original `Void::Storage` (`kStorageErrorDomain = 9`, zero SQLite/external deps, `Crc32c`, `PosixFilePort`/`FaultInjectingFilePort`, V1 `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1` codecs, `Batch` preconditions, single-writer `Engine` with recovery/tail-truncation/checkpoint/compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance), `G-STORE` gate, `StorageOnly` consumer (`fdf0da5`) | [S-STORAGE-01-06](tasks/S-STORAGE-01-06.md) | VERIFIED | Standalone zero-ext-deps `Storage` 5/5 (`14.53s`), `ctest` 2/2 (`24.07s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) |
## Wave 8 — P2 Service, Plugin, Configuration, and Fsm (`feat/roadmap-p2-wave8`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| M-SERVICE-01..05 | Hardened `Service` (`kServiceErrorDomain = 22`, immutable `ServiceSnapshot`, owning `ServiceHandle<I>`, transactional DAG `ProviderSet`/`prepare_batch`/`start_staged`/`publish`/`start_and_publish`/`close_and_join`, retained generation cap) + split `ServicePlugin` (`acquire_plugin_service<I>`, `PluginServiceBinding`), `ServiceOnly` & `ServicePluginOnly` consumers (`6b3dede`, `1474a69`) | [M-SERVICE-01-05](tasks/M-SERVICE-01-05.md) | VERIFIED | Standalone `Service;ServicePlugin;Testing` 18/18, `ctest` 2/2 (`7.47s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
| M-PLUGIN-01..06 | Hardened `Plugin` (`kPluginErrorDomain = 23`, pure-C11 `CAbi.h` v1, `CModuleHost` activity pins/quiesce/checkpoint/replace/degraded state/retention/byte budgets/dep topological batching, `CAbiAdapter`, unlocked `PluginManager` staging), `PluginOnly` consumer (`a24e086`, `1a54f38`) | [M-PLUGIN-01-06](tasks/M-PLUGIN-01-06.md) | VERIFIED | Standalone `Plugin;ServicePlugin;Testing` 32 ✔ / 1 skip (`194.5ms`), `ctest` 2/2 (`9.45s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
| M-CONFIGURATION-01..05 | Hardened `Configuration` (`kConfigurationErrorDomain = 24`, `Bind.hpp` attributes, bounded `Schema<T>` reflection/provenance/redaction/deprecation checks) + split `ConfigurationAsync` (transactional `ReloadController<T>`, `Snapshot<T>`, `prepare_external`, coalescing `WatcherService` integration), `ConfigurationOnly` & `ConfigurationAsyncOnly` consumers (`1dc51d5`) | [M-CONFIGURATION-01-05](tasks/M-CONFIGURATION-01-05.md) | VERIFIED | Standalone `ConfigurationAsync;Testing` `Configuration*` 6/6 (`0.7ms`), `ctest` 2/2 (`13.75s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
| M-FSM-01..05 | Hardened `Fsm` (`kFsmErrorDomain = 25`, shared `terminal(Status)` incl. `Faulted`, `TerminationReason`, `FsmLimits` bounds & reserved control lane, `MonotonicClock` & borrowed `ExecutionBinding`, per-state stop scopes & waiter/timer purge before `on_exit()`, `run_parallel_structured` / `run_parallel_any_structured` loser stop+join & tie-break, boundary `request_checkpoint` / `safe_point` / `restore_checkpoint` / `restore_legacy_checkpoint`, `acquire_service<I>()`, hardened `Orchestrator` `StopOnFault`/`BoundedRestart` & `FsmModel::~FsmModel()` worker join), `FsmOnly` consumer (`ef5312c`, `40b579d`, `cb988fa`) | [M-FSM-01-05](tasks/M-FSM-01-05.md) | VERIFIED | Standalone `Fsm;Testing` 814 ✔ / 2 skips (`789.1ms`), `ctest` 2/2 (`9.59s`), Debug TSan 1,107 ✔ (0 races, `internal_FsmServiceHotReload` 4/4), full RelWithDebInfo (`1,434 ✔`, `ctest` 2/2 `77.11s`), ASan+UBSan (`1,434 ✔`, 0 leaks/UB) |
All workers share the checkout and have disjoint file ownership defined in their
persisted task specifications. Root owns all cross-cutting files and resolves contract
changes. No worker owns application code, build files, existing docs/short-url.md, or Git
+14
View File
@@ -267,3 +267,17 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
| Full Integrated ASan+UBSan (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6b-asan`, 41 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w6b-asan/tests/VoidTests` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`21.78s`), 0 ASan/LSan leaks, 0 UBSan errors |
| Wave 6B TSan Subset (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p libsodium` Debug (`CryptoAsync;SecurityAsync;Update;Testing`, `/tmp/void-w6b-tsan`, 20 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6b-tsan/tests/VoidTests --filter "Crypto*\|crypto_*\|Security*\|security_*\|Archive*\|archive_*\|Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*"` | 56/56 passed (`4.86s`: `Archive` 6, `ArchiveHardening` 3, `Crypto` 3, `CryptoHardening` 3, `CryptoAsync` 2, `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2, `Update` 22, `UpdateHardening` 3), 0 TSan data races |
| Post-W6B Benchmark (`47736cb`, `rev=47736cb6ce2f`) | `/tmp/void-w6b-full/benchmarks/VoidFoundationBench --json /tmp/void-w6b-full/post-w6b.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.52ns, `core_uuid_to_string` 16.53ns, `core_hash_fnv1a64_256b` 179.95ns, `core_hash_murmur3_256b` 67.37ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 58.37ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.76ns, `containers_lru_get_put` 21.02ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 333.32ns, `data_json_serialize_small_object` 165.99ns |
| Wave 7 `Sqlite` & `SqliteAsync` standalone (`84e6fe8`) | `dev cpp-gcc -p sqlite` RelWithDebInfo (`-Werror`, `/tmp/void-w7-sqlite`), 8 modules, `VoidTests --filter 'Sqlite*\|...'` + `ctest` | **PASSED**: `SqliteTests` 8 + `SqliteHardening` 4 + `SqliteAsync` 2 = 14/14 in `426.5ms`; `ctest` 2/2 in `5.11s` (`VoidTests` 0.87s, `VoidInstalledComponentConsumers` including `SqliteOnly` & `SqliteAsyncOnly` 4.23s) |
| Wave 7 `Storage` standalone (`fdf0da5`, `G-STORE`) | `dev cpp-gcc` zero `-p` external deps RelWithDebInfo (`-Werror`, `/tmp/void-w7-storage`), 10 modules, `VoidTests --filter '^storage_'` + `ctest` | **PASSED**: `Storage` 5/5 in `14.53s`; `ctest` 2/2 in `24.07s` (`StorageOnly` verified with Boost/LibArchive/OpenSSL/PkgConfig/SQLite3/Threads disabled) |
| Wave 7 TSan (`84e6fe8`) | `dev cpp-gcc -p sqlite` Debug TSan (`-Werror`, `/tmp/void-w7-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 12 modules (`SqliteAsync;Storage;Testing`) | **PASSED**: 19/19 in `15.38s` (`SqliteTests` 8, `SqliteHardening` 4, `SqliteAsync` 2, `Storage` 5), exit 0, 0 TSan data races / lock-order warnings |
| Wave 7 integrated RelWithDebInfo + consumers (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w7-full`), 43 modules, `VoidTests` + `ctest` | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `21.06s`; `ctest` 2/2 in `65.05s` (`VoidTests` 20.95s, all 28 installed consumers 44.10s) |
| Wave 7 full Debug ASan+UBSan (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w7-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 43 modules | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `36.47s`, 0 leaks, 0 UB |
| Post-W7 Benchmark (`84e6fe8`, `VOID_GIT_REV=fdf0da5ca883`) | `/tmp/void-w7-full/benchmarks/VoidFoundationBench --json /tmp/void-w7-full/post-w7.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 25.06ns, `core_uuid_to_string` 16.69ns, `core_hash_fnv1a64_256b` 181.03ns, `core_hash_murmur3_256b` 67.90ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.24ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.62ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 310.70ns, `data_json_serialize_small_object` 160.98ns |
| Wave 8 `Service` & `ServicePlugin` standalone (`1474a69`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-service`, `Service;ServicePlugin;Testing`), `VoidTests` + `ctest` | **PASSED**: `18/18` in `0.4ms`; `ctest` `2/2` in `7.47s` (`ServiceOnly` & `ServicePluginOnly` consumers) |
| Wave 8 `Plugin` standalone (`a24e086`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-plugin`, `Plugin;ServicePlugin;Testing`), 9 pure-C11 `-Werror` fixtures + `VoidTests` + `ctest` | **PASSED**: `33 tests` (`32 ✔`, `1 ⊘` `plugin_load_and_query_skipped`, `0 ✘`) in `194.5ms`; `ctest` `2/2` in `9.45s` (`PluginOnly` consumer) |
| Wave 8 `Configuration` & `ConfigurationAsync` standalone (`1dc51d5`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-config`, `ConfigurationAsync;Testing`), `VoidTests --filter 'Configuration'` + `ctest` | **PASSED**: `ConfigurationHardening` 3/3 + `ConfigurationAsync` 3/3 = `6/6` in `0.7ms`; `ctest` `2/2` in `13.75s` (`ConfigurationOnly` & `ConfigurationAsyncOnly` consumers) |
| Wave 8 `Fsm` standalone (`ef5312c`) | `dev cpp-gcc` RelWithDebInfo (`-Werror`, `/tmp/void-w8-fsm`, `Fsm;Testing`), `VoidTests` + `ctest` | **PASSED**: `816 tests` (`814 ✔`, `2 ⊘`, `0 ✘`) in `789.1ms`; `ctest` `2/2` in `9.59s` (`FsmOnly` consumer) |
| Wave 8 TSan (`cb988fa`) | `dev cpp-gcc` Debug TSan (`-Werror`, `/tmp/void-w8-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 20 modules (`ServicePlugin;ConfigurationAsync;Fsm;Testing`), `VoidTests` | **PASSED**: `1,110 tests` (`1,107 ✔`, `3 ⊘` skipped, `0 ✘`) in `11.49s` (incl. `ServiceHardening` 5/5, `PluginHardening` 5/5, `Configuration*` 6/6, `FsmHardening` 4/4, `internal_FsmServiceHotReload` 4/4), exit `0`, `0` TSan warnings |
| Wave 8 integrated RelWithDebInfo + consumers (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w8-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `20.99s`; `ctest` `2/2` in `77.11s` (`VoidTests` `20.97s`, all `34` installed consumers `56.13s`) |
| Wave 8 full Debug ASan+UBSan (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w8-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `37.13s`, `0` leaks, `0` UB |
| Post-W8 Benchmark (`cb988fa`, `rev=cb988fa98509`) | `/tmp/void-w8-full/benchmarks/VoidFoundationBench --json /tmp/void-w8-full/post-w8.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns |
@@ -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.
@@ -0,0 +1,26 @@
# M-SQLITE-01..05 — Hardened Sqlite C API Integration & Optional SqliteAsync Pool
- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`)
- **Roadmap reference**: `docs/roadmap/modules/Sqlite.md`, `docs/roadmap/DEPENDENCIES.md`
- **Supported runtime observed**: SQLite 3.54.0 via Nix `sqlite` package
## Scope & Ownership
- `src/Sqlite/module.cmake`: `INTERNAL_DEPS Functional Time`, `EXTERNAL_DEPS SQLite3::SQLite3`, `EXCLUDE_HEADERS Void/Sqlite/AsyncPool.hpp`.
- `include/Void/Sqlite/Types.hpp`: `kSqliteErrorDomain = 21`, `SqliteErrorCode`, `JournalMode`, `SyncMode`, `BeginMode`, `CheckpointMode`, `TransactionState`, `SqliteLimits`, `OpenOptions`, `EffectiveCapabilities`, `ColumnType`, `ValueView`, `OwnedValue`, `OwnedRow`, `CheckpointReport`, `BackupOptions`, `BackupReport`, `CheckedMigration`, `ConnectionHealth`, `ScopedFaultGuard`.
- `include/Void/Sqlite/Sqlite.hpp` + `src/Sqlite/Sqlite.cpp`:
- Shared `ConnectionState` held by `Database`, `Statement`, `Transaction`, and `Savepoint` so moving/destroying `Database` never leaves dangling pointers.
- Preserve 1.x APIs (`Database::open`, `exec`, `prepare`, `begin`, `last_insert_rowid`, `changes`, `user_version`, `migrate`, `Statement::bind`/`step`/`reset`/`clear_bindings`/column getters, `Transaction::commit`/`rollback`, `Migration`, `OpenMode`).
- Add `open_database(path, OpenOptions)` validating limits/pragmas (`WAL`, `FULL`, `foreign_keys`, disabling extension loading by default, querying effective pragma results).
- Add checked `bind_checked` (positional & named, `ValueView`, `max_value_bytes` cap), borrowed lifetime-owned bindings, `reset_checked`, `clear_bindings_checked`, `finalize_checked`, strict single-statement `prepare` (rejecting non-whitespace trailing SQL), `RowView` with expiration generation, strict typed column reads rejecting coercion, `query_all` with row/byte caps.
- Transaction state machine (`Active`, `Committed`, `RolledBack`, `RecoveryRequired`): never mark `Committed` before `COMMIT` succeeds; inspect `sqlite3_get_autocommit` on error; reject nested `begin`; add RAII `Savepoint`.
- Checked `Database::close()` rejecting with `busy` while statements/transactions/savepoints remain open; deferred close in destructor reports errors to optional diagnostic hook.
- Validate migration lists before any SQL; add `migrate_checked` recording `id`+`checksum` in `_void_schema_migrations` in the same transaction as `PRAGMA user_version` and rejecting newer schemas and checksum drift.
- Operational methods: `checkpoint()`, `backup_to()`, `restore_from()`, `health()`, WAL write-admission threshold gating, and exception-safe `create_scalar_function` / `set_authorizer` adapters.
- `src/SqliteAsync/module.cmake` + `include/Void/Sqlite/AsyncPool.hpp` + `src/SqliteAsync/AsyncPool.cpp`:
- Optional async leased connection pool (default 4 readers + 1 writer, bounded blocking workers, `max_queued_jobs = 1024`, `max_pending_input_bytes = 64 MiB`).
- Leases one connection for the complete read/write/transaction with serialized progress/interrupt cleanup so cancellation never leaks to the next borrower.
- Tests & consumers: `tests/standalone/Sqlite/SqliteHardening.cpp`, `tests/standalone/SqliteAsync/SqliteAsync.cpp`, `tests/package/SqliteOnly/*`, `tests/package/SqliteAsyncOnly/*`, updated `tests/package/InstalledComponents.cmake`.
## Verification Criteria
- Standalone `Sqlite;SqliteAsync;Testing` RelWithDebInfo `-Werror` (`-p sqlite`): all `Sqlite*` tests + `ctest` 2/2 (`SqliteOnly`, `SqliteAsyncOnly`).
- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset.
@@ -0,0 +1,27 @@
# S-STORAGE-01..06 — Original Durable Key-Value Storage Engine (`G-STORE`)
- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`)
- **Roadmap reference**: `docs/roadmap/subsystems/Storage.md`, `docs/roadmap/DEPENDENCIES.md`
## Scope & Ownership
- Zero SQLite dependency (`src/Storage/module.cmake`: `INTERNAL_DEPS Core Functional Time Memory Binary IO Async`, zero external deps).
- `include/Void/Storage/Crc32c.hpp`: native Castagnoli CRC32C (`0x1EDC6F41` / reflected `0x82F63B78`, golden `"123456789"` == `0xE3069283`).
- `include/Void/Storage/Types.hpp`: `kStorageErrorDomain = 9`, `StorageErrorCode`, `Sequence`, `ByteView`, `OwnedBytes`, `OwnedValue`, `Durability::{Sync,Buffered}`, `Outcome::{NotCommitted,Committed,Unknown}`, `Limits` (all roadmap defaults + non-zero validation), `CommitReceipt`, `WriteFailure`, `ScanBounds` (with `prefix`), `ScanEntry`, `ScanPage`, `EngineState`, `EngineStats`, unsigned-byte lexicographic comparator.
- `include/Void/Storage/FilePort.hpp` + `src/Storage/FilePort.cpp`: `FilePort`, `FileHandle`, `PosixFilePort` (exclusive `flock`, `EINTR`/short-write loops, file & dir `fsync`, atomic same-dir rename capability check), and `FaultInjectingFilePort` for deterministic power-loss / short-write / sync-failure / rename-failure / unsynced-discard simulation.
- `include/Void/Storage/Format.hpp` + `src/Storage/Format.cpp`:
- V1 WAL (`VOIDWAL1` 64B segment header with CRC32C, 36B `VWR1` record header with header CRC32C checked before allocating payload, 8B trailer with record CRC32C + repeated length, `BEGIN`/`PUT`/`ERASE`/`COMMIT` payloads with aggregate CRC32C).
- V1 Immutable Sorted Table (`VOIDTBL1` header, 32 KiB target sorted blocks with per-block CRC32C, sparse block index, checksummed `VOIDTBF1` footer).
- V1 Immutable Manifest (`VOIDMNF1`) and atomic `CURRENT` (`VOIDCUR1`).
- `include/Void/Storage/Batch.hpp`, `include/Void/Storage/Engine.hpp`, `src/Storage/Engine.cpp`:
- Conditional atomic `Batch` (`put`, `erase`, `require_absent`, `require_version`, `require_value`; rejects duplicate keys/conditions; sequence-based versioning prevents ABA).
- Exclusive directory lock, minimal `CURRENT`/manifest bootstrap & WAL segment rotation publication before write admission, deterministic recovery with tail-only truncation of final active segment and fail-closed `corrupt` on damaged complete records or earlier closed segments.
- Single serialized writer, pre-append reservation/encoding, infallible visibility publication, `RecoveryRequired` + `Outcome::Unknown` on post-append failure, pinned `Snapshot`/`Cursor` with continuation scans and `page_too_small` enforcement.
- `checkpoint()` freezing memtable -> immutable table -> manifest -> `CURRENT` -> deferred retirement after snapshot pins release; bounded incremental `compact()` merging <= 4 overlapping runs while preserving versions needed by live snapshots.
- `include/Void/Storage/Tools.hpp` + `src/Storage/Tools.cpp`: `verify_directory` (full block-level read-only verification), pinned `export_backup` / `restore_backup`, offline `salvage_directory` into a separate destination.
- `include/Void/Storage/AsyncAdapter.hpp` + `src/Storage/AsyncAdapter.cpp`: bounded blocking async adapter following C-03 domain-result classification (`stop before append -> NotCommitted`, `stop during sync -> retain until settled`, `sync succeeds after stop -> CommitReceipt`, `sync fails after append -> Unknown + RecoveryRequired`, single delivery).
- `include/Void/Storage/Storage.hpp`: umbrella header.
- Tests & consumer: `tests/standalone/Storage/Storage.cpp` (CRC32C golden, format/overflow, model checker vs reference map, byte-offset truncation, corruption, fault-injected creation/rotation/sync/checkpoint/compaction crashes, retention under slow snapshots, async stop-race conformance, verify/backup/salvage), `tests/package/StorageOnly/*`, updated `tests/package/InstalledComponents.cmake`.
## Verification Criteria
- Standalone `Storage;Testing` RelWithDebInfo `-Werror` (zero external deps!): `storage_*` tests + `ctest` 2/2 (`StorageOnly`).
- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset.
+15
View File
@@ -51,6 +51,21 @@ namespace Void::Configuration
};
struct Required {
};
struct Secret {
};
struct RestartRequired {
};
struct Deprecated {
Void::Meta::Str message;
};
struct IntRange {
std::int64_t min{0};
std::int64_t max{0};
};
struct RealRange {
double min{0.0};
double max{0.0};
};
#ifdef VOID_HAS_CONFIG_REFLECTION
@@ -0,0 +1,784 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Configuration/Schema.hpp>
#include <Void/System/AsyncWatcher.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <exception>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Configuration
{
struct PreparedChange {
std::shared_ptr<const void> view{};
std::size_t declared_budget_bytes{0};
std::function<Void::Coro::Task<Void::Result::Result<void>>()>
dispose_async{};
};
template <typename T> struct Snapshot {
std::uint64_t generation{0};
std::shared_ptr<const T> values{};
std::shared_ptr<const Provenance> provenance{};
std::shared_ptr<const MergedConfig> raw{};
std::shared_ptr<
const std::unordered_map<std::string, std::shared_ptr<const void>>>
resources{};
std::shared_ptr<const void> retention_token{};
template <typename R>
[[nodiscard]] std::shared_ptr<const R>
resource(std::string_view participant_id) const
{
if (!resources) {
return nullptr;
}
const auto it = resources->find(std::string{participant_id});
if (it == resources->end()) {
return nullptr;
}
return std::static_pointer_cast<const R>(it->second);
}
[[nodiscard]] explicit operator bool() const noexcept
{
return values != nullptr;
}
};
template <typename T> struct PreparedAggregate {
std::shared_ptr<const T> values{};
std::shared_ptr<const Provenance> provenance{};
std::shared_ptr<const MergedConfig> raw{};
std::shared_ptr<
const std::unordered_map<std::string, std::shared_ptr<const void>>>
resources{};
std::vector<PreparedChange> staged_changes{};
std::vector<std::string> changed_keys{};
std::vector<std::string> warnings{};
Void::Coro::Task<Void::Result::Result<void>> dispose_all()
{
for (auto it = staged_changes.rbegin();
it != staged_changes.rend(); ++it) {
if (it->dispose_async) {
(void)co_await it->dispose_async();
}
}
staged_changes.clear();
co_return Void::Result::Result<void>{};
}
};
struct ReloadReport {
std::uint64_t generation{0};
bool committed{false};
bool restart_required{false};
std::vector<std::string> restart_required_keys{};
bool stop_observed_after_commit{false};
std::vector<std::string> changed_keys{};
std::vector<Void::Result::Error> notification_errors{};
std::vector<std::string> warnings{};
std::size_t coalesced_events{0};
};
namespace detail
{
class AsyncReloadGate
{
public:
struct Waiter {
Void::Async::Executor* exec{nullptr};
std::coroutine_handle<> h{};
};
struct Guard {
AsyncReloadGate* gate{nullptr};
Guard() noexcept = default;
explicit Guard(AsyncReloadGate* g) noexcept : gate(g) {}
Guard(Guard&& o) noexcept
: gate(std::exchange(o.gate, nullptr))
{
}
Guard& operator=(Guard&& o) noexcept
{
if (this != &o) {
if (gate != nullptr) gate->release();
gate = std::exchange(o.gate, nullptr);
}
return *this;
}
~Guard()
{
if (gate != nullptr) {
gate->release();
}
}
Guard(const Guard&) = delete;
Guard& operator=(const Guard&) = delete;
};
struct Awaiter {
AsyncReloadGate* gate;
Void::Async::Executor* exec;
bool await_ready() noexcept { return gate->try_lock(); }
bool await_suspend(std::coroutine_handle<> h) noexcept
{
return gate->enqueue_or_acquire(exec, h);
}
Guard await_resume() noexcept { return Guard{gate}; }
};
Awaiter lock(Void::Async::Executor* exec) noexcept
{
return Awaiter{this, exec};
}
bool try_lock() noexcept;
bool enqueue_or_acquire(Void::Async::Executor* exec,
std::coroutine_handle<> h) noexcept;
void release() noexcept;
private:
std::mutex mu_{};
bool locked_{false};
std::deque<Waiter> waiters_{};
};
[[nodiscard]] std::vector<std::string>
diff_merged_keys(const MergedConfig& old_cfg,
const MergedConfig& new_cfg);
} // namespace detail
struct ControllerOptions {
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
Void::Async::Executor* executor{nullptr};
};
template <typename T>
class ReloadController
: public std::enable_shared_from_this<ReloadController<T>>
{
public:
using PrepareFn = std::function<
Void::Coro::Task<Void::Result::Result<PreparedChange>>(
const Snapshot<T>& old_snapshot,
const std::shared_ptr<const T>& candidate,
Void::Async::OperationOptions options)>;
using CommitListener =
std::function<void(const Snapshot<T>& snapshot,
const ReloadReport& report)>;
[[nodiscard]] static Void::Result::Result<
std::shared_ptr<ReloadController<T>>>
create(Schema<T> schema, SourceSet initial_sources,
ControllerOptions options = {})
{
auto merged = load_sources(initial_sources, schema.limits(),
schema.secret_keys());
if (!merged) {
return Void::Result::fail(std::move(merged).error());
}
auto validated = validate<T>(*merged, schema);
if (!validated) {
return Void::Result::fail(std::move(validated).error());
}
auto ctrl = std::shared_ptr<ReloadController<T>>(
new ReloadController<T>(std::move(schema), options));
auto merged_ptr =
std::make_shared<const MergedConfig>(std::move(*merged));
auto val_ptr =
std::make_shared<const T>(std::move(validated->value));
auto res_ptr = std::make_shared<const std::unordered_map<
std::string, std::shared_ptr<const void>>>();
auto tok = std::make_shared<const int>(1);
ctrl->m_retention_tokens.push_back(tok);
ctrl->m_current = Snapshot<T>{
.generation = 1,
.values = std::move(val_ptr),
.provenance = merged_ptr->provenance,
.raw = std::move(merged_ptr),
.resources = std::move(res_ptr),
.retention_token = std::move(tok),
};
ctrl->m_generation = 1;
return ctrl;
}
~ReloadController() { close_and_join(); }
ReloadController(const ReloadController&) = delete;
ReloadController& operator=(const ReloadController&) = delete;
[[nodiscard]] Snapshot<T> current() const
{
std::lock_guard lk{m_pub_mu};
return m_current;
}
[[nodiscard]] std::size_t retained_generation_count() const
{
std::lock_guard lk{m_pub_mu};
std::size_t live = 0;
for (const auto& w : m_retention_tokens) {
if (!w.expired()) ++live;
}
return live;
}
Void::Result::Result<void>
register_participant(std::string id,
std::size_t declared_budget_bytes,
PrepareFn prepare_fn)
{
if (id.empty() || !prepare_fn) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::invalid_argument,
"ReloadController: participant id and callback required"));
}
std::lock_guard lk{m_part_mu};
if (m_closing) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::prepare_failed,
"ReloadController: controller closing"));
}
if (m_participants.size() >= m_schema.limits().max_participants) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::limit_exceeded,
"ReloadController: max_participants exceeded"));
}
for (const auto& p : m_participants) {
if (p.id == id && !p.removing) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::key_collision,
"ReloadController: duplicate participant id '" +
id + "'"));
}
}
m_participants.push_back(ParticipantEntry{
.id = std::move(id),
.budget_bytes = declared_budget_bytes,
.prepare = std::move(prepare_fn),
.in_flight = 0,
.removing = false,
});
return {};
}
void unregister_participant(std::string_view id)
{
std::unique_lock lk{m_part_mu};
for (auto& p : m_participants) {
if (p.id == id) {
p.removing = true;
break;
}
}
m_part_cv.wait(lk, [&] {
for (const auto& p : m_participants) {
if (p.id == id && p.in_flight > 0) return false;
}
return true;
});
std::erase_if(m_participants, [&](const ParticipantEntry& p) {
return p.id == id;
});
}
std::size_t on_committed(CommitListener listener)
{
std::lock_guard lk{m_listener_mu};
const std::size_t id = m_next_listener_id++;
m_listeners.emplace_back(id, std::move(listener));
return id;
}
void remove_listener(std::size_t id)
{
std::lock_guard lk{m_listener_mu};
std::erase_if(m_listeners, [id](const auto& pair) {
return pair.first == id;
});
}
/// Prepare-only port exporting a staged candidate aggregate for a
/// higher-level platform coordinator without swapping m_current.
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<PreparedAggregate<T>>>
prepare_external(SourceSet sources,
Void::Async::OperationOptions opts = {})
{
auto gate_guard = co_await m_gate.lock(m_executor);
if (opts.stop.stop_requested()) {
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::cancelled,
"ReloadController::prepare_external: cancelled"));
}
auto snap = current();
co_return co_await prepare_candidate(
std::move(sources), snap, opts, nullptr);
}
[[nodiscard]] Void::Coro::Task<Void::Result::Result<ReloadReport>>
reload(SourceSet sources, Void::Async::OperationOptions opts = {})
{
if (opts.stop.stop_requested()) {
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::cancelled,
"ReloadController::reload: cancelled before admission"));
}
auto gate_guard = co_await m_gate.lock(m_executor);
if (opts.stop.stop_requested()) {
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::cancelled,
"ReloadController::reload: cancelled while queued"));
}
Snapshot<T> old_snap;
std::uint64_t expected_gen = 0;
{
std::lock_guard lk{m_pub_mu};
std::erase_if(m_retention_tokens, [](const auto& w) {
return w.expired();
});
if (m_schema.limits().max_retained_generations > 0 &&
m_retention_tokens.size() >=
m_schema.limits().max_retained_generations) {
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::retention_limit,
"ReloadController::reload: max_retained_generations reached"));
}
old_snap = m_current;
expected_gen = m_generation;
}
std::vector<std::string> restart_keys;
auto cand_res = co_await prepare_candidate(
std::move(sources), old_snap, opts, &restart_keys);
if (!restart_keys.empty()) {
ReloadReport rep;
rep.generation = expected_gen;
rep.committed = false;
rep.restart_required = true;
rep.restart_required_keys = std::move(restart_keys);
co_return rep;
}
if (!cand_res) {
co_return Void::Result::fail(std::move(cand_res).error());
}
auto agg = std::move(*cand_res);
// Check pre-commit stop/deadline before swapping m_current.
if (opts.stop.stop_requested()) {
(void)co_await agg.dispose_all();
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::cancelled,
"ReloadController::reload: cancelled before commit"));
}
if (opts.deadline.has_value() &&
m_clock->now() >= *opts.deadline) {
(void)co_await agg.dispose_all();
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::timeout,
"ReloadController::reload: deadline expired before commit"));
}
// Short pointer swap — commit point (zero user callbacks or
// allocations under m_pub_mu).
auto tok = std::make_shared<const int>(1);
Snapshot<T> new_snap{
.generation = expected_gen + 1,
.values = std::move(agg.values),
.provenance = std::move(agg.provenance),
.raw = std::move(agg.raw),
.resources = std::move(agg.resources),
.retention_token = tok,
};
Snapshot<T> retired_old;
{
std::lock_guard lk{m_pub_mu};
if (m_generation != expected_gen || m_closing) {
// Should be impossible under m_gate, fail-safe rollback.
retired_old = Snapshot<T>{};
} else {
m_generation = new_snap.generation;
m_retention_tokens.push_back(tok);
retired_old = std::exchange(m_current, new_snap);
}
}
if (!retired_old) {
(void)co_await agg.dispose_all();
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::internal,
"ReloadController::reload: generation swap conflict"));
}
// Release old snapshot outside lock.
retired_old = Snapshot<T>{};
ReloadReport rep;
rep.generation = new_snap.generation;
rep.committed = true;
rep.changed_keys = std::move(agg.changed_keys);
rep.warnings = std::move(agg.warnings);
rep.stop_observed_after_commit = opts.stop.stop_requested();
rep.coalesced_events =
m_coalesced_events.exchange(0, std::memory_order_acq_rel);
// Notify observers strictly outside locks; capture exceptions
// without claiming rollback.
std::vector<CommitListener> copy;
{
std::lock_guard lk{m_listener_mu};
copy.reserve(m_listeners.size());
for (const auto& [_, fn] : m_listeners) {
if (fn) copy.push_back(fn);
}
}
const std::size_t notify_cap =
std::min(copy.size(), m_schema.limits().max_notifications);
for (std::size_t i = 0; i < notify_cap; ++i) {
try {
copy[i](new_snap, rep);
} catch (const std::exception& ex) {
rep.notification_errors.push_back(make_config_error(
ConfigErrorCode::internal, ex.what()));
} catch (...) {
rep.notification_errors.push_back(make_config_error(
ConfigErrorCode::internal,
"ReloadController: notification callback threw"));
}
}
co_return rep;
}
[[nodiscard]] Void::Result::Result<void> attach_watcher(
Void::SystemAsync::WatcherService& watcher,
std::vector<std::filesystem::path> paths,
std::function<SourceSet()> build_sources,
Void::Async::Executor& exec)
{
std::lock_guard lk{m_watch_mu};
if (m_closing) {
return Void::Result::fail(make_config_error(
ConfigErrorCode::internal,
"ReloadController::attach_watcher: controller closing"));
}
std::weak_ptr<ReloadController<T>> weak_self =
this->weak_from_this();
auto on_change = [weak_self, build = std::move(build_sources),
&exec](const Void::SystemAsync::WatchEvent&) {
auto self = weak_self.lock();
if (!self) return;
if (self->m_watcher_busy.exchange(
true, std::memory_order_acq_rel)) {
self->m_coalesced_events.fetch_add(
1, std::memory_order_relaxed);
self->m_watcher_dirty.store(true,
std::memory_order_release);
return;
}
self->schedule_watch_reload(build, exec);
};
std::vector<Void::SystemAsync::WatchSubscription> subs;
for (const auto& p : paths) {
auto sr = watcher.watch(p, on_change);
if (!sr) {
for (auto& s : subs) (void)s.close_and_join();
return Void::Result::fail(std::move(sr).error());
}
subs.push_back(std::move(*sr));
}
for (auto& s : subs) {
m_watch_subs.push_back(std::move(s));
}
return {};
}
void close_and_join()
{
{
std::lock_guard lk{m_part_mu};
m_closing = true;
}
{
std::lock_guard lk{m_pub_mu};
m_closing = true;
}
std::vector<Void::SystemAsync::WatchSubscription> subs;
{
std::lock_guard lk{m_watch_mu};
subs.swap(m_watch_subs);
}
for (auto& s : subs) {
(void)s.close_and_join();
}
std::unique_lock lk{m_part_mu};
m_part_cv.wait(lk, [&] {
for (const auto& p : m_participants) {
if (p.in_flight > 0) return false;
}
return true;
});
}
private:
struct ParticipantEntry {
std::string id{};
std::size_t budget_bytes{0};
PrepareFn prepare{};
std::size_t in_flight{0};
bool removing{false};
};
ReloadController(Schema<T> schema, ControllerOptions opts)
: m_schema(std::move(schema)),
m_clock(opts.clock ? opts.clock
: &Void::Time::SystemMonotonicClock::instance()),
m_executor(opts.executor)
{
}
static Void::Coro::Task<void> run_watch_reload_task(
std::weak_ptr<ReloadController<T>> weak_self,
std::function<SourceSet()> build,
Void::Async::Executor* exec)
{
for (;;) {
auto self = weak_self.lock();
if (!self) co_return;
self->m_watcher_dirty.store(false,
std::memory_order_release);
auto res = co_await self->reload(build());
(void)res;
if (!self->m_watcher_dirty.load(
std::memory_order_acquire)) {
self->m_watcher_busy.store(false,
std::memory_order_release);
if (!self->m_watcher_dirty.load(
std::memory_order_acquire)) {
co_return;
}
if (self->m_watcher_busy.exchange(
true, std::memory_order_acq_rel)) {
co_return;
}
}
}
(void)exec;
}
void schedule_watch_reload(const std::function<SourceSet()>& build,
Void::Async::Executor& exec)
{
Void::Async::spawn(
exec, run_watch_reload_task(this->weak_from_this(), build,
&exec));
}
Void::Coro::Task<Void::Result::Result<PreparedAggregate<T>>>
prepare_candidate(SourceSet sources,
const Snapshot<T>& old_snap,
Void::Async::OperationOptions opts,
std::vector<std::string>* restart_out)
{
auto merged = load_sources(sources, m_schema.limits(),
m_schema.secret_keys());
if (!merged) {
co_return Void::Result::fail(std::move(merged).error());
}
auto validated = validate<T>(*merged, m_schema);
if (!validated) {
co_return Void::Result::fail(std::move(validated).error());
}
if (restart_out != nullptr && old_snap.raw) {
auto rr = detect_restart_required_changes<T>(
*old_snap.raw, *merged, m_schema);
if (!rr.empty()) {
*restart_out = std::move(rr);
co_return Void::Result::fail(make_config_error(
ConfigErrorCode::restart_required,
"ReloadController: restart-required keys changed"));
}
}
auto merged_ptr =
std::make_shared<const MergedConfig>(std::move(*merged));
auto cand_ptr =
std::make_shared<const T>(std::move(validated->value));
auto res_map = std::make_shared<
std::unordered_map<std::string, std::shared_ptr<const void>>>();
std::vector<PreparedChange> prepared_list;
const auto prep_deadline =
m_clock->now() + m_schema.limits().default_prepare_timeout;
Void::Async::OperationOptions p_opts = opts;
if (!p_opts.deadline.has_value() ||
prep_deadline < *p_opts.deadline) {
p_opts.deadline = prep_deadline;
}
// Snapshot participants safely.
struct ActivePart {
std::string id;
std::size_t budget_bytes;
PrepareFn prepare;
};
std::vector<ActivePart> parts;
{
std::lock_guard lk{m_part_mu};
for (auto& p : m_participants) {
if (!p.removing && p.prepare) {
++p.in_flight;
parts.push_back(
ActivePart{p.id, p.budget_bytes, p.prepare});
}
}
}
auto release_inflight = [&]() {
std::lock_guard lk{m_part_mu};
for (auto& ap : parts) {
for (auto& p : m_participants) {
if (p.id == ap.id && p.in_flight > 0) {
--p.in_flight;
}
}
}
m_part_cv.notify_all();
};
std::optional<Void::Result::Error> prep_err;
std::size_t total_budget = 0;
for (auto& ap : parts) {
if (p_opts.stop.stop_requested()) {
prep_err = make_config_error(
ConfigErrorCode::cancelled,
"ReloadController: cancelled during participant prepare");
break;
}
if (p_opts.deadline.has_value() &&
m_clock->now() >= *p_opts.deadline) {
prep_err = make_config_error(
ConfigErrorCode::timeout,
"ReloadController: participant prepare timed out");
break;
}
try {
auto pr =
co_await ap.prepare(old_snap, cand_ptr, p_opts);
if (!pr) {
prep_err = std::move(pr).error();
break;
}
const std::size_t item_budget = std::max(
ap.budget_bytes, pr->declared_budget_bytes);
if (total_budget + item_budget >
m_schema.limits().max_merged_bytes) {
if (pr->dispose_async) {
(void)co_await pr->dispose_async();
}
prep_err = make_config_error(
ConfigErrorCode::limit_exceeded,
"ReloadController: participant budget exceeded");
break;
}
total_budget += item_budget;
if (pr->view) {
res_map->insert_or_assign(ap.id, pr->view);
}
prepared_list.push_back(std::move(*pr));
} catch (const std::exception& ex) {
prep_err = make_config_error(
ConfigErrorCode::prepare_failed, ex.what());
break;
} catch (...) {
prep_err = make_config_error(
ConfigErrorCode::prepare_failed,
"ReloadController: participant prepare threw");
break;
}
}
release_inflight();
if (prep_err.has_value()) {
for (auto it = prepared_list.rbegin();
it != prepared_list.rend(); ++it) {
if (it->dispose_async) {
(void)co_await it->dispose_async();
}
}
co_return Void::Result::fail(std::move(*prep_err));
}
PreparedAggregate<T> agg;
agg.values = std::move(cand_ptr);
agg.provenance = merged_ptr->provenance;
if (old_snap.raw) {
agg.changed_keys =
detail::diff_merged_keys(*old_snap.raw, *merged_ptr);
}
agg.raw = std::move(merged_ptr);
agg.resources = std::move(res_map);
agg.staged_changes = std::move(prepared_list);
agg.warnings = std::move(validated->warnings);
co_return agg;
}
Schema<T> m_schema;
const Void::Time::MonotonicClock* m_clock;
Void::Async::Executor* m_executor{nullptr};
detail::AsyncReloadGate m_gate{};
mutable std::mutex m_pub_mu{};
Snapshot<T> m_current{};
std::uint64_t m_generation{0};
std::vector<std::weak_ptr<const void>> m_retention_tokens{};
bool m_closing{false};
std::mutex m_part_mu{};
std::condition_variable m_part_cv{};
std::vector<ParticipantEntry> m_participants{};
std::mutex m_listener_mu{};
std::vector<std::pair<std::size_t, CommitListener>> m_listeners{};
std::size_t m_next_listener_id{1};
std::mutex m_watch_mu{};
std::vector<Void::SystemAsync::WatchSubscription> m_watch_subs{};
std::atomic<bool> m_watcher_busy{false};
std::atomic<bool> m_watcher_dirty{false};
std::atomic<std::size_t> m_coalesced_events{0};
};
} // namespace Void::Configuration
File diff suppressed because it is too large. Load diff
+81 -18
View File
@@ -1,41 +1,90 @@
#pragma once
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <coroutine>
#include <optional>
#include <span>
#include <stop_token>
#include <typeinfo>
#include <utility>
namespace Void::Fsm::Detail
{
/// One awaiter for every "wait for an event (optionally with a deadline)"
/// operation on a machine. `Storage` is the type-list container (a
/// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is
/// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the
/// awaited value (the matched event, an optional on timeout, a variant,
/// …). Built on ExecutionContext::{try_take_any,set_waiter}.
struct WaiterCancelFn {
ExecutionContext* ctx{nullptr};
ExecutionContext::WaiterId waiter_id{0};
void operator()() const
{
if (ctx != nullptr && waiter_id != 0) {
(void)ctx->try_post_control(
[c = ctx, wid = waiter_id] { c->cancel_waiter(wid); });
}
}
};
/// Unified awaiter for awaiting an event (or event set), optional timeout
/// on injected clock, and cooperative stop cancellation across both
/// per-state scope stop and caller-supplied OperationOptions stop tokens.
template <typename Storage, typename Resume> struct EventAwaiter {
ExecutionContext* ctx;
Storage types;
EventEnvelope env;
ExecutionContext* ctx{nullptr};
Storage types{};
EventEnvelope env{};
bool timed_out{false};
std::optional<std::chrono::steady_clock::time_point> deadline;
Resume resume;
bool cancelled{false};
std::optional<Time::MonotonicClock::time_point> deadline{};
Resume resume{};
ExecutionContext::ScopeId scope{ExecutionContext::kNoScope};
std::stop_token scope_stop{};
std::stop_token user_stop{};
ExecutionContext::WaiterId waiter_id{0};
std::optional<std::stop_callback<WaiterCancelFn>> scope_cb{};
std::optional<std::stop_callback<WaiterCancelFn>> user_cb{};
[[nodiscard]] bool await_ready()
{
return ctx->try_take_any(span(), env);
if (scope_stop.stop_requested() || user_stop.stop_requested()) {
cancelled = true;
return true;
}
if (ctx != nullptr && !types.empty() &&
ctx->try_take_any(span(), env)) {
return true;
}
if (deadline.has_value() && ctx != nullptr &&
ctx->clock().now() >= *deadline) {
timed_out = true;
return true;
}
return false;
}
void await_suspend(std::coroutine_handle<> h)
{
ctx->set_waiter(span(), h, &env, &timed_out, deadline);
waiter_id = ctx->set_waiter(span(), h, &env, &timed_out,
deadline, scope, &cancelled);
if (scope_stop.stop_possible()) {
scope_cb.emplace(scope_stop,
WaiterCancelFn{ctx, waiter_id});
}
if (user_stop.stop_possible()) {
user_cb.emplace(user_stop, WaiterCancelFn{ctx, waiter_id});
}
}
[[nodiscard]] decltype(auto) await_resume()
decltype(auto) await_resume()
{
return resume(std::move(env), timed_out);
scope_cb.reset();
user_cb.reset();
if constexpr (std::is_invocable_v<Resume&, EventEnvelope&&,
bool, bool>) {
return resume(std::move(env), timed_out, cancelled);
} else {
return resume(std::move(env), timed_out);
}
}
private:
@@ -49,10 +98,24 @@ namespace Void::Fsm::Detail
template <typename Storage, typename Resume>
[[nodiscard]] auto make_event_awaiter(
ExecutionContext* ctx, Storage types,
std::optional<std::chrono::steady_clock::time_point> deadline,
Resume resume)
std::optional<Time::MonotonicClock::time_point> deadline,
Resume resume,
ExecutionContext::ScopeId scope = ExecutionContext::kNoScope,
std::stop_token scope_stop = {}, std::stop_token user_stop = {})
{
return EventAwaiter<Storage, Resume>{
ctx, std::move(types), {}, false, deadline, std::move(resume)};
ctx,
std::move(types),
{},
false,
false,
deadline,
std::move(resume),
scope,
std::move(scope_stop),
std::move(user_stop),
0,
std::nullopt,
std::nullopt};
}
} // namespace Void::Fsm::Detail
+141 -54
View File
@@ -4,6 +4,8 @@
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <any>
#include <atomic>
@@ -14,6 +16,7 @@
#include <deque>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <semaphore>
@@ -28,17 +31,14 @@ namespace Void::Fsm::Detail
{
/// Type-erased state. Concrete states derive the single Machine<Derived>::
/// State base; the engine drives each via a signature-inferred per-state
/// thunk (entry / reactive table / continuation handlers).
/// thunk (entry / continuation handlers).
class StateBase
{
public:
virtual ~StateBase() = default;
/// Optional entry/exit lifecycle hooks (default no-ops). The
/// state's behaviour (entry / reactive table / continuation
/// handlers) is discovered by signature via a per-state driver
/// thunk — there is no virtual run().
/// Optional entry/exit lifecycle hooks (default no-ops).
virtual Coro::Task<void> on_enter();
virtual Coro::Task<void> on_exit();
};
@@ -46,18 +46,28 @@ namespace Void::Fsm::Detail
struct EventEnvelope {
const std::type_info* type{nullptr};
std::any value;
std::size_t bytes{0};
};
/// Shared execution substrate for a machine and any machines it nests:
/// one executor + one worker thread + one typed event mailbox. A single
/// consumer (the worker, or the embedder via pump()) touches all
/// mailbox state, so state code runs lock-free and single-threaded;
/// cross-thread post() only enqueues.
/// one logical strand (owned worker, embedder pump(), or borrowed external
/// executor) + bounded event mailbox + reserved control lane + Clock-driven
/// timers. Cross-thread posts enqueue owned envelopes; only the active
/// consumer strand touches waiter/timer/buffer tables.
class ExecutionContext
: public std::enable_shared_from_this<ExecutionContext>
{
public:
ExecutionContext() = default;
using TimerId = std::uint64_t;
using WaiterId = std::uint64_t;
using ScopeId = std::uint64_t;
static constexpr ScopeId kNoScope = 0;
explicit ExecutionContext(
const Time::MonotonicClock* clock = nullptr,
FsmLimits limits = {},
Async::Executor* external_executor = nullptr);
~ExecutionContext();
ExecutionContext(const ExecutionContext&) = delete;
@@ -67,14 +77,61 @@ namespace Void::Fsm::Detail
{
return m_executor;
}
[[nodiscard]] Async::Executor& active_executor() noexcept
{
return m_external_executor != nullptr
? *m_external_executor
: static_cast<Async::Executor&>(m_executor);
}
[[nodiscard]] const Time::MonotonicClock& clock() const noexcept
{
return *m_clock;
}
[[nodiscard]] const FsmLimits& limits() const noexcept
{
return m_limits;
}
[[nodiscard]] std::uint64_t dispatch_turn() const noexcept
{
return m_dispatch_turn;
}
[[nodiscard]] std::size_t last_turn_events() const noexcept
{
return m_last_turn_events;
}
[[nodiscard]] std::size_t queued_events() const noexcept
{
return m_queued_events.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t queued_bytes() const noexcept
{
return m_queued_bytes.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t active_child_regions() const noexcept
{
return m_active_child_regions.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t timer_count() const noexcept
{
return m_timers.size();
}
// ── events (post is the only cross-thread entry point) ────────
[[nodiscard]] bool
try_acquire_child_regions(std::size_t count) noexcept;
void release_child_regions(std::size_t count) noexcept;
// ── events & control (thread-safe entry points) ──────────────
[[nodiscard]] Void::Result::Result<void>
try_post(EventEnvelope env);
void post(EventEnvelope env);
[[nodiscard]] Void::Result::Result<void>
try_post_control(std::function<void()> fn);
// Mailbox ops — consumer thread only (called from awaiters that
// run on the executor, and from the worker drain).
using TimerId = std::uint64_t;
// ── strand-only scope/waiter/timer APIs ──────────────────────
[[nodiscard]] ScopeId allocate_scope() noexcept
{
return m_next_scope.fetch_add(1, std::memory_order_relaxed);
}
/// Pop the oldest buffered event whose type is in `types`.
[[nodiscard]] bool
@@ -82,68 +139,66 @@ namespace Void::Fsm::Detail
EventEnvelope& out);
/// Suspend until an event of one of `types` arrives, or (if
/// `deadline` is set) the deadline passes. `slot` receives the
/// matched event; `*timed_out` is set true on timeout.
void set_waiter(
/// `deadline` is set) the deadline passes, or the waiter/scope is
/// cancelled.
WaiterId set_waiter(
std::span<const std::type_info* const> types,
std::coroutine_handle<> cont, EventEnvelope* slot,
bool* timed_out,
std::optional<std::chrono::steady_clock::time_point> deadline);
std::optional<Time::MonotonicClock::time_point> deadline,
ScopeId scope = kNoScope, bool* cancelled = nullptr);
/// Schedule `on_fire` at `deadline`. Returns an id for
/// cancel_timer.
TimerId add_timer(std::chrono::steady_clock::time_point deadline,
std::function<void()>
on_fire);
void cancel_waiter(WaiterId id);
void cancel_scope(ScopeId scope);
void purge_scope(ScopeId scope);
void drain_control_queue();
/// Schedule `on_fire` at `deadline` (enforces max_timers).
[[nodiscard]] Void::Result::Result<TimerId>
try_add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope = kNoScope);
TimerId add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope = kNoScope);
void cancel_timer(TimerId id);
// ── worker lifecycle ─────────────────────────────────────────
/// Spawn the worker thread (idempotent).
// ── worker / pump lifecycle ──────────────────────────────────
void start_worker();
/// Mark finished and wake the worker so it can exit.
void finish();
/// Stop and join the worker.
void stop();
/// Join the worker without forcing finish (waits for the
/// driver to finish() on its own).
void join();
[[nodiscard]] bool finished() const noexcept
{
return m_done.load(std::memory_order_acquire);
}
/// Embedder-driven step: deliver queued events + run ready
/// coroutines. Returns work done count. Single consumer only.
/// A no-op (returns 0) while paused.
/// Embedder-driven step: drain control lane, fire due timers on
/// injected clock, deliver up to max_events_per_turn /
/// max_turn_duration user events, and drain internal executor.
std::size_t pump();
/// Pause / resume event processing. While paused the worker stops
/// draining (and pump() is a no-op); posted events buffer.
void set_paused(bool paused);
/// Called on external executor threads via scheduled task.
void run_external_pump_step();
/// Wake the consumer (e.g. to re-check an external jump request).
void set_paused(bool paused);
void nudge() { wake(); }
private:
void deliver(EventEnvelope& env);
void run_loop();
void wake() noexcept;
void fire_due_timers();
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
next_deadline() const;
struct BufferedEvent {
std::any value;
std::size_t bytes{0};
};
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::unordered_map<std::type_index, std::deque<std::any>> m_buffers;
using WaiterId = std::uint64_t;
struct Waiter {
WaiterId id{0};
ScopeId scope{kNoScope};
std::vector<const std::type_info*> types;
std::coroutine_handle<> cont{};
EventEnvelope* slot{nullptr};
bool* timed_out{nullptr};
bool* cancelled{nullptr};
TimerId timer{0};
[[nodiscard]] bool wants(const std::type_info& t) const
@@ -156,20 +211,52 @@ namespace Void::Fsm::Detail
return false;
}
};
// Several waiters can be parked at once (parallel regions, deferred
// events). An event resumes the first (FIFO) that wants its type.
struct Timer {
Time::MonotonicClock::time_point deadline;
std::function<void()> on_fire;
ScopeId scope{kNoScope};
};
void deliver(EventEnvelope& env);
void run_loop();
void wake() noexcept;
void schedule_external_pump() noexcept;
void fire_due_timers();
[[nodiscard]] std::optional<Time::MonotonicClock::time_point>
next_deadline() const;
const Time::MonotonicClock* m_clock;
FsmLimits m_limits;
Async::Executor* m_external_executor{nullptr};
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::atomic<std::size_t> m_queued_events{0};
std::atomic<std::size_t> m_queued_bytes{0};
Async::MpscQueue<std::function<void()>> m_control_queue;
std::atomic<std::size_t> m_queued_control{0};
std::unordered_map<std::type_index, std::deque<BufferedEvent>>
m_buffers;
std::size_t m_buffered_events{0};
std::size_t m_buffered_bytes{0};
std::vector<Waiter> m_waiters;
WaiterId m_next_waiter{1};
struct Timer {
std::chrono::steady_clock::time_point deadline;
std::function<void()> on_fire;
};
std::map<TimerId, Timer> m_timers;
TimerId m_next_timer{1};
std::atomic<ScopeId> m_next_scope{1};
std::atomic<std::size_t> m_active_child_regions{0};
std::uint64_t m_dispatch_turn{0};
std::size_t m_last_turn_events{0};
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_pump_scheduled{false};
std::atomic<bool> m_done{false};
std::atomic<bool> m_paused{false};
std::atomic<bool> m_worker_started{false};
+1511 -397
View File
File diff suppressed because it is too large. Load diff
+407 -41
View File
@@ -1,27 +1,73 @@
#pragma once
#include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Service/Registry.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <utility>
#include <vector>
namespace Void::Fsm
{
enum class SupervisionMode : std::uint8_t {
StopOnFault = 0,
BoundedRestart
};
struct SupervisionPolicy {
SupervisionMode mode{SupervisionMode::StopOnFault};
std::size_t max_restarts{3};
std::chrono::nanoseconds restart_window{std::chrono::seconds{60}};
std::chrono::nanoseconds initial_backoff{
std::chrono::milliseconds{10}};
};
struct OrchestratorLimits {
std::size_t max_supervised{1024};
};
struct SupervisionEvent {
enum class Kind : std::uint8_t {
Launched = 0,
RestartScheduled,
Restarted,
Released,
Exhausted
};
Kind kind{Kind::Launched};
Status status{Status::Idle};
TerminationReason reason{TerminationReason::none};
std::size_t restarts{0};
std::string detail{};
};
namespace Detail
{
// Type-erased supervised FSM. Models wrap a concrete Machine<R>
// subclass; the orchestrator only needs lifecycle + status.
// subclass; the orchestrator drives lifecycle, status, and bounded
// restart.
class FsmConcept
{
public:
virtual ~FsmConcept() = default;
virtual void stop() = 0;
virtual void restart() = 0;
[[nodiscard]] virtual Status status() const = 0;
[[nodiscard]] virtual TerminationReason
termination_reason() const = 0;
[[nodiscard]] virtual std::optional<FsmError>
system_error() const = 0;
};
template <typename F> class FsmModel final : public FsmConcept
@@ -33,11 +79,29 @@ namespace Void::Fsm
{
}
~FsmModel() override
{
if (m_fsm) {
m_fsm->stop();
}
}
void stop() override { m_fsm->stop(); }
void restart() override { m_fsm->restart(); }
[[nodiscard]] Status status() const override
{
return m_fsm->status();
}
[[nodiscard]] TerminationReason
termination_reason() const override
{
return m_fsm->termination_reason();
}
[[nodiscard]] std::optional<FsmError>
system_error() const override
{
return m_fsm->system_error();
}
[[nodiscard]] F& get() noexcept { return *m_fsm; }
@@ -45,10 +109,27 @@ namespace Void::Fsm
std::unique_ptr<F> m_fsm;
};
struct SupervisedEntry {
std::shared_ptr<FsmConcept> model;
SupervisionPolicy policy{};
std::vector<Time::MonotonicClock::time_point>
restart_timestamps;
std::optional<Time::MonotonicClock::time_point>
next_restart_at;
std::atomic<std::size_t> restarts{0};
mutable std::mutex evidence_mu;
bool released{false};
Status final_status{Status::Idle};
TerminationReason final_reason{TerminationReason::none};
std::optional<FsmError> final_error{};
};
} // namespace Detail
/// A non-owning supervision handle to a launched FSM: query status and
/// stop it. The Orchestrator owns the FSM's lifetime.
/// Owning handle to a supervised FSM instance: holds a shared_ptr so
/// immutable termination evidence and any still-required cleanup ownership
/// survive even after the Orchestrator releases a finished entry from
/// active supervision.
class FsmHandle
{
public:
@@ -57,48 +138,92 @@ namespace Void::Fsm
void stop() const
{
if (m_impl) {
m_impl->stop();
if (m_entry && m_entry->model) {
m_entry->model->stop();
}
}
[[nodiscard]] Status status() const
{
return m_impl ? m_impl->status() : Status::Idle;
if (!m_entry) {
return Status::Idle;
}
std::lock_guard lk{m_entry->evidence_mu};
if (m_entry->released) {
return m_entry->final_status;
}
return m_entry->model ? m_entry->model->status() : Status::Idle;
}
[[nodiscard]] bool finished() const
[[nodiscard]] bool finished() const { return terminal(status()); }
[[nodiscard]] TerminationReason termination_reason() const
{
const auto s = status();
return s == Status::Succeeded || s == Status::Failed;
if (!m_entry) {
return TerminationReason::none;
}
std::lock_guard lk{m_entry->evidence_mu};
if (m_entry->released) {
return m_entry->final_reason;
}
return m_entry->model ? m_entry->model->termination_reason()
: TerminationReason::none;
}
[[nodiscard]] std::optional<FsmError> system_error() const
{
if (!m_entry) {
return std::nullopt;
}
std::lock_guard lk{m_entry->evidence_mu};
if (m_entry->released) {
return m_entry->final_error;
}
return m_entry->model ? m_entry->model->system_error()
: std::nullopt;
}
[[nodiscard]] std::size_t restart_count() const noexcept
{
return m_entry
? m_entry->restarts.load(std::memory_order_acquire)
: 0;
}
[[nodiscard]] explicit operator bool() const noexcept
{
return m_impl != nullptr;
return m_entry != nullptr && m_entry->model != nullptr;
}
private:
friend class Orchestrator;
explicit FsmHandle(std::shared_ptr<Detail::FsmConcept> impl)
: m_impl(std::move(impl))
explicit FsmHandle(std::shared_ptr<Detail::SupervisedEntry> entry)
: m_entry(std::move(entry))
{
}
std::shared_ptr<Detail::FsmConcept> m_impl;
std::shared_ptr<Detail::SupervisedEntry> m_entry;
};
// ── Orchestrator ──────────────────────────────────────────────────────
// Owns a ServiceRegistry and supervises a set of FSM instances. Each
// launched FSM is injected with the registry as its context, so its
// states resolve dependencies by interface (no concrete coupling), and
// is started immediately. stop_all() winds everything down.
class Orchestrator
{
public:
Orchestrator() = default;
using ObserverCallback =
std::function<void(const SupervisionEvent&)>;
explicit Orchestrator(
const Time::MonotonicClock* clock = nullptr,
OrchestratorLimits limits = {}) noexcept
: m_clock(clock != nullptr
? clock
: &Time::SystemMonotonicClock::instance()),
m_limits(limits)
{
}
~Orchestrator() { stop_all(); }
Orchestrator(const Orchestrator&) = delete;
@@ -109,8 +234,6 @@ namespace Void::Fsm
return m_registry;
}
/// Call on_start() on lifecycle services. Call before launching
/// FSMs that expect started services.
void start_services()
{
m_registry.start_all();
@@ -118,36 +241,177 @@ namespace Void::Fsm
m_services_stopped = false;
}
/// Construct F, inject the registry, start it, and supervise.
/// F must derive Fsm::Machine<...> (provides set_services /
/// start / stop / status).
template <typename F, typename... Args>
[[nodiscard]] Void::Result::Result<FsmHandle>
try_launch(SupervisionPolicy policy, Args&&... args)
{
std::vector<ObserverCallback> observers_copy;
std::shared_ptr<Detail::SupervisedEntry> entry;
{
reap_finished_and_notify();
std::lock_guard lock{m_mutex};
if (m_limits.max_supervised > 0 &&
m_entries.size() >= m_limits.max_supervised) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"Orchestrator: max_supervised limit reached"));
}
auto fsm =
std::make_unique<F>(std::forward<Args>(args)...);
fsm->set_services(m_registry);
fsm->start();
auto model =
std::make_shared<Detail::FsmModel<F>>(std::move(fsm));
entry = std::make_shared<Detail::SupervisedEntry>();
entry->model = std::move(model);
entry->policy = policy;
m_entries.push_back(entry);
}
notify_observers(SupervisionEvent{
.kind = SupervisionEvent::Kind::Launched,
.status = entry->model->status(),
.reason = entry->model->termination_reason(),
.restarts = 0,
.detail = {}});
return FsmHandle{std::move(entry)};
}
template <typename F, typename... Args>
FsmHandle launch(Args&&... args)
{
auto fsm = std::make_unique<F>(std::forward<Args>(args)...);
fsm->set_services(m_registry);
fsm->start();
auto model =
std::make_shared<Detail::FsmModel<F>>(std::move(fsm));
std::lock_guard lock{m_mutex};
m_running.push_back(model);
return FsmHandle{model};
auto r = try_launch<F>(SupervisionPolicy{},
std::forward<Args>(args)...);
return r ? *r : FsmHandle{};
}
/// Stop and release every supervised FSM, then stop services.
void stop_all()
/// Drive supervision rules (bounded restarts with injected Time
/// backoff, and releasing terminal entries while handles keep
/// immutable evidence). Returns actions taken (restarts + releases).
std::size_t supervise_step()
{
std::vector<std::shared_ptr<Detail::FsmConcept>> running;
std::vector<SupervisionEvent> events;
std::vector<std::shared_ptr<Detail::SupervisedEntry>>
to_restart;
const auto now = m_clock->now();
{
std::lock_guard lock{m_mutex};
running.swap(m_running);
for (auto it = m_entries.begin(); it != m_entries.end();) {
auto& e = *it;
const auto st = e->model->status();
if (!terminal(st)) {
++it;
continue;
}
if (e->policy.mode == SupervisionMode::BoundedRestart &&
st == Status::Faulted) {
std::erase_if(
e->restart_timestamps, [&](const auto ts) {
return (now - ts) >=
e->policy.restart_window;
});
if (e->restart_timestamps.size() <
e->policy.max_restarts) {
if (!e->next_restart_at.has_value()) {
const std::size_t attempt =
e->restart_timestamps.size();
const auto shift =
attempt < 16 ? attempt : 16;
const auto backoff =
e->policy.initial_backoff *
(std::size_t{1} << shift);
e->next_restart_at = now + backoff;
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::
RestartScheduled,
.status = st,
.reason =
e->model->termination_reason(),
.restarts = e->restarts.load(
std::memory_order_acquire),
.detail = e->model->system_error()
? e->model->system_error()
->message
: std::string{}});
++it;
continue;
}
if (now < *e->next_restart_at) {
++it;
continue;
}
e->restart_timestamps.push_back(now);
e->next_restart_at.reset();
e->restarts.fetch_add(
1, std::memory_order_acq_rel);
to_restart.push_back(e);
++it;
continue;
}
snapshot_released_evidence(*e);
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Exhausted,
.status = e->final_status,
.reason = e->final_reason,
.restarts =
e->restarts.load(std::memory_order_acquire),
.detail =
e->final_error
? e->final_error->message
: std::string{"restart budget exhausted"}});
it = m_entries.erase(it);
continue;
}
snapshot_released_evidence(*e);
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Released,
.status = e->final_status,
.reason = e->final_reason,
.restarts =
e->restarts.load(std::memory_order_acquire),
.detail = e->final_error ? e->final_error->message
: std::string{}});
it = m_entries.erase(it);
}
}
for (auto& m : running) {
m->stop();
for (auto& e : to_restart) {
e->model->restart();
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Restarted,
.status = e->model->status(),
.reason = e->model->termination_reason(),
.restarts = e->restarts.load(std::memory_order_acquire),
.detail = {}});
}
const std::size_t count = events.size();
for (const auto& ev : events) {
notify_observers(ev);
}
return count;
}
/// Release finished stop-on-fault (or non-faulted) entries from
/// active supervision while existing handles retain evidence.
std::size_t reap_finished() { return reap_finished_and_notify(); }
void stop_all()
{
std::vector<std::shared_ptr<Detail::SupervisedEntry>> running;
{
std::lock_guard lock{m_mutex};
running.swap(m_entries);
}
for (auto& e : running) {
e->model->stop();
snapshot_released_evidence(*e);
}
running.clear();
// Balance start_services() exactly once (stop_all may run
// explicitly and again from the destructor).
if (m_services_started && !m_services_stopped) {
m_registry.stop_all();
m_services_stopped = true;
@@ -157,16 +421,118 @@ namespace Void::Fsm
[[nodiscard]] std::size_t running_count() const
{
std::lock_guard lock{m_mutex};
return m_running.size();
return m_entries.size();
}
std::size_t observe_supervision(ObserverCallback cb)
{
std::lock_guard lock{m_obs_mu};
const std::size_t id = m_next_obs_id++;
m_observers.emplace_back(id, std::move(cb));
return id;
}
void remove_supervision_observer(std::size_t id)
{
std::lock_guard lock{m_obs_mu};
std::erase_if(m_observers, [id](const auto& pair) {
return pair.first == id;
});
}
[[nodiscard]] std::vector<std::string> observer_errors() const
{
std::lock_guard lock{m_obs_mu};
return m_observer_errors;
}
private:
static void
snapshot_released_evidence(Detail::SupervisedEntry& entry)
{
std::lock_guard elk{entry.evidence_mu};
if (entry.released) {
return;
}
entry.final_status = entry.model->status();
entry.final_reason = entry.model->termination_reason();
entry.final_error = entry.model->system_error();
entry.released = true;
}
std::size_t reap_finished_and_notify()
{
std::vector<SupervisionEvent> events;
{
std::lock_guard lock{m_mutex};
for (auto it = m_entries.begin(); it != m_entries.end();) {
auto& e = *it;
const auto st = e->model->status();
if (!terminal(st)) {
++it;
continue;
}
if (e->policy.mode == SupervisionMode::BoundedRestart &&
st == Status::Faulted) {
++it;
continue;
}
snapshot_released_evidence(*e);
events.push_back(SupervisionEvent{
.kind = SupervisionEvent::Kind::Released,
.status = e->final_status,
.reason = e->final_reason,
.restarts =
e->restarts.load(std::memory_order_acquire),
.detail = e->final_error ? e->final_error->message
: std::string{}});
it = m_entries.erase(it);
}
}
for (const auto& ev : events) {
notify_observers(ev);
}
return events.size();
}
void notify_observers(const SupervisionEvent& ev)
{
std::vector<ObserverCallback> copy;
{
std::lock_guard lock{m_obs_mu};
copy.reserve(m_observers.size());
for (const auto& [id, fn] : m_observers) {
if (fn) {
copy.push_back(fn);
}
}
}
for (const auto& fn : copy) {
try {
fn(ev);
} catch (const std::exception& ex) {
std::lock_guard lock{m_obs_mu};
m_observer_errors.push_back(ex.what());
} catch (...) {
std::lock_guard lock{m_obs_mu};
m_observer_errors.push_back("observer threw unknown");
}
}
}
const Time::MonotonicClock* m_clock;
OrchestratorLimits m_limits{};
Service::ServiceRegistry m_registry;
mutable std::mutex m_mutex;
std::vector<std::shared_ptr<Detail::FsmConcept>> m_running;
std::vector<std::shared_ptr<Detail::SupervisedEntry>> m_entries;
bool m_services_started{false};
bool m_services_stopped{false};
mutable std::mutex m_obs_mu;
std::vector<std::pair<std::size_t, ObserverCallback>> m_observers;
std::vector<std::string> m_observer_errors;
std::size_t m_next_obs_id{1};
};
} // namespace Void::Fsm
+159
View File
@@ -1,10 +1,22 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Core/Meta.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <any>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <string_view>
#include <type_traits>
#include <typeinfo>
#include <utility>
@@ -33,6 +45,153 @@ namespace Void::Fsm
Faulted // stopped by a system fault (see system_error())
};
/// Canonical shared predicate identifying every terminal Status value.
[[nodiscard]] constexpr bool terminal(Status s) noexcept
{
return s == Status::Succeeded || s == Status::Failed ||
s == Status::Faulted;
}
/// Why a machine finished (preserving Status values while distinguishing
/// cooperative cancellation and deadline expiration from application
/// outcomes and system faults).
enum class TerminationReason : std::uint8_t {
none = 0,
succeeded,
failed,
faulted,
cancelled,
timed_out
};
enum class FsmErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
invalid_state = 2,
not_found = 3,
overloaded = 4,
cancelled = 5,
timeout = 6,
limit_exceeded = 7,
fault = 8,
checkpoint_rejected = 9,
schema_mismatch = 10,
migration_failed = 11,
service_unavailable = 12,
internal = 13
};
[[nodiscard]] inline Void::Result::Error
make_fsm_error(FsmErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case FsmErrorCode::none:
kind = ErrorKind::internal;
break;
case FsmErrorCode::invalid_argument:
kind = ErrorKind::invalid_argument;
break;
case FsmErrorCode::invalid_state:
case FsmErrorCode::checkpoint_rejected:
kind = ErrorKind::conflict;
break;
case FsmErrorCode::not_found:
case FsmErrorCode::service_unavailable:
kind = ErrorKind::not_found;
break;
case FsmErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case FsmErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case FsmErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case FsmErrorCode::limit_exceeded:
kind = ErrorKind::exhausted;
break;
case FsmErrorCode::schema_mismatch:
case FsmErrorCode::migration_failed:
kind = ErrorKind::corrupt;
break;
case FsmErrorCode::fault:
case FsmErrorCode::internal:
kind = ErrorKind::internal;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kFsmErrorDomain,
static_cast<std::int32_t>(code)}};
}
/// Explicit resource and scheduling bounds for FSM execution.
struct FsmLimits {
std::size_t max_mailbox_events{1024};
std::size_t max_mailbox_bytes{std::size_t{4} * 1024 * 1024};
std::size_t max_deferred_events{256};
std::size_t max_timers{1024};
std::size_t max_child_regions{128};
std::size_t max_hierarchy_depth{32};
std::size_t max_retained_transitions{256};
std::size_t max_checkpoint_bytes{std::size_t{4} * 1024 * 1024};
std::size_t max_events_per_turn{64};
std::chrono::nanoseconds max_turn_duration{
std::chrono::milliseconds{1}};
std::size_t max_control_messages{256};
};
/// Explicit borrowed execution binding passed to Machine::run().
struct ExecutionBinding {
Async::Executor* executor{nullptr};
const Time::MonotonicClock* clock{
&Time::SystemMonotonicClock::instance()};
FsmLimits limits{};
};
/// Versioned boundary checkpoint capturing machine identity, schema,
/// durable state ID, optional application safe-point resume label, and
/// serialized application state.
struct Checkpoint {
static constexpr std::uint32_t kFormatVersion = 1;
std::uint32_t format_version{kFormatVersion};
std::string machine_type;
std::uint32_t application_schema{1};
std::uint64_t transition_sequence{0};
std::string state_id;
std::string resume_label;
Json::Value state;
};
/// Annotation tag specifying a durable state ID (`[[= Void::Fsm::StateId{"..."}]]`).
struct StateId {
Void::Meta::Str value;
};
/// Byte-size accounting helper for typed event admission into bounded
/// FSM mailboxes.
template <typename E>
[[nodiscard]] constexpr std::size_t event_payload_bytes(const E& e) noexcept
{
if constexpr (requires {
{
e.payload_bytes()
} -> std::convertible_to<std::size_t>;
}) {
return static_cast<std::size_t>(e.payload_bytes());
} else if constexpr (std::is_same_v<std::remove_cvref_t<E>,
std::string>) {
return sizeof(E) + e.size();
} else {
return sizeof(E);
}
}
/// The outcome of a sub-machine launched via startMachine<Sub, Next>():
/// a typed Success value, a typed Failure value, or a system fault.
struct LaunchResult {
+4
View File
@@ -71,6 +71,10 @@ namespace Void::Result
inline constexpr std::uint32_t kSecurityErrorDomain = 19;
inline constexpr std::uint32_t kUpdateErrorDomain = 20;
inline constexpr std::uint32_t kSqliteErrorDomain = 21;
inline constexpr std::uint32_t kServiceErrorDomain = 22;
inline constexpr std::uint32_t kPluginErrorDomain = 23;
inline constexpr std::uint32_t kConfigurationErrorDomain = 24;
inline constexpr std::uint32_t kFsmErrorDomain = 25;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
+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::atomic<std::shared_ptr<detail::Instance>> current;
bool watched{false};
std::mutex reload_mutex;
};
Entry* find(std::string_view name) const;
std::expected<void, LoadError>
reload_locked(Entry& entry, std::string_view name,
const std::filesystem::path& sourcePath);
std::shared_ptr<Entry> find_shared(std::string_view name) const;
std::expected<void, LoadError> reload_entry_unlocked(
const std::shared_ptr<Entry>& entry, std::string_view name,
const std::optional<std::filesystem::path>& newPath);
std::vector<std::function<void(std::string_view)>>
reload_callbacks_locked() const;
Options m_options;
mutable std::mutex m_mutex; // guards the registry map + reloads
std::unordered_map<std::string, std::unique_ptr<Entry>> m_plugins;
mutable std::mutex m_mutex; // guards the registry map & observer list
std::unordered_map<std::string, std::shared_ptr<Entry>> m_plugins;
std::vector<std::pair<ReloadCallbackId,
std::function<void(std::string_view)>>>
m_on_reloaded;
+60 -27
View File
@@ -26,6 +26,60 @@ namespace Void::Service
inline constexpr const char* kServiceSymbol = "void_plugin_service";
/// Acquire an owning ServiceHandle<I> directly from a PluginManager entry,
/// pinning the exact PluginHandle so the shared object stays mapped until
/// every copy of the returned handle is destroyed.
template <typename I>
[[nodiscard]] Void::Result::Result<ServiceHandle<I>>
acquire_plugin_service(Plugin::PluginManager& manager,
std::string_view plugin_name,
PublicationEpoch epoch = 0)
{
static_assert(std::is_base_of_v<IService, I>,
"plugin service interface must derive IService");
auto handle = manager.acquire(plugin_name);
if (!handle) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::missing_service,
std::string{"ServicePlugin: plugin '"} +
std::string{plugin_name} + "' is not loaded"));
}
auto* factory = reinterpret_cast<service_factory_fn>(
handle.raw_symbol(kServiceSymbol));
if (factory == nullptr) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::missing_service,
std::string{"ServicePlugin: plugin '"} +
std::string{plugin_name} + "' does not export " +
kServiceSymbol));
}
IService* base = nullptr;
try {
base = factory(handle.get());
} catch (const std::exception& ex) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::internal, ex.what()));
} catch (...) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::internal,
"ServicePlugin: service factory threw"));
}
if (base == nullptr) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::missing_service,
"ServicePlugin: service factory returned null"));
}
I* iface = dynamic_cast<I*>(base);
if (iface == nullptr) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::invalid_argument,
"ServicePlugin: incompatible service interface"));
}
auto owner = std::make_shared<Plugin::PluginHandle>(std::move(handle));
std::shared_ptr<void> pinned(std::move(owner), iface);
return ServiceHandle<I>{iface, std::move(pinned), nullptr, epoch};
}
/// Binds a plugin-provided service (interface I) into a ServiceRegistry
/// and keeps it bound across hot reloads: after each reload the new
/// instance's service (carrying state migrated by the plugin's v2 ABI)
@@ -174,35 +228,14 @@ namespace Void::Service
[[nodiscard]] bool bind_locked() noexcept
{
try {
auto handle = m_manager->acquire(m_name);
if (!handle) {
auto svc_handle = acquire_plugin_service<I>(
*m_manager, m_name);
if (!svc_handle) {
Void::Log::warn("Service.Plugin", "{}",
svc_handle.error().message());
return false;
}
auto* factory =
reinterpret_cast<service_factory_fn>(
handle.raw_symbol(kServiceSymbol));
if (factory == nullptr) {
return false;
}
IService* base = factory(handle.get());
if (base == nullptr) {
return false;
}
I* iface = dynamic_cast<I*>(base);
if (iface == nullptr) {
Void::Log::warn(
"Service.Plugin",
"plugin '{}' exported an incompatible "
"service interface",
m_name);
return false;
}
// Pin the exact instance and shared object that
// supplied the factory and service subobject.
auto owner = std::make_shared<Plugin::PluginHandle>(
std::move(handle));
std::shared_ptr<I> pinned(std::move(owner), iface);
auto pinned = svc_handle->shared();
if (m_validator && !m_validator(pinned)) {
Void::Log::warn(
"Service.Plugin",
+394 -109
View File
@@ -1,16 +1,23 @@
#pragma once
#include <Void/Async/Operation.hpp>
#include <Void/Core/Meta.hpp>
#include <Void/Service/Service.hpp>
#include <Void/Service/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Service
@@ -25,92 +32,297 @@ namespace Void::Service
}
#endif
/// Type-keyed service container: providers register an implementation
/// against an interface type, consumers resolve by that interface and
/// never name the concrete type — the core of the dependency-inversion
/// the orchestrator and FSMs rely on.
class ServiceRegistry;
namespace detail
{
struct RetentionEntry {
PublicationEpoch epoch{0};
std::weak_ptr<const void> token{};
std::string label{};
};
struct RetentionState;
struct LifecycleNode {
std::string id{};
const void* object_key{nullptr};
std::shared_ptr<void> owner{};
IService* service{nullptr};
IManagedService* managed{nullptr};
std::size_t seq{0};
std::vector<std::size_t> dep_indices{};
};
struct SnapshotEntry {
std::shared_ptr<void> impl{}; // holds provider (+ optional pin)
IService* service{nullptr};
std::string id{};
};
struct SnapshotData {
PublicationEpoch epoch{0};
std::shared_ptr<const void> gen_token{};
std::unordered_map<std::type_index, SnapshotEntry> services{};
std::vector<std::type_index> legacy_order{};
std::vector<LifecycleNode> lifecycle_nodes{};
std::shared_ptr<const SnapshotData> parent_snap{};
const ServiceRegistry* live_parent{nullptr};
};
} // namespace detail
/// Immutable, self-retaining point-in-time view of a ServiceRegistry
/// (and any snapshot-captured parent chain). Safe to hold after the source
/// registry is modified or destroyed.
class ServiceSnapshot
{
public:
ServiceSnapshot() = default;
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
{
const detail::SnapshotData* cur = m_data.get();
std::size_t depth = 0;
while (cur != nullptr && depth <= m_max_parent_levels) {
const auto it =
cur->services.find(std::type_index{typeid(I)});
if (it != cur->services.end()) {
return std::static_pointer_cast<I>(it->second.impl);
}
cur = cur->parent_snap.get();
++depth;
}
return nullptr;
}
template <typename I> [[nodiscard]] bool has() const
{
return get<I>() != nullptr;
}
[[nodiscard]] PublicationEpoch epoch() const noexcept
{
return m_data ? m_data->epoch : 0;
}
[[nodiscard]] std::size_t size() const noexcept
{
return m_data ? m_data->services.size() : 0;
}
[[nodiscard]] explicit operator bool() const noexcept
{
return m_data != nullptr;
}
private:
friend class ServiceRegistry;
explicit ServiceSnapshot(std::shared_ptr<const detail::SnapshotData> data,
std::size_t max_parent_levels = 16) noexcept
: m_data(std::move(data)),
m_max_parent_levels(max_parent_levels)
{
}
std::shared_ptr<const detail::SnapshotData> m_data{};
std::size_t m_max_parent_levels{16};
};
/// Staged description of a coherent batch of services and their dependency
/// graph, ready to be validated by ServiceRegistry::prepare_batch().
class ProviderSet
{
public:
struct StagedItem {
std::type_index interface_type;
std::string id{};
std::shared_ptr<void> owner{};
const void* object_key{nullptr};
IService* service{nullptr};
IManagedService* managed{nullptr};
std::vector<std::type_index> required_deps{};
std::vector<std::type_index> optional_deps{};
};
template <typename I>
ProviderSet& add(
std::string id,
std::shared_ptr<I> impl,
std::vector<std::type_index> required_deps = {},
std::vector<std::type_index> optional_deps = {},
ServicePin pin = {})
{
StagedItem item{.interface_type = std::type_index{typeid(I)},
.id = std::move(id),
.owner = pack_owner(impl, std::move(pin)),
.object_key = impl.get(),
.service = extract_service(impl.get()),
.managed = extract_managed(impl.get()),
.required_deps = std::move(required_deps),
.optional_deps = std::move(optional_deps)};
m_items.push_back(std::move(item));
return *this;
}
template <typename AliasI>
ProviderSet& add_alias(
std::string id,
std::shared_ptr<AliasI> impl,
std::vector<std::type_index> required_deps = {},
std::vector<std::type_index> optional_deps = {},
ServicePin pin = {})
{
return add<AliasI>(std::move(id), std::move(impl),
std::move(required_deps),
std::move(optional_deps), std::move(pin));
}
[[nodiscard]] const std::vector<StagedItem>& items() const noexcept
{
return m_items;
}
private:
template <typename I>
static std::shared_ptr<void> pack_owner(const std::shared_ptr<I>& impl,
ServicePin pin)
{
if (!impl) {
return nullptr;
}
if (!pin) {
return std::shared_ptr<void>(impl, impl.get());
}
struct PinnedBox {
std::shared_ptr<void> impl;
ServicePin pin;
};
auto box = std::make_shared<PinnedBox>(
PinnedBox{std::shared_ptr<void>(impl, impl.get()),
std::move(pin)});
return std::shared_ptr<void>(std::move(box), impl.get());
}
template <typename I> static IService* extract_service(I* raw)
{
if (raw == nullptr) {
return nullptr;
}
if constexpr (std::is_base_of_v<IService, I>) {
return static_cast<IService*>(raw);
} else if constexpr (std::is_polymorphic_v<I>) {
return dynamic_cast<IService*>(raw);
} else {
return nullptr;
}
}
template <typename I>
static IManagedService* extract_managed(I* raw)
{
if (raw == nullptr) {
return nullptr;
}
if constexpr (std::is_base_of_v<IManagedService, I>) {
return static_cast<IManagedService*>(raw);
} else if constexpr (std::is_polymorphic_v<I>) {
return dynamic_cast<IManagedService*>(raw);
} else {
return nullptr;
}
}
std::vector<StagedItem> m_items{};
};
/// Validated, topologically ordered candidate batch returned by
/// ServiceRegistry::prepare_batch().
struct PreparedPublication {
ExpectedEpoch expected_epoch{};
std::shared_ptr<detail::SnapshotData> snapshot{};
bool valid{false};
bool started{false};
bool aborted{false};
};
/// Thread-safe, snapshot-published service container supporting both
/// legacy single-service mutations (`provide`/`get`/`require`) and
/// transactional DAG lifecycle publication (`acquire`/`prepare_batch`/
/// `start_staged`/`publish`/`close_and_join`).
///
/// registry.provide<IClock>(std::make_shared<SystemClock>());
/// auto& clock = registry.require<IClock>(); // no SystemClock dep
///
/// Thread-safe. Reads (get/require/has) take a shared lock; they are
/// the hot path for running FSMs resolving services per step.
/// Note: `require<I>()` returns an unpinned reference after unlocking and is
/// kept for legacy compatibility; new code and coroutines should use
/// `acquire<I>()` and retain the returned `ServiceHandle<I>` across calls
/// and `co_await` suspension points.
class ServiceRegistry
{
public:
ServiceRegistry() = default;
ServiceRegistry();
explicit ServiceRegistry(const ServiceRegistry* parent);
explicit ServiceRegistry(
ServiceLimits limits,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~ServiceRegistry();
ServiceRegistry(const ServiceRegistry&) = delete;
ServiceRegistry& operator=(const ServiceRegistry&) = delete;
/// Create a scoped child registry that overlays `parent`: lookups
/// fall through to the parent when a key is not provided locally,
/// and a local provide<I>() shadows the parent's entry. Lifecycle
/// (start_all/stop_all) covers only locally-provided services. The
/// parent must outlive this registry.
explicit ServiceRegistry(const ServiceRegistry* parent)
: m_parent{parent}
{
}
/// Construct a child registry retaining an immutable parent
/// snapshot so lookups survive destruction of the parent registry.
[[nodiscard]] static Void::Result::Result<
std::unique_ptr<ServiceRegistry>>
from_parent_snapshot(
ServiceSnapshot parent,
ServiceLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
/// Explicitly refresh snapshot-based parent linkage from `parent`.
void refresh_parent(const ServiceRegistry& parent);
/// Capture an immutable point-in-time snapshot.
[[nodiscard]] ServiceSnapshot snapshot() const;
// ── Legacy compatible API ─────────────────────────────────────
/// Register (or replace) the implementation for interface I.
/// If I derives IService, the instance joins the lifecycle.
template <typename I> void provide(std::shared_ptr<I> impl)
{
Entry entry;
entry.impl = std::shared_ptr<void>(impl, impl.get());
if constexpr (std::is_base_of_v<IService, I>) {
entry.service = static_cast<IService*>(impl.get());
} else if constexpr (std::is_polymorphic_v<I>) {
// The interface I doesn't derive IService, but the
// concrete implementation might — recover the lifecycle
// aspect by cross-cast. (dynamic_cast requires a
// polymorphic I.)
entry.service = dynamic_cast<IService*>(impl.get());
} else {
// A plain, non-polymorphic service type: storable and
// resolvable, but has no IService lifecycle aspect.
entry.service = nullptr;
}
const std::type_index key{typeid(I)};
std::unique_lock lock{m_mutex};
if (!m_services.contains(key)) {
m_order.push_back(key);
}
m_services.insert_or_assign(key, std::move(entry));
}
/// Withdraw the implementation for interface I from this registry
/// (a parent's entry is unaffected: later lookups fall through to
/// it again). Consumers still holding the shared_ptr keep the
/// instance alive; only new lookups miss. Returns true when an
/// entry was removed.
template <typename I> bool remove()
{
const std::type_index key{typeid(I)};
std::unique_lock lock{m_mutex};
if (m_services.erase(key) == 0) {
return false;
}
std::erase(m_order, key);
return true;
}
/// Resolve I, or nullptr if not provided. Falls through to the
/// parent registry (if any) on a local miss.
template <typename I> [[nodiscard]] std::shared_ptr<I> get() const
{
{
std::shared_lock lock{m_mutex};
const auto it = m_services.find(std::type_index{typeid(I)});
if (it != m_services.end()) {
return std::static_pointer_cast<I>(it->second.impl);
IService* svc = nullptr;
if (impl) {
if constexpr (std::is_base_of_v<IService, I>) {
svc = static_cast<IService*>(impl.get());
} else if constexpr (std::is_polymorphic_v<I>) {
svc = dynamic_cast<IService*>(impl.get());
}
}
return m_parent ? m_parent->get<I>() : nullptr;
provide_erased(
std::type_index{typeid(I)},
impl ? std::shared_ptr<void>(impl, impl.get())
: std::shared_ptr<void>{},
impl.get(), svc);
}
template <typename I> bool remove()
{
return remove_erased(std::type_index{typeid(I)});
}
template <typename I>
[[nodiscard]] std::shared_ptr<I> get() const
{
auto h = acquire<I>();
if (!h) {
return nullptr;
}
return h->shared();
}
/// Resolve I; throws std::runtime_error if not provided.
template <typename I> [[nodiscard]] I& require() const
{
auto p = get<I>();
@@ -124,55 +336,128 @@ namespace Void::Service
template <typename I> [[nodiscard]] bool has() const
{
{
std::shared_lock lock{m_mutex};
if (m_services.contains(std::type_index{typeid(I)})) {
return true;
}
}
return m_parent ? m_parent->has<I>() : false;
return acquire<I>().has_value();
}
/// Call on_start() on every lifecycle service, registration
/// Run on_start() outside registry locks in registration/dependency
/// order.
void start_all()
void start_all();
/// Run on_stop() outside registry locks in reverse order.
void stop_all();
[[nodiscard]] std::size_t size() const;
// ── Hardened owning & transactional lifecycle API ───────────────
template <typename I>
[[nodiscard]] Void::Result::Result<ServiceHandle<I>> acquire() const
{
std::shared_lock lock{m_mutex};
for (const auto& key : m_order) {
if (auto* s = m_services.at(key).service) {
s->on_start();
}
auto snap = acquire_snapshot();
if (!snap) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry: registry is stopping"));
}
return acquire_from_snapshot<I>(*snap, 0);
}
/// Call on_stop() on every lifecycle service, reverse order.
void stop_all()
{
std::shared_lock lock{m_mutex};
for (auto it = m_order.rbegin(); it != m_order.rend(); ++it) {
if (auto* s = m_services.at(*it).service) {
s->on_stop();
}
}
}
[[nodiscard]] Void::Result::Result<PreparedPublication>
prepare_batch(ProviderSet set,
ExpectedEpoch expected = std::nullopt);
[[nodiscard]] std::size_t size() const
{
std::shared_lock lock{m_mutex};
return m_services.size();
}
[[nodiscard]] Void::Result::Result<void>
start_staged(PreparedPublication& prepared,
Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<PublicationEpoch>
publish(PreparedPublication&& prepared);
[[nodiscard]] Void::Result::Result<PublicationEpoch>
start_and_publish(ProviderSet set,
ExpectedEpoch expected = std::nullopt,
Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<void>
start(Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<ShutdownReport>
close_and_join(Async::OperationOptions options = {});
[[nodiscard]] PublicationEpoch epoch() const noexcept;
[[nodiscard]] std::size_t retained_generation_count() const;
[[nodiscard]] bool is_stopping() const noexcept;
using ObserverCallback =
std::function<void(const ServiceObservation&)>;
std::size_t add_observer(ObserverCallback cb);
void remove_observer(std::size_t id);
private:
struct Entry {
std::shared_ptr<void> impl;
IService* service = nullptr; // non-null iff I : IService
};
void provide_erased(std::type_index key, std::shared_ptr<void> impl,
const void* object_key, IService* service);
bool remove_erased(std::type_index key);
std::shared_ptr<const detail::SnapshotData> acquire_snapshot() const;
const ServiceRegistry* m_parent = nullptr;
mutable std::shared_mutex m_mutex;
std::unordered_map<std::type_index, Entry> m_services;
std::vector<std::type_index> m_order;
template <typename I>
[[nodiscard]] Void::Result::Result<ServiceHandle<I>>
acquire_from_snapshot(const detail::SnapshotData& snap,
std::size_t depth) const
{
if (depth > m_limits.max_parent_levels) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::overloaded,
"ServiceRegistry: parent depth limit exceeded"));
}
const auto it =
snap.services.find(std::type_index{typeid(I)});
if (it != snap.services.end()) {
auto* raw = static_cast<I*>(it->second.impl.get());
return ServiceHandle<I>{raw, it->second.impl,
snap.gen_token, snap.epoch};
}
if (snap.parent_snap) {
return acquire_from_snapshot<I>(*snap.parent_snap,
depth + 1);
}
if (snap.live_parent != nullptr) {
auto parent_snap = snap.live_parent->acquire_snapshot();
if (!parent_snap) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::service_stopping,
"ServiceRegistry: parent registry is stopping"));
}
return acquire_from_snapshot<I>(*parent_snap, depth + 1);
}
return Void::Result::fail(make_service_error(
ServiceErrorCode::missing_service,
std::string{"ServiceRegistry: no service for '"} +
typeid(I).name() + "'"));
}
[[nodiscard]] Void::Result::Result<void> rollback_started_nodes(
const std::vector<detail::LifecycleNode>& nodes,
std::size_t count, const Void::Result::Error& primary_error);
void notify_observers(const ServiceObservation& obs);
[[nodiscard]] std::size_t prune_and_count_retained_locked();
ServiceLimits m_limits{};
const Void::Time::MonotonicClock* m_clock{
&Void::Time::SystemMonotonicClock::instance()};
std::shared_ptr<detail::RetentionState> m_retention_state;
mutable std::mutex m_write_mu{};
mutable std::mutex m_snapshot_mu{};
std::shared_ptr<const detail::SnapshotData> m_active_snapshot{};
PublicationEpoch m_epoch{0};
bool m_stopping{false};
bool m_started{false};
mutable std::mutex m_observer_mu{};
std::vector<std::pair<std::size_t, ObserverCallback>> m_observers{};
std::size_t m_next_observer_id{1};
};
} // namespace Void::Service
+227
View File
@@ -0,0 +1,227 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Service/Service.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
namespace Void::Service
{
enum class ServiceErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
missing_service = 2,
conflict = 3,
duplicate_interface = 4,
cycle_detected = 5,
missing_dependency = 6,
start_failed = 7,
not_ready = 8,
stop_failed = 9,
service_stopping = 10,
cancelled = 11,
timeout = 12,
overloaded = 13,
retention_limit = 14,
internal = 15,
};
[[nodiscard]] inline Void::Result::Error
make_service_error(ServiceErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case ServiceErrorCode::none:
kind = ErrorKind::internal;
break;
case ServiceErrorCode::invalid_argument:
case ServiceErrorCode::cycle_detected:
kind = ErrorKind::invalid_argument;
break;
case ServiceErrorCode::missing_service:
case ServiceErrorCode::missing_dependency:
kind = ErrorKind::not_found;
break;
case ServiceErrorCode::conflict:
case ServiceErrorCode::duplicate_interface:
case ServiceErrorCode::service_stopping:
kind = ErrorKind::conflict;
break;
case ServiceErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case ServiceErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case ServiceErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case ServiceErrorCode::retention_limit:
kind = ErrorKind::exhausted;
break;
case ServiceErrorCode::start_failed:
case ServiceErrorCode::not_ready:
case ServiceErrorCode::stop_failed:
case ServiceErrorCode::internal:
kind = ErrorKind::internal;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kServiceErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct ServiceLimits {
std::size_t max_providers{256};
std::size_t max_parent_levels{16};
std::size_t max_dependency_edges{1024};
std::size_t max_staged_changes{64};
std::size_t max_lifecycle_requests{128};
std::size_t max_retained_generations{4};
};
using PublicationEpoch = std::uint64_t;
using ExpectedEpoch = std::optional<PublicationEpoch>;
using ServicePin = std::shared_ptr<const void>;
enum class LifecyclePhase : std::uint8_t {
Constructed = 0,
Starting,
Ready,
Stopping,
Stopped,
Failed,
};
enum class ServiceHealthStatus : std::uint8_t {
Unknown = 0,
Healthy,
Degraded,
Unhealthy,
};
struct ServiceHealth {
ServiceHealthStatus status{ServiceHealthStatus::Unknown};
std::string detail{};
};
struct ServiceObservation {
PublicationEpoch epoch{0};
std::size_t provider_count{0};
std::size_t retained_generations{0};
std::uint64_t duration_ns{0};
bool rollback{false};
std::string detail{};
};
struct ShutdownReport {
std::vector<std::string> stopped_services{};
std::vector<std::string> incomplete_owners{};
std::vector<Void::Result::Error> stop_errors{};
[[nodiscard]] bool clean() const noexcept
{
return incomplete_owners.empty() && stop_errors.empty();
}
};
/// Extended lifecycle contract with checked failure/readiness reporting and
/// abort cleanup on partial startup failure.
class IManagedService : public IService
{
public:
[[nodiscard]] virtual Void::Result::Result<void> start_checked()
{
try {
on_start();
return {};
} catch (const std::exception& ex) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::start_failed, ex.what()));
} catch (...) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::start_failed,
"service start threw unknown exception"));
}
}
[[nodiscard]] virtual Void::Result::Result<void>
check_readiness() const
{
return {};
}
virtual void abort_start() noexcept {}
[[nodiscard]] virtual Void::Result::Result<void> stop_checked()
{
try {
on_stop();
return {};
} catch (const std::exception& ex) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::stop_failed, ex.what()));
} catch (...) {
return Void::Result::fail(make_service_error(
ServiceErrorCode::stop_failed,
"service stop threw unknown exception"));
}
}
};
/// Owning lease to a resolved provider record: keeps the provider object,
/// any external code/resource pin, and its publication generation token alive
/// across removal, replacement, parent destruction, and coroutine suspension.
template <typename I> class ServiceHandle
{
public:
ServiceHandle() noexcept = default;
ServiceHandle(I* ptr, std::shared_ptr<void> owner,
std::shared_ptr<const void> gen_token,
PublicationEpoch epoch) noexcept
: m_ptr(ptr), m_owner(std::move(owner)),
m_gen_token(std::move(gen_token)), m_epoch(epoch)
{
}
[[nodiscard]] I* operator->() const noexcept { return m_ptr; }
[[nodiscard]] I& operator*() const noexcept { return *m_ptr; }
[[nodiscard]] I* get() const noexcept { return m_ptr; }
[[nodiscard]] explicit operator bool() const noexcept
{
return m_ptr != nullptr;
}
[[nodiscard]] PublicationEpoch generation() const noexcept
{
return m_epoch;
}
[[nodiscard]] std::shared_ptr<I> shared() const noexcept
{
return std::shared_ptr<I>(m_owner, m_ptr);
}
private:
I* m_ptr{nullptr};
std::shared_ptr<void> m_owner{};
std::shared_ptr<const void> m_gen_token{};
PublicationEpoch m_epoch{0};
};
} // namespace Void::Service
+179
View File
@@ -0,0 +1,179 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Sqlite/Sqlite.hpp>
#include <Void/Sqlite/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
namespace Void::Sqlite
{
struct AsyncPoolOptions {
std::filesystem::path path{};
OpenOptions open_options{};
/// Default 4 reader connections alongside 1 dedicated writer lane.
std::size_t reader_connections{4};
std::size_t max_queued_jobs{1024};
std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL};
int progress_handler_steps{64};
const Void::Time::MonotonicClock* clock{nullptr};
};
struct AsyncPoolStats {
std::size_t reader_connections{0};
std::size_t queued_read_jobs{0};
std::size_t queued_write_jobs{0};
std::size_t active_read_jobs{0};
std::size_t active_write_jobs{0};
std::size_t pending_input_bytes{0};
std::uint64_t completed_jobs{0};
std::uint64_t rejected_jobs{0};
std::uint64_t cancelled_jobs{0};
};
/// Bounded blocking SQLite connection pool (1 writer lane + N reader lanes).
/// Leases one connection exclusively for the entire callback/transaction
/// without ever running SQLite calls on an IO event-loop thread or leaking
/// interrupts across subsequent borrowers.
class AsyncPool
{
public:
~AsyncPool();
AsyncPool(AsyncPool&&) noexcept;
AsyncPool& operator=(AsyncPool&&) noexcept;
AsyncPool(const AsyncPool&) = delete;
AsyncPool& operator=(const AsyncPool&) = delete;
[[nodiscard]] static Result<AsyncPool> open(
AsyncPoolOptions options,
Void::Async::Executor* completion_executor = nullptr);
/// Execute a read-only unit of work on a leased reader connection.
template <typename T>
[[nodiscard]] Void::Coro::Task<Result<T>> run_read(
std::function<Result<T>(Database&)> fn,
Void::Async::OperationOptions op = {},
std::size_t input_bytes = 0)
{
auto box = std::make_shared<std::optional<Result<T>>>();
auto r = co_await submit_erased(
false,
[box, f = std::move(fn)](Database& db) -> Result<void> {
*box = f(db);
return {};
},
std::move(op),
input_bytes);
if (!r) {
co_return Void::Result::fail(std::move(r).error());
}
if (!box->has_value()) {
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::sqlite_error,
"AsyncPool read callback produced no result"));
}
co_return std::move(**box);
}
/// Execute a write unit of work on the serialized writer lane.
template <typename T>
[[nodiscard]] Void::Coro::Task<Result<T>> run_write(
std::function<Result<T>(Database&)> fn,
Void::Async::OperationOptions op = {},
std::size_t input_bytes = 0)
{
auto box = std::make_shared<std::optional<Result<T>>>();
auto r = co_await submit_erased(
true,
[box, f = std::move(fn)](Database& db) -> Result<void> {
*box = f(db);
return {};
},
std::move(op),
input_bytes);
if (!r) {
co_return Void::Result::fail(std::move(r).error());
}
if (!box->has_value()) {
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::sqlite_error,
"AsyncPool write callback produced no result"));
}
co_return std::move(**box);
}
/// Execute a full transaction on the leased writer connection.
/// Commits if `fn` returns ok; rolls back on error. Never releases
/// the writer lease mid-transaction.
template <typename T>
[[nodiscard]] Void::Coro::Task<Result<T>> run_write_transaction(
BeginMode mode,
std::function<Result<T>(Database&, Transaction&)> fn,
Void::Async::OperationOptions op = {},
std::size_t input_bytes = 0)
{
return run_write<T>(
[mode, f = std::move(fn)](Database& db) -> Result<T> {
auto tx = db.begin(mode);
if (!tx) {
return Void::Result::fail(std::move(tx).error());
}
auto res = f(db, *tx);
if (!res) {
(void)tx->rollback_checked();
return res;
}
if (tx->is_active()) {
auto c = tx->commit();
if (!c) {
if (tx->is_active()) {
(void)tx->rollback_checked();
}
return Void::Result::fail(std::move(c).error());
}
}
return res;
},
std::move(op),
input_bytes);
}
[[nodiscard]] Void::Coro::Task<Result<void>> run_read_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op = {},
std::size_t input_bytes = 0);
[[nodiscard]] Void::Coro::Task<Result<void>> run_write_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op = {},
std::size_t input_bytes = 0);
[[nodiscard]] AsyncPoolStats stats() const noexcept;
/// Stop new admission, drain all admitted jobs, join worker threads,
/// and close all pooled SQLite connections.
[[nodiscard]] Result<void> close_and_join();
private:
struct Impl;
explicit AsyncPool(std::shared_ptr<Impl> impl) noexcept;
[[nodiscard]] Void::Coro::Task<Result<void>> submit_erased(
bool is_write,
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes);
std::shared_ptr<Impl> m_impl{};
};
} // namespace Void::Sqlite
+253 -33
View File
@@ -2,36 +2,79 @@
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Sqlite/Types.hpp>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
struct sqlite3;
struct sqlite3_stmt;
// A thin, RAII, Result-based wrapper over the SQLite C API. Generic — no
// application schema baggage. Open a Database, prepare Statements, bind by
// 1-based index, step over result rows, read columns by 0-based index. Schema
// versioning is handled via PRAGMA user_version (migrate()).
// A hardened RAII, Result-based wrapper over the SQLite C API. Generic — no
// application schema baggage. Open a Database (or open_database with explicit
// OpenOptions), prepare Statements, bind by 1-based index or parameter name,
// step over result rows, and read typed columns by 0-based index.
namespace Void::Sqlite
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class OpenMode { ReadOnly, ReadWrite, ReadWriteCreate };
namespace detail
{
struct ConnectionState;
} // namespace detail
class Database;
class Statement;
class Transaction;
class Savepoint;
/// A prepared statement. Move-only; finalizes on destruction.
/// Non-owning view of the current row of a Statement. Expires on the next
/// step(), reset(), reset_checked(), finalize_checked(), or destruction.
/// Must never cross an await or outlive the Statement step that produced it.
class RowView
{
public:
RowView() noexcept = default;
[[nodiscard]] bool is_valid() const noexcept;
[[nodiscard]] int column_count() const noexcept;
[[nodiscard]] Result<ColumnType> column_type(int col) const;
[[nodiscard]] Result<bool> is_null(int col) const;
[[nodiscard]] Result<std::int64_t> get_int(int col) const;
[[nodiscard]] Result<double> get_double(int col) const;
[[nodiscard]] Result<std::string_view> get_text_view(int col) const;
[[nodiscard]] Result<std::string> get_text(int col) const;
[[nodiscard]] Result<std::span<const std::byte>> get_blob_view(int col) const;
[[nodiscard]] Result<std::vector<std::byte>> get_blob(int col) const;
[[nodiscard]] Result<std::optional<std::int64_t>> get_optional_int(int col) const;
[[nodiscard]] Result<std::optional<double>> get_optional_double(int col) const;
[[nodiscard]] Result<std::optional<std::string>> get_optional_text(int col) const;
[[nodiscard]] Result<std::optional<std::vector<std::byte>>> get_optional_blob(int col) const;
[[nodiscard]] Result<OwnedValue> get_value(int col) const;
[[nodiscard]] Result<OwnedRow> copy() const;
private:
friend class Statement;
RowView(const Statement* stmt, std::uint64_t generation) noexcept
: m_stmt(stmt), m_generation(generation)
{
}
const Statement* m_stmt{nullptr};
std::uint64_t m_generation{0};
};
/// A prepared statement. Move-only; retains shared ConnectionState so moving
/// or destroying Database cannot dangle this statement.
class Statement
{
public:
Statement() = default;
~Statement();
Statement(Statement&&) noexcept;
@@ -39,7 +82,7 @@ namespace Void::Sqlite
Statement(const Statement&) = delete;
Statement& operator=(const Statement&) = delete;
// Bind parameters (1-based, matching SQLite). Chainable.
// ── Legacy 1.x chainable bind methods (1-based) ──────────────────
Statement& bind(int index, std::int64_t value);
Statement& bind(int index, int value)
{
@@ -56,48 +99,143 @@ namespace Void::Sqlite
Statement& bind(int index, std::nullptr_t);
Statement& bind(int index, const std::optional<std::string>& value);
/// Error captured by the most recent legacy unchecked bind() call, if any.
[[nodiscard]] const std::optional<Error>& last_bind_error() const noexcept
{
return m_last_bind_error;
}
// ── Checked bind / parameter metadata ────────────────────────────
[[nodiscard]] int bind_parameter_count() const noexcept;
[[nodiscard]] Result<int> bind_parameter_index(std::string_view name) const;
[[nodiscard]] Result<void> bind_checked(int index, ValueView value);
[[nodiscard]] Result<void> bind_checked(std::string_view name, ValueView value);
/// Zero-copy borrowed text/blob binding keeping `owner` alive until
/// reset(), clear_bindings(), rebind, finalize, or destruction.
[[nodiscard]] Result<void> bind_borrowed_text(
int index, std::string_view value, std::shared_ptr<const void> owner);
[[nodiscard]] Result<void> bind_borrowed_blob(
int index, std::span<const std::byte> value, std::shared_ptr<const void> owner);
/// Advance to the next row. Returns true with a row available,
/// false when the statement is done, or an Error on failure.
[[nodiscard]] Result<bool> step();
/// Reset for re-execution (keeps bindings unless clear_bindings).
void reset() noexcept;
void clear_bindings() noexcept;
[[nodiscard]] Result<void> reset_checked();
// Column accessors (0-based), valid after step() yields a row.
void clear_bindings() noexcept;
[[nodiscard]] Result<void> clear_bindings_checked();
/// Explicitly finalize the statement and report any native error.
[[nodiscard]] Result<void> finalize_checked();
[[nodiscard]] bool is_open() const noexcept { return m_stmt != nullptr; }
[[nodiscard]] bool has_row() const noexcept { return m_has_row; }
[[nodiscard]] std::uint64_t row_generation() const noexcept
{
return m_row_generation;
}
// ── Legacy 1.x column accessors (0-based) ────────────────────────
[[nodiscard]] int column_count() const noexcept;
[[nodiscard]] bool is_null(int col) const noexcept;
[[nodiscard]] std::int64_t column_int(int col) const noexcept;
[[nodiscard]] double column_double(int col) const noexcept;
[[nodiscard]] std::string column_text(int col) const;
private:
// ── Strict typed column accessors & row views ────────────────────
[[nodiscard]] Result<RowView> current_row() const;
[[nodiscard]] Result<OwnedRow> copy_row() const;
[[nodiscard]] Result<ColumnType> column_type(int col) const;
[[nodiscard]] Result<std::int64_t> try_column_int(int col) const;
[[nodiscard]] Result<double> try_column_double(int col) const;
[[nodiscard]] Result<std::string_view> try_column_text_view(int col) const;
[[nodiscard]] Result<std::string> try_column_text(int col) const;
[[nodiscard]] Result<std::span<const std::byte>> try_column_blob_view(int col) const;
[[nodiscard]] Result<std::vector<std::byte>> try_column_blob(int col) const;
[[nodiscard]] Result<std::optional<std::int64_t>> try_column_optional_int(int col) const;
[[nodiscard]] Result<std::optional<double>> try_column_optional_double(int col) const;
[[nodiscard]] Result<std::optional<std::string>> try_column_optional_text(int col) const;
[[nodiscard]] Result<std::optional<std::vector<std::byte>>> try_column_optional_blob(int col) const;
[[nodiscard]] Result<OwnedValue> try_column_value(int col) const;
private:
friend class Database;
explicit Statement(sqlite3_stmt* stmt) : m_stmt(stmt) {}
sqlite3_stmt* m_stmt = nullptr;
friend class RowView;
Statement(std::shared_ptr<detail::ConnectionState> conn,
sqlite3_stmt* stmt) noexcept;
void release_handle() noexcept;
[[nodiscard]] Result<void> validate_column_access(int col) const;
std::shared_ptr<detail::ConnectionState> m_conn{};
sqlite3_stmt* m_stmt{nullptr};
bool m_has_row{false};
std::uint64_t m_row_generation{0};
std::vector<std::shared_ptr<const void>> m_borrowed_owners{};
std::optional<Error> m_last_bind_error{};
};
/// RAII transaction. Rolls back on destruction unless commit() was called.
/// RAII transaction retaining shared ConnectionState. Never marks Committed
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error.
class Transaction
{
public:
Transaction() noexcept = default;
~Transaction();
Transaction(Transaction&&) noexcept;
Transaction& operator=(Transaction&&) noexcept;
Transaction(const Transaction&) = delete;
Transaction& operator=(const Transaction&) = delete;
[[nodiscard]] TransactionState state() const noexcept { return m_state; }
[[nodiscard]] bool is_active() const noexcept
{
return m_state == TransactionState::Active;
}
Result<void> commit();
[[nodiscard]] Result<void> rollback_checked();
void rollback() noexcept;
private:
friend class Database;
explicit Transaction(Database* db) : m_db(db) {}
Database* m_db = nullptr;
bool m_done = false;
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept;
std::shared_ptr<detail::ConnectionState> m_conn{};
TransactionState m_state{TransactionState::RolledBack};
};
/// Separately owned nested savepoint scope.
class Savepoint
{
public:
Savepoint() noexcept = default;
~Savepoint();
Savepoint(Savepoint&&) noexcept;
Savepoint& operator=(Savepoint&&) noexcept;
Savepoint(const Savepoint&) = delete;
Savepoint& operator=(const Savepoint&) = delete;
[[nodiscard]] bool is_active() const noexcept { return m_active; }
[[nodiscard]] std::string_view name() const noexcept { return m_name; }
[[nodiscard]] Result<void> release();
[[nodiscard]] Result<void> rollback_to();
[[nodiscard]] Result<void> rollback_and_release();
private:
friend class Database;
Savepoint(std::shared_ptr<detail::ConnectionState> conn,
std::string name) noexcept;
std::shared_ptr<detail::ConnectionState> m_conn{};
std::string m_name{};
bool m_active{false};
};
/// A single forward schema migration applied when the database's
@@ -107,10 +245,18 @@ namespace Void::Sqlite
std::string_view sql; ///< DDL/DML to reach this version
};
using ScalarFunction =
std::function<Result<OwnedValue>(std::span<const ValueView>)>;
using AuthorizerCallback = std::function<AuthorizerDecision(
int action_code,
std::string_view arg1,
std::string_view arg2,
std::string_view db_name,
std::string_view trigger_or_view)>;
class Database
{
public:
Database() = default;
~Database();
Database(Database&&) noexcept;
@@ -119,19 +265,46 @@ namespace Void::Sqlite
Database& operator=(const Database&) = delete;
/// Open (or create) a database file. Use ":memory:" for an
/// in-memory db. Enables WAL + a busy timeout for ReadWrite modes.
/// in-memory db. Enables checked WAL + FULL + foreign_keys for
/// writable file databases.
[[nodiscard]] static Result<Database>
open(const std::filesystem::path& path,
OpenMode mode = OpenMode::ReadWriteCreate);
/// Open with explicit checked options, limits, and diagnostics.
[[nodiscard]] static Result<Database>
open_with_options(const std::filesystem::path& path,
OpenOptions options);
/// Execute one or more semicolon-separated statements (no results).
Result<void> exec(std::string_view sql);
/// Prepare a single statement for binding/stepping.
/// Prepare a single statement for binding/stepping. Rejects
/// non-whitespace trailing SQL and enforces statement/SQL limits.
[[nodiscard]] Result<Statement> prepare(std::string_view sql);
/// Begin a transaction (BEGIN; commit/rollback via the handle).
[[nodiscard]] Result<Transaction> begin();
/// Begin a transaction. Rejects nested begin() while a transaction
/// is already active (use savepoint() for nesting).
[[nodiscard]] Result<Transaction> begin(BeginMode mode = BeginMode::Deferred);
/// Create a named nested savepoint (ASCII identifier only).
[[nodiscard]] Result<Savepoint> savepoint(std::string_view name);
/// Stream all rows from a prepared statement with row & byte caps.
[[nodiscard]] Result<std::vector<OwnedRow>> query_all(
Statement& stmt,
std::size_t max_rows = 0,
std::size_t max_bytes = 0);
/// Explicitly close the connection. Stops admission and returns
/// SqliteErrorCode::busy while live statements/transactions/savepoints
/// remain open.
[[nodiscard]] Result<void> close();
[[nodiscard]] bool is_open() const noexcept;
[[nodiscard]] EffectiveCapabilities capabilities() const;
[[nodiscard]] ConnectionHealth health() const;
[[nodiscard]] const SqliteLimits& limits() const noexcept;
[[nodiscard]] std::int64_t last_insert_rowid() const noexcept;
[[nodiscard]] int changes() const noexcept;
@@ -139,16 +312,63 @@ namespace Void::Sqlite
/// Current schema version (PRAGMA user_version).
[[nodiscard]] Result<int> user_version();
/// Apply, in order, any migrations whose version exceeds the
/// current user_version, each inside a transaction, then bump
/// user_version. Idempotent and safe to call on every startup.
/// Validate strictly increasing unique versions before mutation,
/// reject unexpected newer schemas, and apply pending migrations.
Result<void> migrate(std::span<const Migration> migrations);
[[nodiscard]] sqlite3* handle() const noexcept { return m_db; }
/// Validate migrations, record immutable id & checksum in
/// `_void_schema_migrations` in the same transaction as user_version,
/// and reject checksum drift or unexpected newer schemas.
[[nodiscard]] Result<void>
migrate_checked(std::span<const CheckedMigration> migrations);
/// Run a WAL checkpoint and report completed/remaining frames and busy state.
[[nodiscard]] Result<CheckpointReport>
checkpoint(CheckpointMode mode = CheckpointMode::Passive);
/// Copy this database consistently to `destination` via SQLite's backup API.
[[nodiscard]] Result<BackupReport>
backup_to(const std::filesystem::path& destination,
BackupOptions options = {});
/// Restore this database consistently from `source` via SQLite's backup API.
[[nodiscard]] Result<BackupReport>
restore_from(const std::filesystem::path& source,
BackupOptions options = {});
/// Register an exception-safe custom scalar SQL function owned by
/// this connection's ConnectionState.
[[nodiscard]] Result<void> create_scalar_function(
std::string name,
int num_args,
ScalarFunction fn,
bool deterministic = true);
/// Register (or clear when empty) an exception-safe SQLite authorizer.
[[nodiscard]] Result<void> set_authorizer(AuthorizerCallback cb);
/// Expert native handle borrow under caller's execution lease.
[[nodiscard]] sqlite3* handle() const noexcept;
/// Operation-scoped interrupt/progress hooks for leased async execution
/// (serialized with end_operation so interrupts never leak across queries).
void begin_leased_operation(std::uint64_t generation,
int progress_steps,
std::function<bool()> should_interrupt);
void interrupt_leased_operation(std::uint64_t generation) noexcept;
void end_leased_operation(std::uint64_t generation) noexcept;
private:
sqlite3* m_db = nullptr;
explicit Database(std::shared_ptr<detail::ConnectionState> conn) noexcept;
std::shared_ptr<detail::ConnectionState> m_conn{};
};
/// Free-function helper matching roadmap `open_database(path, OpenOptions)`.
[[nodiscard]] inline Result<Database> open_database(
const std::filesystem::path& path,
OpenOptions options = {})
{
return Database::open_with_options(path, std::move(options));
}
} // namespace Void::Sqlite
+405
View File
@@ -0,0 +1,405 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
namespace Void::Sqlite
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class OpenMode : std::uint8_t {
ReadOnly,
ReadWrite,
ReadWriteCreate
};
enum class JournalMode : std::uint8_t {
Wal,
Rollback
};
enum class SyncMode : std::uint8_t {
Full,
Normal
};
enum class BeginMode : std::uint8_t {
Deferred,
Immediate,
Exclusive
};
enum class CheckpointMode : std::uint8_t {
Passive,
Full,
Restart,
Truncate
};
enum class TransactionState : std::uint8_t {
Active,
Committed,
RolledBack,
RecoveryRequired
};
enum class ColumnType : std::uint8_t {
Null = 0,
Integer = 1,
Real = 2,
Text = 3,
Blob = 4
};
enum class SqliteErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
busy = 2,
locked = 3,
constraint = 4,
corrupt = 5,
io = 6,
readonly = 7,
full = 8,
misuse = 9,
not_found = 10,
range = 11,
type_mismatch = 12,
trailing_sql = 13,
statement_limit = 14,
size_limit = 15,
unsupported_pragma = 16,
recovery_required = 17,
closed = 18,
cancelled = 19,
timeout = 20,
overloaded = 21,
migration_error = 22,
backup_error = 23,
sqlite_error = 24
};
[[nodiscard]] inline Error make_sqlite_error(
SqliteErrorCode code,
std::string message,
int primary_code = 0,
int extended_code = 0)
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case SqliteErrorCode::none:
case SqliteErrorCode::sqlite_error:
kind = ErrorKind::internal;
break;
case SqliteErrorCode::invalid_argument:
case SqliteErrorCode::misuse:
case SqliteErrorCode::range:
case SqliteErrorCode::type_mismatch:
case SqliteErrorCode::trailing_sql:
kind = ErrorKind::invalid_argument;
break;
case SqliteErrorCode::busy:
case SqliteErrorCode::locked:
case SqliteErrorCode::constraint:
case SqliteErrorCode::recovery_required:
case SqliteErrorCode::migration_error:
kind = ErrorKind::conflict;
break;
case SqliteErrorCode::corrupt:
kind = ErrorKind::corrupt;
break;
case SqliteErrorCode::io:
case SqliteErrorCode::readonly:
case SqliteErrorCode::backup_error:
kind = ErrorKind::io;
break;
case SqliteErrorCode::full:
case SqliteErrorCode::statement_limit:
case SqliteErrorCode::size_limit:
kind = ErrorKind::exhausted;
break;
case SqliteErrorCode::not_found:
kind = ErrorKind::not_found;
break;
case SqliteErrorCode::unsupported_pragma:
kind = ErrorKind::unsupported;
break;
case SqliteErrorCode::closed:
case SqliteErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case SqliteErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case SqliteErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
}
if (primary_code != 0 || extended_code != 0) {
message += " (sqlite rc=";
message += std::to_string(primary_code);
if (extended_code != 0 && extended_code != primary_code) {
message += ", extended=";
message += std::to_string(extended_code);
}
message += ")";
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kSqliteErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct SqliteLimits {
std::size_t max_live_statements{128};
std::size_t max_sql_bytes{1024ULL * 1024ULL};
std::size_t max_value_bytes{16ULL * 1024ULL * 1024ULL};
std::size_t max_query_all_rows{10000};
std::size_t max_query_all_bytes{16ULL * 1024ULL * 1024ULL};
std::size_t max_cached_statements{64};
std::size_t max_cache_bytes{8ULL * 1024ULL * 1024ULL};
std::chrono::milliseconds busy_timeout{5000};
std::uint64_t wal_checkpoint_threshold_bytes{16ULL * 1024ULL * 1024ULL};
std::uint64_t wal_warn_threshold_bytes{64ULL * 1024ULL * 1024ULL};
std::uint64_t wal_stop_writes_threshold_bytes{256ULL * 1024ULL * 1024ULL};
std::size_t max_queued_jobs{1024};
std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL};
};
[[nodiscard]] inline Result<void> validate_limits(const SqliteLimits& limits)
{
if (limits.max_live_statements == 0 ||
limits.max_sql_bytes == 0 ||
limits.max_value_bytes == 0 ||
limits.max_query_all_rows == 0 ||
limits.max_query_all_bytes == 0 ||
limits.max_cached_statements == 0 ||
limits.max_cache_bytes == 0 ||
limits.busy_timeout.count() < 0 ||
limits.wal_checkpoint_threshold_bytes == 0 ||
limits.wal_warn_threshold_bytes == 0 ||
limits.wal_stop_writes_threshold_bytes == 0 ||
limits.max_queued_jobs == 0 ||
limits.max_pending_input_bytes == 0) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"SqliteLimits must specify positive finite bounds"));
}
if (limits.wal_checkpoint_threshold_bytes > limits.wal_warn_threshold_bytes ||
limits.wal_warn_threshold_bytes > limits.wal_stop_writes_threshold_bytes) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"SqliteLimits WAL thresholds must be non-decreasing"));
}
return {};
}
struct OpenOptions {
OpenMode mode{OpenMode::ReadWriteCreate};
JournalMode journal_mode{JournalMode::Wal};
SyncMode sync_mode{SyncMode::Full};
bool foreign_keys{true};
bool allow_extension_loading{false};
SqliteLimits limits{};
std::function<void(std::string_view)> diagnostic_hook{};
};
struct EffectiveCapabilities {
std::string sqlite_version{};
int sqlite_version_number{0};
int threadsafe_mode{0};
bool in_memory{false};
bool read_only{false};
std::string journal_mode{};
int synchronous_mode{0};
bool foreign_keys{false};
bool extension_loading_enabled{false};
};
struct ValueView {
using Storage = std::variant<
std::nullptr_t,
std::int64_t,
double,
std::string_view,
std::span<const std::byte>>;
Storage value{nullptr};
constexpr ValueView() noexcept = default;
constexpr ValueView(std::nullptr_t) noexcept : value(nullptr) {}
constexpr ValueView(std::int64_t v) noexcept : value(v) {}
constexpr ValueView(int v) noexcept : value(static_cast<std::int64_t>(v)) {}
constexpr ValueView(double v) noexcept : value(v) {}
constexpr ValueView(std::string_view v) noexcept : value(v) {}
ValueView(const std::string& v) noexcept : value(std::string_view{v}) {}
constexpr ValueView(const char* v) noexcept
: value(v ? Storage{std::string_view{v}} : Storage{nullptr}) {}
constexpr ValueView(std::span<const std::byte> v) noexcept : value(v) {}
[[nodiscard]] constexpr ColumnType type() const noexcept
{
switch (value.index()) {
case 0: return ColumnType::Null;
case 1: return ColumnType::Integer;
case 2: return ColumnType::Real;
case 3: return ColumnType::Text;
case 4: return ColumnType::Blob;
default: return ColumnType::Null;
}
}
[[nodiscard]] constexpr bool is_null() const noexcept
{
return std::holds_alternative<std::nullptr_t>(value);
}
};
struct OwnedValue {
using Storage = std::variant<
std::nullptr_t,
std::int64_t,
double,
std::string,
std::vector<std::byte>>;
Storage value{nullptr};
OwnedValue() noexcept = default;
OwnedValue(std::nullptr_t) noexcept : value(nullptr) {}
OwnedValue(std::int64_t v) noexcept : value(v) {}
OwnedValue(double v) noexcept : value(v) {}
OwnedValue(std::string v) noexcept : value(std::move(v)) {}
OwnedValue(std::vector<std::byte> v) noexcept : value(std::move(v)) {}
[[nodiscard]] ColumnType type() const noexcept
{
switch (value.index()) {
case 0: return ColumnType::Null;
case 1: return ColumnType::Integer;
case 2: return ColumnType::Real;
case 3: return ColumnType::Text;
case 4: return ColumnType::Blob;
default: return ColumnType::Null;
}
}
[[nodiscard]] bool is_null() const noexcept
{
return std::holds_alternative<std::nullptr_t>(value);
}
[[nodiscard]] ValueView as_view() const noexcept
{
if (const auto* i = std::get_if<std::int64_t>(&value)) return ValueView{*i};
if (const auto* d = std::get_if<double>(&value)) return ValueView{*d};
if (const auto* s = std::get_if<std::string>(&value)) return ValueView{std::string_view{*s}};
if (const auto* b = std::get_if<std::vector<std::byte>>(&value)) {
return ValueView{std::span<const std::byte>{b->data(), b->size()}};
}
return ValueView{nullptr};
}
[[nodiscard]] bool operator==(const OwnedValue&) const = default;
};
struct OwnedRow {
std::vector<OwnedValue> columns{};
[[nodiscard]] std::size_t size() const noexcept { return columns.size(); }
[[nodiscard]] bool empty() const noexcept { return columns.empty(); }
[[nodiscard]] const OwnedValue& operator[](std::size_t idx) const noexcept
{
return columns[idx];
}
};
struct CheckpointReport {
int log_frames{0};
int checkpointed_frames{0};
bool busy{false};
std::uint64_t wal_size_bytes{0};
};
struct BackupOptions {
int pages_per_step{64};
int max_steps{1000000};
std::chrono::milliseconds step_sleep{0};
};
struct BackupReport {
int total_pages{0};
int remaining_pages{0};
int steps{0};
};
/// Immutable schema migration with explicit identity & checksum verification.
struct CheckedMigration {
int version{0};
std::string_view id{};
std::string_view checksum{};
std::string_view sql{};
};
struct ConnectionHealth {
std::size_t live_statements{0};
bool active_transaction{false};
std::size_t open_savepoints{0};
std::uint64_t wal_size_bytes{0};
bool wal_checkpoint_recommended{false};
bool wal_warn_exceeded{false};
bool wal_write_admission_blocked{false};
};
enum class AuthorizerDecision : std::uint8_t {
Allow,
Deny,
Ignore
};
struct FaultConfig {
/// If non-zero, next COMMIT returns this SQLite error code without
/// calling SQLite COMMIT (leaving transaction active so autocommit==0).
int fail_next_commit_rc{0};
/// If true along with fail_next_commit_rc, simulates SQLite
/// auto-rollback before returning the error.
bool auto_rollback_on_faulted_commit{false};
/// If non-zero, next explicit close() returns this SQLite error code.
int fail_next_close_rc{0};
};
/// Process-local RAII guard for deterministic fault injection in tests.
class ScopedFaultGuard
{
public:
explicit ScopedFaultGuard(FaultConfig cfg) noexcept;
~ScopedFaultGuard();
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
[[nodiscard]] static FaultConfig current() noexcept;
private:
FaultConfig prev_{};
};
} // namespace Void::Sqlite
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Storage/Engine.hpp>
#include <Void/Storage/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
namespace Void::Storage
{
struct AsyncAdapterOptions {
std::size_t max_pending_batches{64};
std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL};
const Void::Time::MonotonicClock* clock{nullptr};
};
struct AsyncAdapterStats {
std::size_t queued_writes{0};
std::size_t pending_bytes{0};
std::uint64_t completed_writes{0};
std::uint64_t rejected_writes{0};
std::uint64_t unknown_outcomes{0};
std::uint64_t cancelled_before_append{0};
};
/// Bounded blocking async adapter over Storage::Engine following C-03
/// domain-result classification (never steals a persisted commit outcome with
/// a synthetic timeout/cancel once WAL append begins; single delivery only).
class AsyncStorageAdapter
{
public:
explicit AsyncStorageAdapter(
Engine& engine,
AsyncAdapterOptions options = {},
Void::Async::Executor* completion_executor = nullptr);
~AsyncStorageAdapter();
AsyncStorageAdapter(const AsyncStorageAdapter&) = delete;
AsyncStorageAdapter& operator=(const AsyncStorageAdapter&) = delete;
AsyncStorageAdapter(AsyncStorageAdapter&&) = delete;
AsyncStorageAdapter& operator=(AsyncStorageAdapter&&) = delete;
[[nodiscard]] Void::Coro::Task<std::expected<CommitReceipt, WriteFailure>>
write_async(
Batch batch,
Durability durability,
Void::Async::OperationOptions op = {});
[[nodiscard]] Void::Coro::Task<Result<OwnedValue>>
get_async(
ByteView key,
Void::Async::OperationOptions op = {});
[[nodiscard]] Void::Coro::Task<Result<void>>
checkpoint_async(Void::Async::OperationOptions op = {});
[[nodiscard]] AsyncAdapterStats stats() const noexcept;
void close_and_join();
private:
struct Impl;
std::shared_ptr<Impl> m_impl{};
};
} // namespace Void::Storage
+93
View File
@@ -0,0 +1,93 @@
#pragma once
#include <Void/Storage/Types.hpp>
#include <cstdint>
#include <optional>
#include <string_view>
#include <vector>
namespace Void::Storage
{
enum class MutationKind : std::uint8_t {
Put = 1,
Erase = 2
};
enum class PreconditionKind : std::uint8_t {
Absent = 1,
VersionEquals = 2,
ValueEquals = 3
};
struct Mutation {
MutationKind kind{MutationKind::Put};
OwnedBytes key{};
OwnedBytes value{};
};
struct Precondition {
PreconditionKind kind{PreconditionKind::Absent};
OwnedBytes key{};
Sequence expected_version{0};
OwnedBytes expected_value{};
};
/// Atomic conditional write batch owning all key and value bytes.
/// Rejects duplicate mutation keys and duplicate preconditions per key.
class Batch
{
public:
Batch() = default;
Batch& put(ByteView key, ByteView value);
Batch& put(std::string_view key, std::string_view value)
{
return put(to_byte_view(key), to_byte_view(value));
}
Batch& erase(ByteView key);
Batch& erase(std::string_view key)
{
return erase(to_byte_view(key));
}
Batch& require_absent(ByteView key);
Batch& require_absent(std::string_view key)
{
return require_absent(to_byte_view(key));
}
Batch& require_version(ByteView key, Sequence expected_version);
Batch& require_version(std::string_view key, Sequence expected_version)
{
return require_version(to_byte_view(key), expected_version);
}
Batch& require_value(ByteView key, ByteView expected_value);
Batch& require_value(std::string_view key, std::string_view expected_value)
{
return require_value(to_byte_view(key), to_byte_view(expected_value));
}
[[nodiscard]] const std::vector<Mutation>& mutations() const noexcept
{
return m_mutations;
}
[[nodiscard]] const std::vector<Precondition>& preconditions() const noexcept
{
return m_preconditions;
}
[[nodiscard]] bool empty() const noexcept
{
return m_mutations.empty() && m_preconditions.empty();
}
[[nodiscard]] Result<void> validate(const Limits& limits) const;
private:
std::vector<Mutation> m_mutations{};
std::vector<Precondition> m_preconditions{};
};
} // namespace Void::Storage
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string_view>
namespace Void::Storage
{
namespace detail
{
[[nodiscard]] constexpr std::array<std::uint32_t, 256>
make_crc32c_table() noexcept
{
// Reflected Castagnoli polynomial (normal 0x1EDC6F41, reflected 0x82F63B78).
constexpr std::uint32_t kPoly = 0x82F63B78u;
std::array<std::uint32_t, 256> table{};
for (std::uint32_t i = 0; i < 256; ++i) {
std::uint32_t c = i;
for (int k = 0; k < 8; ++k) {
c = (c & 1u) ? (kPoly ^ (c >> 1)) : (c >> 1);
}
table[i] = c;
}
return table;
}
inline constexpr auto kCrc32cTable = make_crc32c_table();
} // namespace detail
inline constexpr std::uint32_t kCrc32cInitial = 0xFFFFFFFFu;
[[nodiscard]] constexpr std::uint32_t crc32c_init() noexcept
{
return kCrc32cInitial;
}
[[nodiscard]] constexpr std::uint32_t crc32c_update(
std::uint32_t state,
std::span<const std::byte> data) noexcept
{
for (const auto b : data) {
const auto idx =
(state ^ static_cast<std::uint32_t>(std::to_integer<unsigned char>(b))) &
0xFFu;
state = detail::kCrc32cTable[idx] ^ (state >> 8);
}
return state;
}
[[nodiscard]] constexpr std::uint32_t crc32c_update(
std::uint32_t state,
std::string_view text) noexcept
{
for (const unsigned char c : text) {
state = detail::kCrc32cTable[(state ^ c) & 0xFFu] ^ (state >> 8);
}
return state;
}
[[nodiscard]] constexpr std::uint32_t crc32c_finalize(std::uint32_t state) noexcept
{
return state ^ 0xFFFFFFFFu;
}
[[nodiscard]] constexpr std::uint32_t crc32c(
std::span<const std::byte> data) noexcept
{
return crc32c_finalize(crc32c_update(crc32c_init(), data));
}
[[nodiscard]] constexpr std::uint32_t crc32c(std::string_view text) noexcept
{
return crc32c_finalize(crc32c_update(crc32c_init(), text));
}
static_assert(crc32c(std::string_view{"123456789"}) == 0xE3069283u,
"CRC32C golden vector mismatch");
static_assert(crc32c(std::string_view{""}) == 0u,
"CRC32C empty vector mismatch");
} // namespace Void::Storage
+147
View File
@@ -0,0 +1,147 @@
#pragma once
#include <Void/Storage/Batch.hpp>
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Types.hpp>
#include <expected>
#include <filesystem>
#include <memory>
namespace Void::Storage
{
namespace detail
{
class EngineControl;
struct SourceView;
} // namespace detail
class Engine;
class Cursor;
/// Move-only reader pin of a committed sequence and immutable source set.
class Snapshot
{
public:
Snapshot() noexcept = default;
~Snapshot();
Snapshot(Snapshot&&) noexcept;
Snapshot& operator=(Snapshot&&) noexcept;
Snapshot(const Snapshot&) = delete;
Snapshot& operator=(const Snapshot&) = delete;
[[nodiscard]] Sequence sequence() const noexcept { return m_sequence; }
[[nodiscard]] bool valid() const noexcept { return static_cast<bool>(m_control); }
void reset() noexcept;
private:
friend class Engine;
friend class Cursor;
friend class detail::EngineControl;
Snapshot(std::shared_ptr<detail::EngineControl> control,
std::shared_ptr<const detail::SourceView> view,
Sequence seq,
std::uint64_t pin_id) noexcept;
std::shared_ptr<detail::EngineControl> m_control{};
std::shared_ptr<const detail::SourceView> m_view{};
Sequence m_sequence{0};
std::uint64_t m_pin_id{0};
};
/// Move-only ordered byte-lexicographic iterator retaining its Snapshot.
class Cursor
{
public:
Cursor() noexcept = default;
~Cursor();
Cursor(Cursor&&) noexcept;
Cursor& operator=(Cursor&&) noexcept;
Cursor(const Cursor&) = delete;
Cursor& operator=(const Cursor&) = delete;
[[nodiscard]] Result<ScanPage> next_page();
[[nodiscard]] bool valid() const noexcept { return !m_closed && m_snapshot.valid(); }
void close() noexcept;
private:
friend class Engine;
Cursor(Snapshot snap,
ScanBounds bounds,
std::size_t page_bytes,
std::size_t page_rows,
std::uint64_t cursor_id) noexcept;
Snapshot m_snapshot{};
ScanBounds m_bounds{};
std::size_t m_page_bytes{0};
std::size_t m_page_rows{0};
std::uint64_t m_cursor_id{0};
std::optional<OwnedBytes> m_resume_after{};
bool m_finished{false};
bool m_closed{false};
};
class Engine
{
public:
Engine() noexcept = default;
~Engine();
Engine(Engine&&) noexcept;
Engine& operator=(Engine&&) noexcept;
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
[[nodiscard]] static Result<Engine> open(OpenOptions options);
[[nodiscard]] Result<Snapshot> snapshot();
[[nodiscard]] std::expected<CommitReceipt, WriteFailure> write(
Batch batch,
Durability durability);
[[nodiscard]] std::expected<CommitReceipt, WriteFailure> write(Batch batch)
{
return write(std::move(batch), default_durability());
}
[[nodiscard]] Result<OwnedValue> get(
const Snapshot& snap,
ByteView key) const;
[[nodiscard]] Result<OwnedValue> get(
const Snapshot& snap,
std::string_view key) const
{
return get(snap, to_byte_view(key));
}
[[nodiscard]] Result<Cursor> scan(
Snapshot snap,
ScanBounds bounds = ScanBounds::all()) const;
[[nodiscard]] Result<void> checkpoint();
[[nodiscard]] Result<void> compact();
[[nodiscard]] Result<void> sync();
[[nodiscard]] Result<void> close();
/// Copy consistent manifest, tables, and necessary WAL prefix into
/// `destination` while keeping this engine open and pinning sources.
[[nodiscard]] Result<void> export_backup(
const std::filesystem::path& destination);
[[nodiscard]] EngineState state() const noexcept;
[[nodiscard]] EngineStats stats() const noexcept;
[[nodiscard]] Durability default_durability() const noexcept;
[[nodiscard]] const Limits& limits() const noexcept;
private:
friend class AsyncStorageAdapter;
explicit Engine(std::shared_ptr<detail::EngineControl> control) noexcept;
std::shared_ptr<detail::EngineControl> m_control{};
};
} // namespace Void::Storage
+145
View File
@@ -0,0 +1,145 @@
#pragma once
#include <Void/Storage/Types.hpp>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <vector>
namespace Void::Storage
{
enum class FileOpenMode : std::uint8_t {
ReadOnly = 0,
ReadWriteExisting = 1,
CreateNew = 2,
CreateOrOpen = 3
};
class FileHandle
{
public:
virtual ~FileHandle() = default;
[[nodiscard]] virtual Result<std::size_t> pread(
std::uint64_t offset, std::span<std::byte> out) = 0;
[[nodiscard]] virtual Result<void> pread_exact(
std::uint64_t offset, std::span<std::byte> out) = 0;
[[nodiscard]] virtual Result<void> pwrite_all(
std::uint64_t offset, ByteView data) = 0;
[[nodiscard]] virtual Result<std::uint64_t> append_all(ByteView data) = 0;
[[nodiscard]] virtual Result<void> sync() = 0;
[[nodiscard]] virtual Result<void> truncate(std::uint64_t new_size) = 0;
[[nodiscard]] virtual Result<std::uint64_t> size() const = 0;
[[nodiscard]] virtual Result<void> close() = 0;
};
class DirLockHandle
{
public:
virtual ~DirLockHandle() = default;
};
class FilePort
{
public:
virtual ~FilePort() = default;
[[nodiscard]] virtual Result<void> ensure_dir(
const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<bool> exists(
const std::filesystem::path& p) = 0;
[[nodiscard]] virtual Result<std::uint64_t> file_size(
const std::filesystem::path& p) = 0;
[[nodiscard]] virtual Result<std::vector<std::string>> list_dir(
const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<std::unique_ptr<DirLockHandle>>
lock_directory(const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<std::unique_ptr<FileHandle>> open_file(
const std::filesystem::path& p, FileOpenMode mode) = 0;
[[nodiscard]] virtual Result<void> rename_atomic(
const std::filesystem::path& from,
const std::filesystem::path& to) = 0;
[[nodiscard]] virtual Result<void> unlink_file(
const std::filesystem::path& p) = 0;
[[nodiscard]] virtual Result<void> sync_dir(
const std::filesystem::path& dir) = 0;
[[nodiscard]] virtual Result<void> probe_durability_capabilities(
const std::filesystem::path& dir) = 0;
};
[[nodiscard]] std::shared_ptr<FilePort> make_posix_file_port();
enum class FaultOp : std::uint8_t {
LockDir = 0,
ProbeDurability = 1,
OpenFile = 2,
AppendWrite = 3,
PWrite = 4,
SyncFile = 5,
SyncDir = 6,
Rename = 7,
Unlink = 8,
Truncate = 9
};
struct FaultRule {
FaultOp op{FaultOp::SyncFile};
std::string path_contains{};
/// 1-based hit index among matching operations (0 = fail every match).
std::uint64_t hit_index{1};
StorageErrorCode error_code{StorageErrorCode::io_error};
/// For write ops: write at most this many bytes before failing (SIZE_MAX = skip write).
std::optional<std::size_t> partial_write_bytes{};
bool consumed{false};
std::uint64_t match_count{0};
};
/// Deterministic filesystem fault-injection proxy wrapping a FilePort
/// (default: PosixFilePort) for crash, partial-write, and sync-failure tests.
class FaultInjectingFilePort final : public FilePort
{
public:
explicit FaultInjectingFilePort(
std::shared_ptr<FilePort> delegate = make_posix_file_port());
void add_rule(FaultRule rule);
void clear_rules();
void set_pause_before_sync(std::function<void()> hook);
[[nodiscard]] std::uint64_t op_count(FaultOp op) const noexcept;
[[nodiscard]] Result<void> ensure_dir(const std::filesystem::path& dir) override;
[[nodiscard]] Result<bool> exists(const std::filesystem::path& p) override;
[[nodiscard]] Result<std::uint64_t> file_size(const std::filesystem::path& p) override;
[[nodiscard]] Result<std::vector<std::string>> list_dir(const std::filesystem::path& dir) override;
[[nodiscard]] Result<std::unique_ptr<DirLockHandle>> lock_directory(const std::filesystem::path& dir) override;
[[nodiscard]] Result<std::unique_ptr<FileHandle>> open_file(const std::filesystem::path& p, FileOpenMode mode) override;
[[nodiscard]] Result<void> rename_atomic(const std::filesystem::path& from, const std::filesystem::path& to) override;
[[nodiscard]] Result<void> unlink_file(const std::filesystem::path& p) override;
[[nodiscard]] Result<void> sync_dir(const std::filesystem::path& dir) override;
[[nodiscard]] Result<void> probe_durability_capabilities(const std::filesystem::path& dir) override;
private:
friend class FaultFileHandle;
struct MatchedFault {
StorageErrorCode error_code{StorageErrorCode::none};
std::optional<std::size_t> partial_write_bytes{};
bool triggered{false};
};
[[nodiscard]] MatchedFault check_fault(FaultOp op, const std::string& path);
void maybe_run_sync_hook();
std::shared_ptr<FilePort> delegate_;
mutable std::mutex mu_;
std::vector<FaultRule> rules_{};
std::function<void()> pause_before_sync_{};
std::uint64_t op_counts_[10]{};
};
} // namespace Void::Storage
+216
View File
@@ -0,0 +1,216 @@
#pragma once
#include <Void/Core/Uuid.hpp>
#include <Void/Storage/Types.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace Void::Storage
{
inline constexpr std::array<char, 8> kWalSegmentMagic{'V', 'O', 'I', 'D', 'W', 'A', 'L', '1'};
inline constexpr std::uint16_t kWalFormatMajor = 1;
inline constexpr std::uint16_t kWalFormatMinor = 0;
inline constexpr std::uint32_t kWalSegmentHeaderSize = 64;
inline constexpr std::uint32_t kWalRecordMagic = 0x56575231u; // "1RWV" little-endian
inline constexpr std::uint16_t kWalRecordVersion = 1;
inline constexpr std::uint32_t kWalRecordHeaderSize = 36;
inline constexpr std::uint32_t kWalRecordTrailerSize = 8;
enum class WalRecordType : std::uint16_t {
Begin = 1,
Put = 2,
Erase = 3,
Commit = 4
};
struct WalSegmentHeader {
std::uint16_t major{kWalFormatMajor};
std::uint16_t minor{kWalFormatMinor};
std::uint32_t header_size{kWalSegmentHeaderSize};
Void::Uuid::Uuid database_uuid{};
std::uint64_t segment_id{0};
std::uint64_t previous_segment_id{0};
Sequence first_candidate_sequence{0};
std::uint32_t flags{0};
};
struct WalRecordHeader {
std::uint32_t total_length{0};
WalRecordType type{WalRecordType::Begin};
std::uint16_t record_version{kWalRecordVersion};
std::uint32_t flags{0};
Sequence batch_sequence{0};
std::uint32_t ordinal{0};
std::uint32_t payload_length{0};
};
struct WalBeginPayload {
std::uint32_t op_count{0};
std::uint64_t total_op_bytes{0};
};
struct WalMutationPayload {
OwnedBytes key{};
OwnedBytes value{};
};
struct WalCommitPayload {
std::uint32_t op_count{0};
std::uint64_t total_op_bytes{0};
std::uint32_t aggregate_crc32c{0};
};
[[nodiscard]] Result<OwnedBytes> encode_wal_segment_header(const WalSegmentHeader& hdr);
[[nodiscard]] Result<WalSegmentHeader> decode_wal_segment_header(ByteView bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_record_frame(
WalRecordType type,
Sequence batch_sequence,
std::uint32_t ordinal,
ByteView payload);
/// Decode and verify ONLY the 36-byte record header before reading/allocating payload.
[[nodiscard]] Result<WalRecordHeader> decode_wal_record_header(
ByteView header_bytes,
std::size_t max_payload_bytes);
/// Verify full record CRC32C and trailing repeated length after reading payload+trailer.
[[nodiscard]] Result<void> verify_wal_record_frame(
const WalRecordHeader& hdr,
ByteView full_record_bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_begin_payload(const WalBeginPayload& p);
[[nodiscard]] Result<WalBeginPayload> decode_wal_begin_payload(ByteView bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_mutation_payload(
bool is_erase, ByteView key, ByteView value);
[[nodiscard]] Result<WalMutationPayload> decode_wal_mutation_payload(
bool is_erase,
ByteView bytes,
std::size_t max_key_bytes,
std::size_t max_value_bytes);
[[nodiscard]] Result<OwnedBytes> encode_wal_commit_payload(const WalCommitPayload& p);
[[nodiscard]] Result<WalCommitPayload> decode_wal_commit_payload(ByteView bytes);
// ── V1 Immutable Sorted Table (`VOIDTBL1`) ───────────────────────────────
inline constexpr std::array<char, 8> kTableMagic{'V', 'O', 'I', 'D', 'T', 'B', 'L', '1'};
inline constexpr std::array<char, 8> kTableFooterMagic{'V', 'O', 'I', 'D', 'T', 'B', 'F', '1'};
inline constexpr std::uint32_t kTableHeaderSize = 76;
inline constexpr std::uint32_t kTableFooterSize = 48;
struct TableEntryRecord {
OwnedBytes key{};
Sequence sequence{0};
bool erased{false};
OwnedBytes value{};
};
struct TableHeader {
std::uint16_t major{1};
std::uint16_t minor{0};
std::uint32_t header_size{kTableHeaderSize};
Void::Uuid::Uuid database_uuid{};
std::uint64_t table_id{0};
std::uint32_t level{0};
std::uint32_t flags{0};
std::uint64_t entry_count{0};
Sequence min_sequence{0};
Sequence max_sequence{0};
};
struct TableBlockIndexEntry {
OwnedBytes first_key{};
OwnedBytes last_key{};
std::uint64_t offset{0};
std::uint32_t byte_length{0};
};
struct TableFooter {
std::uint64_t index_offset{0};
std::uint64_t index_size{0};
std::uint64_t data_end_offset{0};
std::uint32_t file_crc32c{0};
};
struct TableMeta {
std::uint64_t table_id{0};
std::uint32_t level{0};
std::uint64_t file_size{0};
std::uint64_t entry_count{0};
Sequence min_sequence{0};
Sequence max_sequence{0};
OwnedBytes min_key{};
OwnedBytes max_key{};
std::uint32_t file_crc32c{0};
};
[[nodiscard]] Result<OwnedBytes> encode_table_header(const TableHeader& hdr);
[[nodiscard]] Result<TableHeader> decode_table_header(ByteView bytes);
[[nodiscard]] Result<OwnedBytes> encode_table_block(
std::span<const TableEntryRecord> entries,
std::size_t max_bytes);
[[nodiscard]] Result<std::vector<TableEntryRecord>> decode_table_block(
ByteView bytes,
std::size_t max_key_bytes,
std::size_t max_value_bytes);
[[nodiscard]] Result<OwnedBytes> encode_table_index(
std::span<const TableBlockIndexEntry> index,
std::size_t max_bytes);
[[nodiscard]] Result<std::vector<TableBlockIndexEntry>> decode_table_index(
ByteView bytes,
std::size_t max_key_bytes);
[[nodiscard]] Result<OwnedBytes> encode_table_footer(const TableFooter& footer);
[[nodiscard]] Result<TableFooter> decode_table_footer(ByteView bytes);
// ── V1 Manifest (`VOIDMNF1`) & CURRENT (`VOIDCUR1`) ──────────────────────
inline constexpr std::array<char, 8> kManifestMagic{'V', 'O', 'I', 'D', 'M', 'N', 'F', '1'};
inline constexpr std::array<char, 8> kCurrentMagic{'V', 'O', 'I', 'D', 'C', 'U', 'R', '1'};
inline constexpr std::string_view kComparatorIdV1 = "void.byte.lex.v1";
struct ManifestData {
std::uint16_t major{1};
std::uint16_t minor{0};
std::uint32_t flags{0};
Void::Uuid::Uuid database_uuid{};
std::uint64_t generation{0};
Sequence checkpoint_sequence{0};
Sequence next_sequence_hint{1};
std::uint64_t next_file_id{1};
std::string comparator{kComparatorIdV1};
std::vector<TableMeta> tables{};
std::vector<std::uint64_t> wal_segments{};
};
struct CurrentPointer {
std::uint16_t major{1};
std::uint16_t minor{0};
Void::Uuid::Uuid database_uuid{};
std::uint64_t generation{0};
std::string manifest_filename{};
};
[[nodiscard]] Result<OwnedBytes> encode_manifest(
const ManifestData& m,
std::size_t max_manifest_bytes);
[[nodiscard]] Result<ManifestData> decode_manifest(
ByteView bytes,
std::size_t max_manifest_bytes,
std::size_t max_tables,
std::size_t max_key_bytes);
[[nodiscard]] Result<OwnedBytes> encode_current(const CurrentPointer& cur);
[[nodiscard]] Result<CurrentPointer> decode_current(ByteView bytes);
[[nodiscard]] std::string make_wal_filename(std::uint64_t segment_id);
[[nodiscard]] std::string make_table_filename(std::uint64_t table_id);
[[nodiscard]] std::string make_manifest_filename(std::uint64_t generation);
} // namespace Void::Storage
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <Void/Storage/AsyncAdapter.hpp>
#include <Void/Storage/Batch.hpp>
#include <Void/Storage/Crc32c.hpp>
#include <Void/Storage/Engine.hpp>
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Format.hpp>
#include <Void/Storage/Tools.hpp>
#include <Void/Storage/Types.hpp>
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Types.hpp>
#include <cstdint>
#include <filesystem>
#include <memory>
namespace Void::Storage
{
struct VerifyReport {
std::uint64_t manifest_generation{0};
Sequence checkpoint_sequence{0};
std::uint64_t tables_verified{0};
std::uint64_t blocks_verified{0};
std::uint64_t wal_segments_verified{0};
std::uint64_t wal_batches_verified{0};
};
struct SalvageReport {
Sequence highest_recovered_sequence{0};
std::uint64_t recovered_batches{0};
std::uint64_t keys_recovered{0};
std::uint64_t tombstones_preserved{0};
std::uint64_t truncated_or_skipped_bytes{0};
};
/// Read-only full structural & block-level verification of an offline or
/// quiesced Storage directory (CURRENT, MANIFEST, every block of every table,
/// and every manifest-listed WAL segment).
[[nodiscard]] Result<VerifyReport> verify_directory(
const std::filesystem::path& directory,
const Limits& limits = {},
std::shared_ptr<FilePort> port = nullptr);
/// Restore a verified backup directory into `destination` without mutating
/// `backup_dir`.
[[nodiscard]] Result<void> restore_backup(
const std::filesystem::path& backup_dir,
const std::filesystem::path& destination,
const Limits& limits = {},
std::shared_ptr<FilePort> port = nullptr);
/// Offline salvage: extracts the valid prefix of committed data and valid
/// tables/WAL records from `source_dir` into a fresh `destination_dir`.
/// Refuses same-directory salvage.
[[nodiscard]] Result<SalvageReport> salvage_directory(
const std::filesystem::path& source_dir,
const std::filesystem::path& destination_dir,
const Limits& limits = {},
std::shared_ptr<FilePort> port = nullptr);
} // namespace Void::Storage
+381
View File
@@ -0,0 +1,381 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <memory_resource>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
namespace Void::Storage
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
using Sequence = std::uint64_t;
using ByteView = std::span<const std::byte>;
using OwnedBytes = std::vector<std::byte>;
class FilePort;
enum class Durability : std::uint8_t {
Sync = 0,
Buffered = 1
};
enum class Outcome : std::uint8_t {
NotCommitted = 0,
Committed = 1,
Unknown = 2
};
enum class EngineState : std::uint8_t {
Open = 0,
RecoveryRequired = 1,
Closed = 2
};
enum class StorageErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
not_found = 2,
conflict = 3,
interrupted = 4,
timeout = 5,
overloaded = 6,
unsupported_capability = 7,
io_error = 8,
corrupt = 9,
incomplete_init = 10,
sequence_exhausted = 11,
recovery_required = 12,
busy = 13,
closed = 14,
page_too_small = 15,
quota_exceeded = 16
};
[[nodiscard]] inline Error make_storage_error(
StorageErrorCode code,
std::string message,
std::error_code sys_err = {})
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case StorageErrorCode::none:
kind = ErrorKind::internal;
break;
case StorageErrorCode::invalid_argument:
case StorageErrorCode::page_too_small:
kind = ErrorKind::invalid_argument;
break;
case StorageErrorCode::not_found:
kind = ErrorKind::not_found;
break;
case StorageErrorCode::conflict:
case StorageErrorCode::recovery_required:
case StorageErrorCode::busy:
case StorageErrorCode::incomplete_init:
kind = ErrorKind::conflict;
break;
case StorageErrorCode::interrupted:
case StorageErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case StorageErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case StorageErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case StorageErrorCode::unsupported_capability:
kind = ErrorKind::unsupported;
break;
case StorageErrorCode::io_error:
kind = ErrorKind::io;
break;
case StorageErrorCode::corrupt:
kind = ErrorKind::corrupt;
break;
case StorageErrorCode::sequence_exhausted:
case StorageErrorCode::quota_exceeded:
kind = ErrorKind::exhausted;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kStorageErrorDomain,
static_cast<std::int32_t>(code)},
sys_err};
}
struct StorageError {
StorageErrorCode code{StorageErrorCode::none};
Error error{};
};
struct CommitReceipt {
Sequence sequence{0};
Durability durability{Durability::Sync};
};
struct WriteFailure {
StorageError cause{};
Outcome outcome{Outcome::NotCommitted};
};
struct OwnedValue {
OwnedBytes bytes{};
Sequence version{0};
[[nodiscard]] std::string_view as_string_view() const noexcept
{
return bytes.empty()
? std::string_view{}
: std::string_view{
reinterpret_cast<const char*>(bytes.data()),
bytes.size()};
}
[[nodiscard]] bool operator==(const OwnedValue&) const = default;
};
[[nodiscard]] inline OwnedBytes to_owned_bytes(std::string_view s)
{
OwnedBytes out(s.size());
for (std::size_t i = 0; i < s.size(); ++i) {
out[i] = static_cast<std::byte>(static_cast<unsigned char>(s[i]));
}
return out;
}
[[nodiscard]] inline ByteView to_byte_view(std::string_view s) noexcept
{
return std::as_bytes(std::span{s.data(), s.size()});
}
[[nodiscard]] inline std::string_view to_string_view(ByteView b) noexcept
{
return b.empty()
? std::string_view{}
: std::string_view{
reinterpret_cast<const char*>(b.data()),
b.size()};
}
/// Locale-independent unsigned-byte lexicographic comparison.
[[nodiscard]] inline int byte_compare(ByteView a, ByteView b) noexcept
{
const std::size_t n = std::min(a.size(), b.size());
for (std::size_t i = 0; i < n; ++i) {
const auto xa = std::to_integer<unsigned char>(a[i]);
const auto yb = std::to_integer<unsigned char>(b[i]);
if (xa < yb) return -1;
if (xa > yb) return 1;
}
if (a.size() < b.size()) return -1;
if (a.size() > b.size()) return 1;
return 0;
}
struct ByteLess {
using is_transparent = void;
[[nodiscard]] bool operator()(ByteView a, ByteView b) const noexcept
{
return byte_compare(a, b) < 0;
}
[[nodiscard]] bool operator()(const OwnedBytes& a, const OwnedBytes& b) const noexcept
{
return byte_compare(a, b) < 0;
}
[[nodiscard]] bool operator()(const OwnedBytes& a, ByteView b) const noexcept
{
return byte_compare(a, b) < 0;
}
[[nodiscard]] bool operator()(ByteView a, const OwnedBytes& b) const noexcept
{
return byte_compare(a, b) < 0;
}
};
struct ScanBounds {
std::optional<OwnedBytes> begin{};
std::optional<OwnedBytes> end{};
std::size_t page_bytes{0};
std::size_t page_rows{0};
[[nodiscard]] static ScanBounds all() { return {}; }
[[nodiscard]] static ScanBounds range(ByteView b, ByteView e)
{
ScanBounds sb;
sb.begin.emplace(b.begin(), b.end());
sb.end.emplace(e.begin(), e.end());
return sb;
}
[[nodiscard]] static ScanBounds range(std::string_view b, std::string_view e)
{
return range(to_byte_view(b), to_byte_view(e));
}
[[nodiscard]] static ScanBounds prefix(ByteView p)
{
ScanBounds sb;
sb.begin.emplace(p.begin(), p.end());
OwnedBytes upper(p.begin(), p.end());
while (!upper.empty()) {
const auto b = std::to_integer<unsigned char>(upper.back());
if (b < 0xFFu) {
upper.back() = static_cast<std::byte>(b + 1u);
sb.end = std::move(upper);
return sb;
}
upper.pop_back();
}
// All-0xFF prefix has no finite upper bound.
return sb;
}
[[nodiscard]] static ScanBounds prefix(std::string_view p)
{
return prefix(to_byte_view(p));
}
};
struct ScanEntry {
OwnedBytes key{};
OwnedBytes value{};
Sequence version{0};
};
struct ScanPage {
std::vector<ScanEntry> entries{};
bool has_more{false};
};
struct Limits {
std::size_t max_key_bytes{4096};
std::size_t max_value_bytes{4ULL * 1024ULL * 1024ULL};
std::size_t max_batch_encoded_bytes{16ULL * 1024ULL * 1024ULL};
std::size_t max_batch_mutations{1024};
std::size_t max_batch_conditions{1024};
std::size_t max_pending_batches{64};
std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t active_memtable_target_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_total_memtable_bytes{256ULL * 1024ULL * 1024ULL};
std::size_t max_snapshots{128};
std::size_t max_cursors{128};
std::size_t default_scan_page_bytes{1024ULL * 1024ULL};
std::size_t max_scan_page_bytes{8ULL * 1024ULL * 1024ULL};
std::size_t default_scan_page_rows{1024};
std::size_t max_obsolete_pinned_bytes{1024ULL * 1024ULL * 1024ULL};
std::size_t block_cache_bytes{32ULL * 1024ULL * 1024ULL};
std::size_t compaction_workspace_bytes{16ULL * 1024ULL * 1024ULL};
std::uint64_t wal_segment_target_bytes{64ULL * 1024ULL * 1024ULL};
std::uint64_t max_wal_total_bytes{4ULL * 1024ULL * 1024ULL * 1024ULL};
std::size_t max_active_runs{32};
std::size_t table_block_target_bytes{32768};
std::size_t max_manifest_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_manifest_tables{65536};
std::size_t max_compaction_merge_runs{4};
std::uint64_t compaction_output_target_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t compaction_work_slice_bytes{8ULL * 1024ULL * 1024ULL};
};
[[nodiscard]] inline Result<void> validate_limits(const Limits& l)
{
if (l.max_key_bytes == 0 ||
l.max_value_bytes == 0 ||
l.max_batch_encoded_bytes == 0 ||
l.max_batch_mutations == 0 ||
l.max_batch_conditions == 0 ||
l.max_pending_batches == 0 ||
l.max_pending_bytes == 0 ||
l.active_memtable_target_bytes == 0 ||
l.max_total_memtable_bytes == 0 ||
l.max_snapshots == 0 ||
l.max_cursors == 0 ||
l.default_scan_page_bytes == 0 ||
l.max_scan_page_bytes == 0 ||
l.default_scan_page_rows == 0 ||
l.max_obsolete_pinned_bytes == 0 ||
l.block_cache_bytes == 0 ||
l.compaction_workspace_bytes == 0 ||
l.wal_segment_target_bytes == 0 ||
l.max_wal_total_bytes == 0 ||
l.max_active_runs == 0 ||
l.table_block_target_bytes == 0 ||
l.max_manifest_bytes == 0 ||
l.max_manifest_tables == 0 ||
l.max_compaction_merge_runs == 0 ||
l.compaction_output_target_bytes == 0 ||
l.compaction_work_slice_bytes == 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Limits: all limits must be positive finite values"));
}
if (l.default_scan_page_bytes > l.max_scan_page_bytes ||
l.active_memtable_target_bytes > l.max_total_memtable_bytes ||
l.wal_segment_target_bytes > l.max_wal_total_bytes ||
l.max_batch_encoded_bytes > l.wal_segment_target_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Limits: inconsistent bound ordering (max batch must fit in one WAL segment)"));
}
return {};
}
struct OpenOptions {
std::filesystem::path directory{};
Durability default_durability{Durability::Sync};
Limits limits{};
std::pmr::memory_resource* memory_resource{nullptr};
std::shared_ptr<FilePort> file_port{};
const Void::Time::MonotonicClock* monotonic_clock{nullptr};
std::function<void(std::string_view)> metric_hook{};
/// Optional explicit sequence seed used only when opening a brand-new
/// database (e.g. sequence-exhaustion tests).
Sequence initial_sequence{0};
};
struct EngineStats {
EngineState state{EngineState::Closed};
Sequence committed_sequence{0};
Sequence checkpoint_sequence{0};
Sequence oldest_snapshot_sequence{0};
std::uint64_t live_snapshots{0};
std::uint64_t live_cursors{0};
std::uint64_t active_memtable_bytes{0};
std::uint64_t total_memtable_bytes{0};
std::uint64_t wal_total_bytes{0};
std::uint64_t active_table_count{0};
std::uint64_t obsolete_pinned_bytes{0};
std::uint64_t total_table_bytes{0};
std::uint64_t recovery_truncated_bytes{0};
bool durable_sync_verified{false};
};
} // namespace Void::Storage
+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
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
)
+361 -40
View File
@@ -1,22 +1,152 @@
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <utility>
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_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(); }
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)
{
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();
return {};
}
bool ExecutionContext::try_take_any(
@@ -26,57 +156,170 @@ namespace Void::Fsm::Detail
const auto it = m_buffers.find(std::type_index{*ty});
if (it != m_buffers.end() && !it->second.empty()) {
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();
if (m_buffered_events > 0) {
--m_buffered_events;
}
m_buffered_bytes -= std::min(m_buffered_bytes, out.bytes);
return true;
}
}
return false;
}
void ExecutionContext::set_waiter(
ExecutionContext::WaiterId ExecutionContext::set_waiter(
std::span<const std::type_info* const> types,
std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out,
std::optional<std::chrono::steady_clock::time_point> deadline)
std::optional<Time::MonotonicClock::time_point> deadline,
ScopeId scope, bool* cancelled)
{
Waiter w;
w.id = m_next_waiter++;
w.scope = scope;
w.types.assign(types.begin(), types.end());
w.cont = cont;
w.slot = slot;
w.timed_out = timed_out;
w.cancelled = cancelled;
w.timer = 0;
if (deadline.has_value()) {
const WaiterId id = w.id;
w.timer = add_timer(*deadline, [this, id] {
// Timeout: resume that waiter (if still parked) with timed_out.
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;
auto timer_res = try_add_timer(
*deadline,
[this, id] {
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;
}
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) {
*it->timed_out = true;
}
auto cont2 = it->cont;
m_waiters.erase(it);
m_executor.post(cont2);
});
active_executor().post_completion(cont);
return w.id;
}
}
m_waiters.push_back(std::move(w));
return m_waiters.back().id;
}
ExecutionContext::TimerId ExecutionContext::add_timer(
std::chrono::steady_clock::time_point deadline,
std::function<void()>
on_fire)
void ExecutionContext::cancel_waiter(WaiterId id)
{
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++;
m_timers.emplace(id, Timer{deadline, std::move(on_fire)});
m_timers.emplace(id, Timer{deadline, std::move(on_fire), scope});
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)
{
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
{
std::optional<std::chrono::steady_clock::time_point> next;
std::optional<Time::MonotonicClock::time_point> next;
for (const auto& [id, timer] : m_timers) {
if (!next.has_value() || timer.deadline < *next) {
next = timer.deadline;
@@ -101,7 +344,7 @@ namespace Void::Fsm::Detail
if (m_timers.empty()) {
return;
}
const auto now = std::chrono::steady_clock::now();
const auto now = m_clock->now();
std::vector<std::function<void()>> due;
for (auto it = m_timers.begin(); it != m_timers.end();) {
if (it->second.deadline <= now) {
@@ -120,20 +363,36 @@ namespace Void::Fsm::Detail
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) {
if (it->wants(*env.type)) {
*it->slot = std::move(env);
cancel_timer(it->timer);
auto cont = it->cont;
m_waiters.erase(it);
m_executor.post(cont);
active_executor().post_completion(cont);
return;
}
}
// Otherwise buffer for a later await.
m_buffers[std::type_index{*env.type}].push_back(std::move(env.value));
if (m_limits.max_deferred_events > 0 &&
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)
@@ -144,22 +403,81 @@ namespace Void::Fsm::Detail
std::size_t ExecutionContext::pump()
{
drain_control_queue();
if (m_paused.load(std::memory_order_acquire)) {
return 0;
}
++m_dispatch_turn;
std::size_t work = 0;
std::size_t events_this_turn = 0;
const auto turn_start = m_clock->now();
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);
++events_this_turn;
++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();
drain_control_queue();
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
{
if (m_external_executor != nullptr) {
schedule_external_pump();
}
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
m_wakeup.release();
}
@@ -204,22 +522,25 @@ namespace Void::Fsm::Detail
const bool paused = m_paused.load(std::memory_order_acquire);
if (!paused) {
pump();
} else {
drain_control_queue();
}
if (m_done.load(std::memory_order_acquire)) {
return;
}
m_sleeping.store(true, std::memory_order_release);
// Queued events only count as wakeable work when not paused.
if ((!paused && !m_queue.empty()) ||
if ((!paused && !m_queue.empty()) || !m_control_queue.empty() ||
m_done.load(std::memory_order_acquire)) {
m_sleeping.store(false, std::memory_order_release);
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();
!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 {
m_wakeup.acquire();
}
+1 -1
View File
@@ -1,3 +1,3 @@
void_add_module(Fsm
INTERNAL_DEPS Async Core Data Functional Log Service
INTERNAL_DEPS Async Core Data Functional Time Log Service
)
+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
// already-mapped image when the file is replaced in place. The name
// 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.
// already-mapped image when the file is replaced in place.
std::expected<std::filesystem::path, LoadError>
hotswap_copy(const std::filesystem::path& path)
{
@@ -213,9 +210,10 @@ namespace Void::Plugin
// ── PluginManager ─────────────────────────────────────────────────────
PluginManager::PluginManager(Options options)
: m_options(options), m_watcher(FileSystem::FileWatcherOptions{
.poll_interval = options.poll_interval,
.debounce_polls = options.debounce_polls})
: m_options(std::move(options)),
m_watcher(FileSystem::FileWatcherOptions{
.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();
}
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>
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);
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);
}
if (!inst.has_value()) {
@@ -278,15 +281,24 @@ namespace Void::Plugin
return std::unexpected{LoadError::ActivationFailed};
}
std::lock_guard lock(m_mutex);
auto entry = std::make_unique<Entry>();
entry->path = path;
entry->current.store(std::move(*inst), std::memory_order_release);
Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})",
path.string(), name,
entry->current.load(std::memory_order_relaxed)
->info.plugin_version);
m_plugins.insert_or_assign(name, std::move(entry));
std::shared_ptr<Entry> replaced_entry;
{
std::lock_guard lock(m_mutex);
auto entry = std::make_shared<Entry>();
entry->path = path;
entry->current.store(std::move(*inst), std::memory_order_release);
Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})",
path.string(), name,
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;
}
@@ -323,195 +335,199 @@ namespace Void::Plugin
std::expected<void, LoadError> PluginManager::unload(std::string_view name)
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
std::shared_ptr<Entry> removed;
{
std::lock_guard lock(m_mutex);
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);
return {};
}
PluginHandle PluginManager::acquire(std::string_view name) const
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
std::shared_ptr<Entry> entry;
{
std::lock_guard lock(m_mutex);
entry = find_shared(name);
}
if (!entry) {
return PluginHandle{};
}
// One atomic load pins the instance; it survives any later swap.
return PluginHandle{entry->current.load(std::memory_order_acquire)};
}
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);
auto* entry = find(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();
entry = find_shared(name);
}
for (const auto& cb : callbacks) {
cb(name);
if (!entry) {
return std::unexpected{LoadError::UnknownPlugin};
}
return {};
return reload_entry_unlocked(entry, name, std::nullopt);
}
std::expected<void, LoadError>
PluginManager::replace(std::string_view name,
const std::filesystem::path& newPath)
{
std::vector<std::function<void(std::string_view)>> callbacks;
bool restartWatcher = false;
std::shared_ptr<Entry> entry;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
return std::unexpected{LoadError::UnknownPlugin};
}
std::error_code error;
if (!std::filesystem::is_regular_file(newPath, error)) {
return std::unexpected{LoadError::FileNotFound};
}
auto result = reload_locked(*entry, name, newPath);
if (!result) {
return result;
}
restartWatcher = entry->watched;
if (restartWatcher) {
m_watcher.unwatch(entry->path);
}
entry->path = newPath;
callbacks = reload_callbacks_locked();
entry = find_shared(name);
}
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) {
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);
for (const auto& cb : callbacks) {
cb(name);
}
return {};
}
void PluginManager::watch(std::string_view name)
{
std::shared_ptr<Entry> entry;
std::filesystem::path path;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name);
if (entry == nullptr) {
entry = find_shared(name);
if (!entry) {
return;
}
path = entry->path;
entry->watched = true;
}
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) {
if (!e.exists) {
return;
}
std::vector<std::function<void(std::string_view)>> callbacks;
{
std::lock_guard lock(m_mutex);
auto* entry = find(name_str);
if (entry == nullptr) {
return;
}
if (!reload_locked(*entry, name_str, entry->path).has_value()) {
return;
}
callbacks = reload_callbacks_locked();
}
for (const auto& cb : callbacks) {
cb(name_str);
}
(void)reload_entry_unlocked(entry, name_str, std::nullopt);
});
}
+1 -1
View File
@@ -1,4 +1,4 @@
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
)
+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
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
)
+2339 -100
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -1,4 +1,5 @@
void_add_module(Sqlite
INTERNAL_DEPS Functional
INTERNAL_DEPS Functional Time
EXTERNAL_DEPS SQLite3::SQLite3
EXCLUDE_HEADERS Void/Sqlite/AsyncPool.hpp
)
+461
View File
@@ -0,0 +1,461 @@
#include <Void/Sqlite/AsyncPool.hpp>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <stop_token>
#include <thread>
#include <utility>
#include <vector>
namespace Void::Sqlite
{
struct AsyncPool::Impl : public std::enable_shared_from_this<Impl> {
struct Job {
std::shared_ptr<Void::Async::OperationState<void>> op_state{};
std::function<Result<void>(Database&)> fn{};
std::size_t input_bytes{0};
std::uint64_t generation{0};
};
explicit Impl(AsyncPoolOptions opts, Void::Async::Executor* exec)
: options(std::move(opts)),
clock(options.clock ? options.clock
: &Void::Time::SystemMonotonicClock::instance()),
completion_executor(exec)
{
}
~Impl()
{
(void)close_and_join();
}
Result<void> start()
{
if (options.path.empty()) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: database path must not be empty"));
}
if (options.reader_connections > 0 &&
(options.path == ":memory:" ||
options.path.string().starts_with("file::memory:"))) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: multi-connection pool does not support private :memory: paths"));
}
if (options.max_queued_jobs == 0 || options.max_pending_input_bytes == 0) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: max_queued_jobs and max_pending_input_bytes must be positive"));
}
if (auto v = validate_limits(options.open_options.limits); !v) {
return v;
}
// Open writer first so the file and WAL mode are initialized before
// read-only connections open.
OpenOptions writer_opts = options.open_options;
if (writer_opts.mode == OpenMode::ReadOnly) {
writer_opts.mode = OpenMode::ReadWriteCreate;
}
auto wdb = Database::open_with_options(options.path, std::move(writer_opts));
if (!wdb) {
return Void::Result::fail(std::move(wdb).error());
}
writer_db = std::move(*wdb);
readers.reserve(options.reader_connections);
for (std::size_t i = 0; i < options.reader_connections; ++i) {
OpenOptions ropts = options.open_options;
ropts.mode = OpenMode::ReadOnly;
auto rdb = Database::open_with_options(options.path, std::move(ropts));
if (!rdb) {
(void)writer_db.close();
for (auto& existing : readers) {
(void)existing.close();
}
readers.clear();
return Void::Result::fail(std::move(rdb).error());
}
readers.push_back(std::move(*rdb));
}
writer_thread = std::thread([this]() { run_writer_loop(); });
reader_threads.reserve(readers.size());
for (std::size_t i = 0; i < readers.size(); ++i) {
reader_threads.emplace_back([this, i]() { run_reader_loop(i); });
}
return {};
}
Void::Coro::Task<Result<void>> submit_erased(
bool is_write,
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
if (!fn) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: null work callback"));
}
if (is_write == false && readers.empty()) {
// Route read to writer lane when configured with 0 readers.
is_write = true;
}
if (op.stop.stop_requested()) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::cancelled,
"AsyncPool: operation cancelled before admission"));
}
if (op.deadline.has_value() && clock->now() >= *op.deadline) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation deadline expired before admission"));
}
auto state = Void::Async::OperationState<void>::create(
op, completion_executor, Void::Async::StopBehavior::notify_only);
Job job;
job.op_state = state;
job.fn = std::move(fn);
job.input_bytes = input_bytes;
{
std::lock_guard lk{mu};
if (closing || closed) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::closed,
"AsyncPool: pool is closing"));
}
const std::size_t total_queued = write_queue.size() + read_queue.size();
if (total_queued >= options.max_queued_jobs ||
input_bytes > options.max_pending_input_bytes ||
pending_input_bytes > options.max_pending_input_bytes - input_bytes) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::overloaded,
"AsyncPool: queue depth or pending input byte budget exceeded"));
}
job.generation = ++next_generation;
pending_input_bytes += input_bytes;
state->acquire_backend_ref();
if (is_write) {
write_queue.push_back(std::move(job));
} else {
read_queue.push_back(std::move(job));
}
}
if (is_write) {
write_cv.notify_one();
} else {
read_cv.notify_one();
}
auto res = co_await state->awaitable(completion_executor);
co_return res;
}
void execute_job(Database& db, Job& job)
{
auto& state = job.op_state;
if (state->stop_requested()) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
if (auto t = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::cancelled,
"AsyncPool: operation cancelled before execution"));
t) {
t->dispatch();
}
state->release_backend_ref_and_dispatch();
return;
}
if (state->is_deadline_expired(*clock)) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
if (auto t = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation deadline expired before execution"));
t) {
t->dispatch();
}
state->release_backend_ref_and_dispatch();
return;
}
const auto gen = job.generation;
const int steps = std::max(1, options.progress_handler_steps);
db.begin_leased_operation(
gen,
steps,
[state, clk = this->clock]() {
return state->stop_requested() || state->is_deadline_expired(*clk);
});
struct StopInterrupter {
Database* target_db{nullptr};
std::uint64_t target_gen{0};
void operator()() const noexcept
{
if (target_db != nullptr) {
target_db->interrupt_leased_operation(target_gen);
}
}
};
// Registered before job.fn runs and destroyed BEFORE end_leased_operation,
// so stop callbacks never race with subsequent borrowers.
Result<void> exec_result;
{
std::optional<std::stop_callback<StopInterrupter>> stop_cb;
const auto st = state->stop_token();
if (st.stop_possible()) {
stop_cb.emplace(st, StopInterrupter{&db, gen});
}
exec_result = job.fn(db);
}
db.end_leased_operation(gen);
std::optional<Void::Async::ResumeTicket> ticket;
if (exec_result) {
completed_jobs.fetch_add(1, std::memory_order_relaxed);
ticket = state->try_commit_value();
} else {
const auto kind = exec_result.error().kind();
if (kind == Void::Result::ErrorKind::cancelled ||
kind == Void::Result::ErrorKind::timeout) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
}
// Reclassify SQLITE_INTERRUPT when caused by deadline expiry.
if (kind == Void::Result::ErrorKind::cancelled &&
!state->stop_requested() &&
state->is_deadline_expired(*clock)) {
ticket = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation interrupted due to deadline expiry"));
} else {
ticket = state->try_commit_error(std::move(exec_result).error());
}
}
if (ticket) {
ticket->dispatch();
}
state->release_backend_ref_and_dispatch();
}
void run_writer_loop()
{
for (;;) {
Job job;
{
std::unique_lock lk{mu};
write_cv.wait(lk, [this]() {
return !write_queue.empty() || closing;
});
if (write_queue.empty() && closing) {
return;
}
job = std::move(write_queue.front());
write_queue.pop_front();
pending_input_bytes -= job.input_bytes;
++active_write_jobs;
}
execute_job(writer_db, job);
{
std::lock_guard lk{mu};
--active_write_jobs;
}
}
}
void run_reader_loop(std::size_t idx)
{
for (;;) {
Job job;
{
std::unique_lock lk{mu};
read_cv.wait(lk, [this]() {
return !read_queue.empty() || closing;
});
if (read_queue.empty() && closing) {
return;
}
job = std::move(read_queue.front());
read_queue.pop_front();
pending_input_bytes -= job.input_bytes;
++active_read_jobs;
}
execute_job(readers[idx], job);
{
std::lock_guard lk{mu};
--active_read_jobs;
}
}
}
Result<void> close_and_join()
{
{
std::lock_guard lk{mu};
if (closed) {
return {};
}
closing = true;
}
write_cv.notify_all();
read_cv.notify_all();
if (writer_thread.joinable()) {
writer_thread.join();
}
for (auto& t : reader_threads) {
if (t.joinable()) {
t.join();
}
}
reader_threads.clear();
std::optional<Error> first_err;
if (writer_db.is_open()) {
if (auto r = writer_db.close(); !r && !first_err) {
first_err = std::move(r).error();
}
}
for (auto& rdb : readers) {
if (rdb.is_open()) {
if (auto r = rdb.close(); !r && !first_err) {
first_err = std::move(r).error();
}
}
}
readers.clear();
{
std::lock_guard lk{mu};
closed = true;
}
if (first_err) {
return Void::Result::fail(std::move(*first_err));
}
return {};
}
AsyncPoolOptions options;
const Void::Time::MonotonicClock* clock;
Void::Async::Executor* completion_executor{nullptr};
Database writer_db{};
std::vector<Database> readers{};
mutable std::mutex mu{};
std::condition_variable write_cv{};
std::condition_variable read_cv{};
std::deque<Job> write_queue{};
std::deque<Job> read_queue{};
std::size_t pending_input_bytes{0};
std::size_t active_read_jobs{0};
std::size_t active_write_jobs{0};
std::uint64_t next_generation{0};
bool closing{false};
bool closed{false};
std::atomic<std::uint64_t> completed_jobs{0};
std::atomic<std::uint64_t> rejected_jobs{0};
std::atomic<std::uint64_t> cancelled_jobs{0};
std::thread writer_thread{};
std::vector<std::thread> reader_threads{};
};
AsyncPool::AsyncPool(std::shared_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
AsyncPool::~AsyncPool()
{
if (m_impl) {
(void)m_impl->close_and_join();
}
}
AsyncPool::AsyncPool(AsyncPool&&) noexcept = default;
AsyncPool& AsyncPool::operator=(AsyncPool&&) noexcept = default;
Result<AsyncPool> AsyncPool::open(
AsyncPoolOptions options,
Void::Async::Executor* completion_executor)
{
auto impl = std::make_shared<Impl>(std::move(options), completion_executor);
if (auto r = impl->start(); !r) {
return Void::Result::fail(std::move(r).error());
}
return AsyncPool{std::move(impl)};
}
Void::Coro::Task<Result<void>> AsyncPool::submit_erased(
bool is_write,
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
if (!m_impl) {
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::closed, "AsyncPool: moved-from pool"));
}
co_return co_await m_impl->submit_erased(
is_write, std::move(fn), std::move(op), input_bytes);
}
Void::Coro::Task<Result<void>> AsyncPool::run_read_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
co_return co_await submit_erased(false, std::move(fn), std::move(op), input_bytes);
}
Void::Coro::Task<Result<void>> AsyncPool::run_write_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
co_return co_await submit_erased(true, std::move(fn), std::move(op), input_bytes);
}
AsyncPoolStats AsyncPool::stats() const noexcept
{
AsyncPoolStats out;
if (!m_impl) return out;
std::lock_guard lk{m_impl->mu};
out.reader_connections = m_impl->readers.size();
out.queued_read_jobs = m_impl->read_queue.size();
out.queued_write_jobs = m_impl->write_queue.size();
out.active_read_jobs = m_impl->active_read_jobs;
out.active_write_jobs = m_impl->active_write_jobs;
out.pending_input_bytes = m_impl->pending_input_bytes;
out.completed_jobs = m_impl->completed_jobs.load(std::memory_order_relaxed);
out.rejected_jobs = m_impl->rejected_jobs.load(std::memory_order_relaxed);
out.cancelled_jobs = m_impl->cancelled_jobs.load(std::memory_order_relaxed);
return out;
}
Result<void> AsyncPool::close_and_join()
{
if (!m_impl) return {};
return m_impl->close_and_join();
}
} // namespace Void::Sqlite
+4
View File
@@ -0,0 +1,4 @@
void_add_module(SqliteAsync
INTERNAL_DEPS Sqlite Async Time Functional
EXTRA_HEADERS Void/Sqlite/AsyncPool.hpp
)
+272
View File
@@ -0,0 +1,272 @@
#include <Void/Storage/AsyncAdapter.hpp>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <thread>
#include <utility>
namespace Void::Storage
{
struct AsyncStorageAdapter::Impl {
struct WriteJob {
std::shared_ptr<Void::Async::OperationState<std::expected<CommitReceipt, WriteFailure>>> state{};
Batch batch{};
Durability durability{Durability::Sync};
std::size_t bytes{0};
};
Impl(Engine& eng, AsyncAdapterOptions opts, Void::Async::Executor* exec)
: engine(eng),
options(std::move(opts)),
clock(options.clock ? options.clock : &Void::Time::SystemMonotonicClock::instance()),
completion_executor(exec)
{
worker = std::thread([this]() { run_loop(); });
}
~Impl()
{
close_and_join();
}
void run_loop()
{
for (;;) {
WriteJob job;
{
std::unique_lock lk{mu};
cv.wait(lk, [this]() { return !queue.empty() || closing; });
if (queue.empty() && closing) {
return;
}
job = std::move(queue.front());
queue.pop_front();
pending_bytes -= job.bytes;
}
auto& st = job.state;
// Check stop / deadline BEFORE emitting WAL bytes.
if (st->stop_requested()) {
cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
std::expected<CommitReceipt, WriteFailure> wf = std::unexpected{WriteFailure{
StorageError{StorageErrorCode::interrupted,
make_storage_error(StorageErrorCode::interrupted,
"AsyncStorageAdapter: stopped before append")},
Outcome::NotCommitted}};
if (auto t = st->try_commit_value(std::move(wf)); t) {
t->dispatch();
}
st->release_backend_ref_and_dispatch();
continue;
}
if (st->is_deadline_expired(*clock)) {
cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
std::expected<CommitReceipt, WriteFailure> wf = std::unexpected{WriteFailure{
StorageError{StorageErrorCode::timeout,
make_storage_error(StorageErrorCode::timeout,
"AsyncStorageAdapter: deadline expired before append")},
Outcome::NotCommitted}};
if (auto t = st->try_commit_value(std::move(wf)); t) {
t->dispatch();
}
st->release_backend_ref_and_dispatch();
continue;
}
// Perform write: once append starts, external stop/deadline NEVER revokes
// a committed receipt or skips visibility publication!
auto wr = engine.write(std::move(job.batch), job.durability);
if (wr.has_value()) {
completed_writes.fetch_add(1, std::memory_order_relaxed);
} else if (wr.error().outcome == Outcome::Unknown) {
unknown_outcomes.fetch_add(1, std::memory_order_relaxed);
} else {
rejected_writes.fetch_add(1, std::memory_order_relaxed);
}
if (auto t = st->try_commit_value(std::move(wr)); t) {
t->dispatch();
}
st->release_backend_ref_and_dispatch();
}
}
void close_and_join()
{
{
std::lock_guard lk{mu};
if (closed) return;
closing = true;
}
cv.notify_all();
if (worker.joinable()) {
worker.join();
}
std::lock_guard lk{mu};
closed = true;
}
Engine& engine;
AsyncAdapterOptions options;
const Void::Time::MonotonicClock* clock;
Void::Async::Executor* completion_executor{nullptr};
mutable std::mutex mu{};
std::condition_variable cv{};
std::deque<WriteJob> queue{};
std::size_t pending_bytes{0};
bool closing{false};
bool closed{false};
std::thread worker{};
std::atomic<std::uint64_t> completed_writes{0};
std::atomic<std::uint64_t> rejected_writes{0};
std::atomic<std::uint64_t> unknown_outcomes{0};
std::atomic<std::uint64_t> cancelled_before_append{0};
};
AsyncStorageAdapter::AsyncStorageAdapter(
Engine& engine,
AsyncAdapterOptions options,
Void::Async::Executor* completion_executor)
: m_impl(std::make_shared<Impl>(engine, std::move(options), completion_executor))
{
}
AsyncStorageAdapter::~AsyncStorageAdapter()
{
close_and_join();
}
Void::Coro::Task<std::expected<CommitReceipt, WriteFailure>>
AsyncStorageAdapter::write_async(
Batch batch,
Durability durability,
Void::Async::OperationOptions op)
{
if (op.stop.stop_requested()) {
m_impl->cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::interrupted,
make_storage_error(StorageErrorCode::interrupted,
"AsyncStorageAdapter: stopped before admission")},
Outcome::NotCommitted}};
}
if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) {
m_impl->cancelled_before_append.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::timeout,
make_storage_error(StorageErrorCode::timeout,
"AsyncStorageAdapter: deadline expired before admission")},
Outcome::NotCommitted}};
}
if (auto vb = batch.validate(m_impl->engine.limits()); !vb) {
m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed);
const auto code = static_cast<StorageErrorCode>(vb.error().code().value);
co_return std::unexpected{WriteFailure{
StorageError{code, std::move(vb).error()}, Outcome::NotCommitted}};
}
std::size_t batch_bytes = 0;
for (const auto& m : batch.mutations()) {
batch_bytes += m.key.size() + m.value.size();
}
auto state = Void::Async::OperationState<
std::expected<CommitReceipt, WriteFailure>>::create(
op, m_impl->completion_executor, Void::Async::StopBehavior::notify_only);
{
std::lock_guard lk{m_impl->mu};
if (m_impl->closing || m_impl->closed) {
m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::closed,
make_storage_error(StorageErrorCode::closed,
"AsyncStorageAdapter: closing")},
Outcome::NotCommitted}};
}
if (m_impl->queue.size() >= m_impl->options.max_pending_batches ||
batch_bytes > m_impl->options.max_pending_bytes ||
m_impl->pending_bytes > m_impl->options.max_pending_bytes - batch_bytes) {
m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed);
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::overloaded,
make_storage_error(StorageErrorCode::overloaded,
"AsyncStorageAdapter: pending queue overloaded")},
Outcome::NotCommitted}};
}
m_impl->pending_bytes += batch_bytes;
state->acquire_backend_ref();
m_impl->queue.push_back(Impl::WriteJob{
state, std::move(batch), durability, batch_bytes});
}
m_impl->cv.notify_one();
auto awaited = co_await state->awaitable(m_impl->completion_executor);
if (!awaited) {
co_return std::unexpected{WriteFailure{
StorageError{StorageErrorCode::io_error, std::move(awaited).error()},
Outcome::Unknown}};
}
co_return std::move(*awaited);
}
Void::Coro::Task<Result<OwnedValue>>
AsyncStorageAdapter::get_async(
ByteView key,
Void::Async::OperationOptions op)
{
if (op.stop.stop_requested()) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::interrupted, "AsyncStorageAdapter::get_async cancelled"));
}
if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::timeout, "AsyncStorageAdapter::get_async timed out"));
}
auto snap = m_impl->engine.snapshot();
if (!snap) co_return Void::Result::fail(std::move(snap).error());
co_return m_impl->engine.get(*snap, key);
}
Void::Coro::Task<Result<void>>
AsyncStorageAdapter::checkpoint_async(Void::Async::OperationOptions op)
{
if (op.stop.stop_requested()) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::interrupted, "AsyncStorageAdapter::checkpoint_async cancelled"));
}
if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) {
co_return Void::Result::fail(make_storage_error(
StorageErrorCode::timeout, "AsyncStorageAdapter::checkpoint_async timed out"));
}
co_return m_impl->engine.checkpoint();
}
AsyncAdapterStats AsyncStorageAdapter::stats() const noexcept
{
AsyncAdapterStats st;
if (!m_impl) return st;
std::lock_guard lk{m_impl->mu};
st.queued_writes = m_impl->queue.size();
st.pending_bytes = m_impl->pending_bytes;
st.completed_writes = m_impl->completed_writes.load(std::memory_order_relaxed);
st.rejected_writes = m_impl->rejected_writes.load(std::memory_order_relaxed);
st.unknown_outcomes = m_impl->unknown_outcomes.load(std::memory_order_relaxed);
st.cancelled_before_append =
m_impl->cancelled_before_append.load(std::memory_order_relaxed);
return st;
}
void AsyncStorageAdapter::close_and_join()
{
if (m_impl) {
m_impl->close_and_join();
}
}
} // namespace Void::Storage
+122
View File
@@ -0,0 +1,122 @@
#include <Void/Storage/Batch.hpp>
#include <set>
namespace Void::Storage
{
Batch& Batch::put(ByteView key, ByteView value)
{
Mutation m;
m.kind = MutationKind::Put;
m.key.assign(key.begin(), key.end());
m.value.assign(value.begin(), value.end());
m_mutations.push_back(std::move(m));
return *this;
}
Batch& Batch::erase(ByteView key)
{
Mutation m;
m.kind = MutationKind::Erase;
m.key.assign(key.begin(), key.end());
m_mutations.push_back(std::move(m));
return *this;
}
Batch& Batch::require_absent(ByteView key)
{
Precondition p;
p.kind = PreconditionKind::Absent;
p.key.assign(key.begin(), key.end());
m_preconditions.push_back(std::move(p));
return *this;
}
Batch& Batch::require_version(ByteView key, Sequence expected_version)
{
Precondition p;
p.kind = PreconditionKind::VersionEquals;
p.key.assign(key.begin(), key.end());
p.expected_version = expected_version;
m_preconditions.push_back(std::move(p));
return *this;
}
Batch& Batch::require_value(ByteView key, ByteView expected_value)
{
Precondition p;
p.kind = PreconditionKind::ValueEquals;
p.key.assign(key.begin(), key.end());
p.expected_value.assign(expected_value.begin(), expected_value.end());
m_preconditions.push_back(std::move(p));
return *this;
}
Result<void> Batch::validate(const Limits& limits) const
{
if (m_mutations.size() > limits.max_batch_mutations) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: mutation count exceeds max_batch_mutations"));
}
if (m_preconditions.size() > limits.max_batch_conditions) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: precondition count exceeds max_batch_conditions"));
}
std::set<ByteView, ByteLess> seen_mut_keys;
std::size_t total_op_bytes = 0;
for (const auto& m : m_mutations) {
if (m.key.size() > limits.max_key_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: mutation key exceeds max_key_bytes"));
}
if (m.value.size() > limits.max_value_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: mutation value exceeds max_value_bytes"));
}
if (m.kind == MutationKind::Erase && !m.value.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: erase mutation must have empty value"));
}
if (!seen_mut_keys.insert(ByteView{m.key}).second) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: duplicate mutation key in batch"));
}
const std::size_t pair_bytes = m.key.size() + m.value.size();
if (total_op_bytes > limits.max_batch_encoded_bytes - pair_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::quota_exceeded,
"Storage::Batch: mutation payload exceeds max_batch_encoded_bytes"));
}
total_op_bytes += pair_bytes;
}
std::set<ByteView, ByteLess> seen_cond_keys;
for (const auto& p : m_preconditions) {
if (p.key.size() > limits.max_key_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: precondition key exceeds max_key_bytes"));
}
if (p.expected_value.size() > limits.max_value_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: precondition expected_value exceeds max_value_bytes"));
}
if (!seen_cond_keys.insert(ByteView{p.key}).second) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"Storage::Batch: duplicate precondition for same key"));
}
}
return {};
}
} // namespace Void::Storage
File diff suppressed because it is too large. Load diff
+681
View File
@@ -0,0 +1,681 @@
#include <Void/Storage/FilePort.hpp>
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <format>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utility>
namespace Void::Storage
{
namespace
{
[[nodiscard]] StorageErrorCode map_errno(int err) noexcept
{
switch (err) {
case ENOENT:
return StorageErrorCode::not_found;
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
case EBUSY:
return StorageErrorCode::busy;
case EEXIST:
return StorageErrorCode::conflict;
case ENOSYS:
case EOPNOTSUPP:
#if ENOTSUP != EOPNOTSUPP
case ENOTSUP:
#endif
return StorageErrorCode::unsupported_capability;
case ENOSPC:
case EDQUOT:
return StorageErrorCode::quota_exceeded;
case EINVAL:
return StorageErrorCode::invalid_argument;
default:
return StorageErrorCode::io_error;
}
}
[[nodiscard]] Error errno_error(std::string_view op, const std::filesystem::path& p, int err)
{
return make_storage_error(
map_errno(err),
std::format("Storage: {} '{}' failed: {}", op, p.string(), std::strerror(err)),
std::error_code{err, std::generic_category()});
}
class PosixDirLock final : public DirLockHandle
{
public:
explicit PosixDirLock(int fd) noexcept : m_fd(fd) {}
~PosixDirLock() override
{
if (m_fd >= 0) {
::flock(m_fd, LOCK_UN);
::close(m_fd);
m_fd = -1;
}
}
private:
int m_fd{-1};
};
class PosixFileHandle final : public FileHandle
{
public:
PosixFileHandle(int fd, std::filesystem::path path, std::uint64_t initial_size) noexcept
: m_fd(fd), m_path(std::move(path)), m_append_pos(initial_size)
{
}
~PosixFileHandle() override
{
if (m_fd >= 0) {
::close(m_fd);
m_fd = -1;
}
}
Result<std::size_t> pread(std::uint64_t offset, std::span<std::byte> out) override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: pread on closed handle"));
}
std::size_t total = 0;
while (total < out.size()) {
const ssize_t n = ::pread(
m_fd,
out.data() + total,
out.size() - total,
static_cast<off_t>(offset + total));
if (n > 0) {
total += static_cast<std::size_t>(n);
} else if (n == 0) {
break;
} else if (errno == EINTR) {
continue;
} else {
return Void::Result::fail(errno_error("pread", m_path, errno));
}
}
return total;
}
Result<void> pread_exact(std::uint64_t offset, std::span<std::byte> out) override
{
auto r = pread(offset, out);
if (!r) return Void::Result::fail(std::move(r).error());
if (*r != out.size()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt,
std::format("Storage: short pread on '{}' at offset {} (wanted {}, got {})",
m_path.string(), offset, out.size(), *r)));
}
return {};
}
Result<void> pwrite_all(std::uint64_t offset, ByteView data) override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: pwrite_all on closed handle"));
}
std::size_t total = 0;
while (total < data.size()) {
const ssize_t n = ::pwrite(
m_fd,
data.data() + total,
data.size() - total,
static_cast<off_t>(offset + total));
if (n > 0) {
total += static_cast<std::size_t>(n);
} else if (n < 0 && errno == EINTR) {
continue;
} else {
const int err = (n < 0) ? errno : EIO;
return Void::Result::fail(errno_error("pwrite", m_path, err));
}
}
return {};
}
Result<std::uint64_t> append_all(ByteView data) override
{
std::lock_guard lk{m_mu};
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: append_all on closed handle"));
}
const std::uint64_t start = m_append_pos;
auto w = pwrite_all(start, data);
if (!w) {
// Refresh actual size from fstat so partial failures keep accurate EOF.
struct stat st {};
if (::fstat(m_fd, &st) == 0 && st.st_size >= 0) {
m_append_pos = static_cast<std::uint64_t>(st.st_size);
}
return Void::Result::fail(std::move(w).error());
}
m_append_pos = start + data.size();
return start;
}
Result<void> sync() override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: sync on closed handle"));
}
for (;;) {
if (::fsync(m_fd) == 0) {
return {};
}
if (errno == EINTR) {
continue;
}
return Void::Result::fail(errno_error("fsync", m_path, errno));
}
}
Result<void> truncate(std::uint64_t new_size) override
{
std::lock_guard lk{m_mu};
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: truncate on closed handle"));
}
for (;;) {
if (::ftruncate(m_fd, static_cast<off_t>(new_size)) == 0) {
m_append_pos = new_size;
return {};
}
if (errno == EINTR) {
continue;
}
return Void::Result::fail(errno_error("ftruncate", m_path, errno));
}
}
Result<std::uint64_t> size() const override
{
if (m_fd < 0) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::closed, "Storage: size on closed handle"));
}
struct stat st {};
if (::fstat(m_fd, &st) != 0) {
return Void::Result::fail(errno_error("fstat", m_path, errno));
}
return st.st_size >= 0 ? static_cast<std::uint64_t>(st.st_size) : 0ULL;
}
Result<void> close() override
{
std::lock_guard lk{m_mu};
if (m_fd < 0) {
return {};
}
const int rc = ::close(m_fd);
m_fd = -1;
if (rc != 0) {
return Void::Result::fail(errno_error("close", m_path, errno));
}
return {};
}
private:
mutable std::mutex m_mu{};
int m_fd{-1};
std::filesystem::path m_path{};
std::uint64_t m_append_pos{0};
};
class PosixFilePort final : public FilePort
{
public:
Result<void> ensure_dir(const std::filesystem::path& dir) override
{
std::error_code ec;
std::filesystem::create_directories(dir, ec);
if (ec) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::io_error,
std::format("Storage: create_directories '{}' failed: {}",
dir.string(), ec.message()),
ec));
}
return {};
}
Result<bool> exists(const std::filesystem::path& p) override
{
std::error_code ec;
const bool ex = std::filesystem::exists(p, ec);
if (ec) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::io_error,
std::format("Storage: exists '{}' failed: {}", p.string(), ec.message()),
ec));
}
return ex;
}
Result<std::uint64_t> file_size(const std::filesystem::path& p) override
{
struct stat st {};
if (::lstat(p.c_str(), &st) != 0) {
return Void::Result::fail(errno_error("lstat", p, errno));
}
if (!S_ISREG(st.st_mode)) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt,
std::format("Storage: '{}' is not a regular file", p.string())));
}
return st.st_size >= 0 ? static_cast<std::uint64_t>(st.st_size) : 0ULL;
}
Result<std::vector<std::string>> list_dir(const std::filesystem::path& dir) override
{
std::error_code ec;
std::vector<std::string> out;
for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) {
if (ec) break;
out.push_back(entry.path().filename().string());
}
if (ec) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::io_error,
std::format("Storage: list_dir '{}' failed: {}", dir.string(), ec.message()),
ec));
}
std::sort(out.begin(), out.end());
return out;
}
Result<std::unique_ptr<DirLockHandle>> lock_directory(
const std::filesystem::path& dir) override
{
const auto lock_path = dir / "LOCK";
const int fd = ::open(
lock_path.c_str(),
O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC,
0600);
if (fd < 0) {
return Void::Result::fail(errno_error("open lock", lock_path, errno));
}
if (::flock(fd, LOCK_EX | LOCK_NB) != 0) {
const int err = errno;
::close(fd);
return Void::Result::fail(errno_error("flock", lock_path, err));
}
return std::unique_ptr<DirLockHandle>{new PosixDirLock{fd}};
}
Result<std::unique_ptr<FileHandle>> open_file(
const std::filesystem::path& p,
FileOpenMode mode) override
{
int flags = O_NOFOLLOW | O_CLOEXEC;
switch (mode) {
case FileOpenMode::ReadOnly:
flags |= O_RDONLY;
break;
case FileOpenMode::ReadWriteExisting:
flags |= O_RDWR;
break;
case FileOpenMode::CreateNew:
flags |= O_RDWR | O_CREAT | O_EXCL;
break;
case FileOpenMode::CreateOrOpen:
flags |= O_RDWR | O_CREAT;
break;
}
const int fd = ::open(p.c_str(), flags, 0600);
if (fd < 0) {
return Void::Result::fail(errno_error("open", p, errno));
}
struct stat st {};
if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
const int err = S_ISREG(st.st_mode) ? errno : EINVAL;
::close(fd);
return Void::Result::fail(errno_error("fstat", p, err));
}
const std::uint64_t sz =
st.st_size >= 0 ? static_cast<std::uint64_t>(st.st_size) : 0ULL;
return std::unique_ptr<FileHandle>{new PosixFileHandle{fd, p, sz}};
}
Result<void> rename_atomic(
const std::filesystem::path& from,
const std::filesystem::path& to) override
{
if (::rename(from.c_str(), to.c_str()) != 0) {
return Void::Result::fail(errno_error("rename", to, errno));
}
return {};
}
Result<void> unlink_file(const std::filesystem::path& p) override
{
if (::unlink(p.c_str()) != 0) {
return Void::Result::fail(errno_error("unlink", p, errno));
}
return {};
}
Result<void> sync_dir(const std::filesystem::path& dir) override
{
const int fd = ::open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd < 0) {
return Void::Result::fail(errno_error("open dir", dir, errno));
}
int rc = 0;
int saved_errno = 0;
for (;;) {
rc = ::fsync(fd);
if (rc == 0) break;
if (errno == EINTR) continue;
saved_errno = errno;
break;
}
::close(fd);
if (rc != 0) {
return Void::Result::fail(errno_error("fsync dir", dir, saved_errno));
}
return {};
}
Result<void> probe_durability_capabilities(
const std::filesystem::path& dir) override
{
const auto p_tmp = dir / std::format(".void-probe-{}.tmp", ::getpid());
const auto p_dst = dir / std::format(".void-probe-{}.dst", ::getpid());
(void)::unlink(p_tmp.c_str());
(void)::unlink(p_dst.c_str());
auto f = open_file(p_tmp, FileOpenMode::CreateOrOpen);
if (!f) return Void::Result::fail(std::move(f).error());
const std::byte one{0x5Au};
if (auto w = (*f)->append_all(ByteView{&one, 1}); !w) {
(void)::unlink(p_tmp.c_str());
return Void::Result::fail(std::move(w).error());
}
if (auto s = (*f)->sync(); !s) {
(void)::unlink(p_tmp.c_str());
return s;
}
(void)(*f)->close();
if (auto r = rename_atomic(p_tmp, p_dst); !r) {
(void)::unlink(p_tmp.c_str());
(void)::unlink(p_dst.c_str());
return r;
}
auto sd = sync_dir(dir);
(void)::unlink(p_dst.c_str());
if (!sd) return sd;
return sync_dir(dir);
}
};
} // namespace
std::shared_ptr<FilePort> make_posix_file_port()
{
return std::make_shared<PosixFilePort>();
}
class FaultFileHandle final : public FileHandle
{
public:
FaultFileHandle(
FaultInjectingFilePort* owner,
std::unique_ptr<FileHandle> inner,
std::string path) noexcept
: m_owner(owner), m_inner(std::move(inner)), m_path(std::move(path))
{
}
Result<std::size_t> pread(std::uint64_t offset, std::span<std::byte> out) override
{
return m_inner->pread(offset, out);
}
Result<void> pread_exact(std::uint64_t offset, std::span<std::byte> out) override
{
return m_inner->pread_exact(offset, out);
}
Result<void> pwrite_all(std::uint64_t offset, ByteView data) override
{
const auto mf = m_owner->check_fault(FaultOp::PWrite, m_path);
if (mf.triggered) {
if (mf.partial_write_bytes.has_value() && *mf.partial_write_bytes > 0) {
const std::size_t n = std::min(*mf.partial_write_bytes, data.size());
(void)m_inner->pwrite_all(offset, data.subspan(0, n));
}
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected pwrite fault on '{}'", m_path)));
}
return m_inner->pwrite_all(offset, data);
}
Result<std::uint64_t> append_all(ByteView data) override
{
const auto mf = m_owner->check_fault(FaultOp::AppendWrite, m_path);
if (mf.triggered) {
if (mf.partial_write_bytes.has_value() && *mf.partial_write_bytes > 0) {
const std::size_t n = std::min(*mf.partial_write_bytes, data.size());
(void)m_inner->append_all(data.subspan(0, n));
}
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected append fault on '{}'", m_path)));
}
return m_inner->append_all(data);
}
Result<void> sync() override
{
m_owner->maybe_run_sync_hook();
const auto mf = m_owner->check_fault(FaultOp::SyncFile, m_path);
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected fsync fault on '{}'", m_path)));
}
return m_inner->sync();
}
Result<void> truncate(std::uint64_t new_size) override
{
const auto mf = m_owner->check_fault(FaultOp::Truncate, m_path);
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected truncate fault on '{}'", m_path)));
}
return m_inner->truncate(new_size);
}
Result<std::uint64_t> size() const override
{
return m_inner->size();
}
Result<void> close() override
{
return m_inner->close();
}
private:
FaultInjectingFilePort* m_owner;
std::unique_ptr<FileHandle> m_inner;
std::string m_path;
};
FaultInjectingFilePort::FaultInjectingFilePort(std::shared_ptr<FilePort> delegate)
: delegate_(delegate ? std::move(delegate) : make_posix_file_port())
{
}
void FaultInjectingFilePort::add_rule(FaultRule rule)
{
std::lock_guard lk{mu_};
rules_.push_back(std::move(rule));
}
void FaultInjectingFilePort::clear_rules()
{
std::lock_guard lk{mu_};
rules_.clear();
}
void FaultInjectingFilePort::set_pause_before_sync(std::function<void()> hook)
{
std::lock_guard lk{mu_};
pause_before_sync_ = std::move(hook);
}
std::uint64_t FaultInjectingFilePort::op_count(FaultOp op) const noexcept
{
std::lock_guard lk{mu_};
return op_counts_[static_cast<std::size_t>(op)];
}
FaultInjectingFilePort::MatchedFault FaultInjectingFilePort::check_fault(
FaultOp op,
const std::string& path)
{
std::lock_guard lk{mu_};
++op_counts_[static_cast<std::size_t>(op)];
for (auto& r : rules_) {
if (r.consumed || r.op != op) continue;
if (!r.path_contains.empty() && path.find(r.path_contains) == std::string::npos) {
continue;
}
++r.match_count;
if (r.hit_index == 0 || r.match_count == r.hit_index) {
if (r.hit_index != 0) {
r.consumed = true;
}
return MatchedFault{r.error_code, r.partial_write_bytes, true};
}
}
return {};
}
void FaultInjectingFilePort::maybe_run_sync_hook()
{
std::function<void()> cb;
{
std::lock_guard lk{mu_};
cb = pause_before_sync_;
}
if (cb) {
cb();
}
}
Result<void> FaultInjectingFilePort::ensure_dir(const std::filesystem::path& dir)
{
return delegate_->ensure_dir(dir);
}
Result<bool> FaultInjectingFilePort::exists(const std::filesystem::path& p)
{
return delegate_->exists(p);
}
Result<std::uint64_t> FaultInjectingFilePort::file_size(const std::filesystem::path& p)
{
return delegate_->file_size(p);
}
Result<std::vector<std::string>> FaultInjectingFilePort::list_dir(const std::filesystem::path& dir)
{
return delegate_->list_dir(dir);
}
Result<std::unique_ptr<DirLockHandle>> FaultInjectingFilePort::lock_directory(
const std::filesystem::path& dir)
{
const auto mf = check_fault(FaultOp::LockDir, dir.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code, "Storage: injected directory lock fault"));
}
return delegate_->lock_directory(dir);
}
Result<std::unique_ptr<FileHandle>> FaultInjectingFilePort::open_file(
const std::filesystem::path& p,
FileOpenMode mode)
{
const auto mf = check_fault(FaultOp::OpenFile, p.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected open_file fault on '{}'", p.string())));
}
auto h = delegate_->open_file(p, mode);
if (!h) return Void::Result::fail(std::move(h).error());
return std::unique_ptr<FileHandle>{
new FaultFileHandle{this, std::move(*h), p.string()}};
}
Result<void> FaultInjectingFilePort::rename_atomic(
const std::filesystem::path& from,
const std::filesystem::path& to)
{
const auto mf = check_fault(FaultOp::Rename, to.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected rename fault to '{}'", to.string())));
}
return delegate_->rename_atomic(from, to);
}
Result<void> FaultInjectingFilePort::unlink_file(const std::filesystem::path& p)
{
const auto mf = check_fault(FaultOp::Unlink, p.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected unlink fault on '{}'", p.string())));
}
return delegate_->unlink_file(p);
}
Result<void> FaultInjectingFilePort::sync_dir(const std::filesystem::path& dir)
{
const auto mf = check_fault(FaultOp::SyncDir, dir.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code,
std::format("Storage: injected sync_dir fault on '{}'", dir.string())));
}
return delegate_->sync_dir(dir);
}
Result<void> FaultInjectingFilePort::probe_durability_capabilities(
const std::filesystem::path& dir)
{
const auto mf = check_fault(FaultOp::ProbeDurability, dir.string());
if (mf.triggered) {
return Void::Result::fail(make_storage_error(
mf.error_code, "Storage: injected probe durability fault"));
}
return delegate_->probe_durability_capabilities(dir);
}
} // namespace Void::Storage
File diff suppressed because it is too large. Load diff
+98
View File
@@ -0,0 +1,98 @@
#pragma once
#include <Void/Storage/FilePort.hpp>
#include <Void/Storage/Format.hpp>
#include <filesystem>
#include <memory>
#include <mutex>
#include <vector>
namespace Void::Storage::detail
{
class TableReader final
{
public:
[[nodiscard]] static Result<std::shared_ptr<TableReader>> open(
std::shared_ptr<FilePort> port,
std::filesystem::path path,
Void::Uuid::Uuid expected_uuid,
const TableMeta& meta,
const Limits& limits);
[[nodiscard]] const TableMeta& meta() const noexcept { return m_meta; }
[[nodiscard]] const std::filesystem::path& path() const noexcept { return m_path; }
[[nodiscard]] const std::vector<TableBlockIndexEntry>& index() const noexcept
{
return m_index;
}
/// Lookup highest version <= snap_seq for exact `key`.
/// Returns std::nullopt if `key` is absent at <= snap_seq in this table;
/// returns TableEntryRecord{key, seq, erased, value} if present (including tombstone).
[[nodiscard]] Result<std::optional<TableEntryRecord>> lookup(
ByteView key,
Sequence snap_seq) const;
/// Read and decode block `block_idx` while verifying its CRC32C.
[[nodiscard]] Result<std::vector<TableEntryRecord>> read_block(
std::size_t block_idx) const;
/// Verify every block's CRC32C, key ordering, AND full-file CRC32C.
[[nodiscard]] Result<std::uint64_t> verify_all_blocks_and_file_crc() const;
private:
TableReader() = default;
std::shared_ptr<FilePort> m_port{};
std::filesystem::path m_path{};
TableMeta m_meta{};
TableHeader m_header{};
TableFooter m_footer{};
Limits m_limits{};
std::vector<TableBlockIndexEntry> m_index{};
mutable std::mutex m_handle_mu{};
mutable std::unique_ptr<FileHandle> m_cached_handle{};
};
[[nodiscard]] Result<TableMeta> write_sorted_table(
FilePort& port,
const std::filesystem::path& tmp_path,
const std::filesystem::path& final_path,
Void::Uuid::Uuid db_uuid,
std::uint64_t table_id,
std::uint32_t level,
const std::vector<TableEntryRecord>& sorted_entries,
const Limits& limits);
/// Validate and replay a WAL segment, filling `recovered_batches` with valid committed batches.
struct WalRecoveredBatch {
Sequence sequence{0};
std::vector<TableEntryRecord> entries{};
};
struct WalSegmentScanResult {
WalSegmentHeader header{};
std::vector<WalRecoveredBatch> batches{};
std::uint64_t file_size{0};
std::optional<std::uint64_t> truncate_offset{};
};
[[nodiscard]] Result<WalSegmentScanResult> scan_wal_segment(
FilePort& port,
const std::filesystem::path& path,
Void::Uuid::Uuid expected_uuid,
std::uint64_t expected_seg_id,
std::optional<std::uint64_t> expected_prev_seg_id,
bool is_final_active_segment,
const Limits& limits,
bool allow_uncommitted_tail = true);
/// Salvage scan: recovers as many valid complete committed batches as possible before stopping.
[[nodiscard]] Result<WalSegmentScanResult> salvage_wal_segment(
FilePort& port,
const std::filesystem::path& path,
Void::Uuid::Uuid expected_uuid,
const Limits& limits);
} // namespace Void::Storage::detail
+327
View File
@@ -0,0 +1,327 @@
#include <Void/Core/Uuid.hpp>
#include <Void/Storage/Engine.hpp>
#include <Void/Storage/Format.hpp>
#include <Void/Storage/Tools.hpp>
#include "TableInternal.hpp"
#include <algorithm>
#include <format>
#include <limits>
#include <map>
#include <vector>
namespace Void::Storage
{
namespace
{
[[nodiscard]] Result<OwnedBytes> read_entire_file(
FilePort& port,
const std::filesystem::path& path,
std::size_t max_bytes)
{
auto sz_r = port.file_size(path);
if (!sz_r) return Void::Result::fail(std::move(sz_r).error());
if (*sz_r > max_bytes) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt,
std::format("Storage tool: '{}' size {} exceeds bound {}",
path.string(), *sz_r, max_bytes)));
}
OwnedBytes out(*sz_r);
auto f = port.open_file(path, FileOpenMode::ReadOnly);
if (!f) return Void::Result::fail(std::move(f).error());
if (*sz_r > 0) {
if (auto r = (*f)->pread_exact(0, out); !r) {
return Void::Result::fail(std::move(r).error());
}
}
return out;
}
} // namespace
Result<VerifyReport> verify_directory(
const std::filesystem::path& directory,
const Limits& limits,
std::shared_ptr<FilePort> port)
{
if (directory.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument, "verify_directory: empty directory"));
}
if (auto vl = validate_limits(limits); !vl) {
return Void::Result::fail(std::move(vl).error());
}
if (!port) port = make_posix_file_port();
auto cur_bytes = read_entire_file(*port, directory / "CURRENT", 512);
if (!cur_bytes) return Void::Result::fail(std::move(cur_bytes).error());
auto cur = decode_current(*cur_bytes);
if (!cur) return Void::Result::fail(std::move(cur).error());
auto man_bytes = read_entire_file(
*port, directory / cur->manifest_filename, limits.max_manifest_bytes);
if (!man_bytes) return Void::Result::fail(std::move(man_bytes).error());
auto man = decode_manifest(
*man_bytes, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes);
if (!man) return Void::Result::fail(std::move(man).error());
if (man->database_uuid != cur->database_uuid || man->generation != cur->generation) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::corrupt, "verify_directory: manifest mismatches CURRENT"));
}
VerifyReport report;
report.manifest_generation = man->generation;
report.checkpoint_sequence = man->checkpoint_sequence;
for (const auto& tm : man->tables) {
auto tr = detail::TableReader::open(
port,
directory / make_table_filename(tm.table_id),
man->database_uuid,
tm,
limits);
if (!tr) return Void::Result::fail(std::move(tr).error());
auto blks = (*tr)->verify_all_blocks_and_file_crc();
if (!blks) return Void::Result::fail(std::move(blks).error());
++report.tables_verified;
report.blocks_verified += *blks;
}
for (std::size_t i = 0; i < man->wal_segments.size(); ++i) {
const auto seg_id = man->wal_segments[i];
const bool is_final = (i + 1 == man->wal_segments.size());
const std::optional<std::uint64_t> exp_prev =
(i > 0) ? std::optional<std::uint64_t>{man->wal_segments[i - 1]}
: (seg_id == 1 ? std::optional<std::uint64_t>{0} : std::nullopt);
auto scan = detail::scan_wal_segment(
*port,
directory / make_wal_filename(seg_id),
man->database_uuid,
seg_id,
exp_prev,
is_final,
limits,
true);
if (!scan) return Void::Result::fail(std::move(scan).error());
++report.wal_segments_verified;
report.wal_batches_verified += scan->batches.size();
}
return report;
}
Result<void> restore_backup(
const std::filesystem::path& backup_dir,
const std::filesystem::path& destination,
const Limits& limits,
std::shared_ptr<FilePort> port)
{
if (backup_dir.empty() || destination.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument, "restore_backup: empty path"));
}
if (!port) port = make_posix_file_port();
std::error_code ec;
if (std::filesystem::exists(destination, ec) &&
std::filesystem::equivalent(backup_dir, destination, ec)) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"restore_backup: source and destination cannot be identical"));
}
auto vr = verify_directory(backup_dir, limits, port);
if (!vr) return Void::Result::fail(std::move(vr).error());
if (auto ed = port->ensure_dir(destination); !ed) return ed;
auto lock = port->lock_directory(destination);
if (!lock) return Void::Result::fail(std::move(lock).error());
auto cur_bytes = read_entire_file(*port, backup_dir / "CURRENT", 512);
if (!cur_bytes) return Void::Result::fail(std::move(cur_bytes).error());
auto cur = decode_current(*cur_bytes);
if (!cur) return Void::Result::fail(std::move(cur).error());
auto man_bytes = read_entire_file(
*port, backup_dir / cur->manifest_filename, limits.max_manifest_bytes);
if (!man_bytes) return Void::Result::fail(std::move(man_bytes).error());
auto man = decode_manifest(
*man_bytes, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes);
if (!man) return Void::Result::fail(std::move(man).error());
auto copy_file = [&](const std::string& name) -> Result<void> {
const auto src = backup_dir / name;
const auto dst = destination / name;
const auto dst_tmp = destination / (name + ".tmp");
auto sz = port->file_size(src);
if (!sz) return Void::Result::fail(std::move(sz).error());
OwnedBytes buf(*sz);
auto sf = port->open_file(src, FileOpenMode::ReadOnly);
if (!sf) return Void::Result::fail(std::move(sf).error());
if (*sz > 0) {
if (auto r = (*sf)->pread_exact(0, buf); !r) return r;
}
(void)port->unlink_file(dst_tmp);
auto df = port->open_file(dst_tmp, FileOpenMode::CreateNew);
if (!df) return Void::Result::fail(std::move(df).error());
if (!buf.empty()) {
if (auto w = (*df)->append_all(buf); !w) return Void::Result::fail(std::move(w).error());
}
if (auto s = (*df)->sync(); !s) return s;
if (auto c = (*df)->close(); !c) return c;
return port->rename_atomic(dst_tmp, dst);
};
for (const auto& tm : man->tables) {
if (auto r = copy_file(make_table_filename(tm.table_id)); !r) return r;
}
for (const auto seg : man->wal_segments) {
if (auto r = copy_file(make_wal_filename(seg)); !r) return r;
}
if (auto r = copy_file(cur->manifest_filename); !r) return r;
if (auto r = copy_file("CURRENT"); !r) return r;
return port->sync_dir(destination);
}
Result<SalvageReport> salvage_directory(
const std::filesystem::path& source_dir,
const std::filesystem::path& destination_dir,
const Limits& limits,
std::shared_ptr<FilePort> port)
{
if (source_dir.empty() || destination_dir.empty()) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument, "salvage_directory: empty path"));
}
if (auto vl = validate_limits(limits); !vl) {
return Void::Result::fail(std::move(vl).error());
}
if (!port) port = make_posix_file_port();
std::error_code ec;
if (std::filesystem::exists(destination_dir, ec) &&
std::filesystem::equivalent(source_dir, destination_dir, ec)) {
return Void::Result::fail(make_storage_error(
StorageErrorCode::invalid_argument,
"salvage_directory: offline salvage must write into a distinct destination directory"));
}
// Collect latest committed/recoverable key states without mutating source_dir!
struct Val {
Sequence seq{0};
bool erased{false};
OwnedBytes bytes{};
};
std::map<OwnedBytes, Val, ByteLess> kv;
SalvageReport rep;
std::optional<Void::Uuid::Uuid> db_uuid;
std::vector<std::string> files;
if (auto fl = port->list_dir(source_dir); fl) {
files = std::move(*fl);
} else {
return Void::Result::fail(std::move(fl).error());
}
// Try CURRENT -> Manifest if intact, so valid checkpoint tables are recovered too.
if (auto ce = port->exists(source_dir / "CURRENT"); ce && *ce) {
auto cb = read_entire_file(*port, source_dir / "CURRENT", 512);
if (cb) {
if (auto cp = decode_current(*cb); cp) {
db_uuid = cp->database_uuid;
if (auto mb = read_entire_file(*port, source_dir / cp->manifest_filename, limits.max_manifest_bytes); mb) {
if (auto md = decode_manifest(*mb, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes); md) {
for (const auto& tm : md->tables) {
auto tr = detail::TableReader::open(
port, source_dir / make_table_filename(tm.table_id),
md->database_uuid, tm, limits);
if (!tr) continue;
for (std::size_t bi = 0; bi < (*tr)->index().size(); ++bi) {
auto blk = (*tr)->read_block(bi);
if (!blk) continue;
for (const auto& e : *blk) {
auto it = kv.find(e.key);
if (it == kv.end() || e.sequence > it->second.seq) {
kv[e.key] = Val{e.sequence, e.erased, e.value};
}
rep.highest_recovered_sequence =
std::max(rep.highest_recovered_sequence, e.sequence);
}
}
}
}
}
}
}
}
// Scan every WAL-*.vwal in lexicographic name order stopping at first damaged record.
for (const auto& fname : files) {
if (!fname.starts_with("WAL-") || !fname.ends_with(".vwal")) continue;
const auto wpath = source_dir / fname;
// Peek segment header for UUID if CURRENT/Manifest wasn't usable.
if (!db_uuid.has_value()) {
OwnedBytes hdr_b(kWalSegmentHeaderSize);
auto wf = port->open_file(wpath, FileOpenMode::ReadOnly);
if (wf && (*wf)->pread_exact(0, hdr_b).has_value()) {
if (auto dec = decode_wal_segment_header(hdr_b); dec) {
db_uuid = dec->database_uuid;
}
}
}
if (!db_uuid.has_value()) continue;
auto scan = detail::salvage_wal_segment(*port, wpath, *db_uuid, limits);
if (!scan) continue;
if (scan->truncate_offset.has_value()) {
rep.truncated_or_skipped_bytes += (scan->file_size - *scan->truncate_offset);
}
for (const auto& b : scan->batches) {
++rep.recovered_batches;
rep.highest_recovered_sequence =
std::max(rep.highest_recovered_sequence, b.sequence);
for (const auto& e : b.entries) {
auto it = kv.find(e.key);
if (it == kv.end() || e.sequence > it->second.seq) {
kv[e.key] = Val{e.sequence, e.erased, e.value};
}
}
}
}
// Materialize salvaged data into fresh destination directory preserving versions!
OpenOptions out_opts;
out_opts.directory = destination_dir;
out_opts.limits = limits;
out_opts.file_port = port;
out_opts.initial_sequence = rep.highest_recovered_sequence;
auto dest_eng = Engine::open(std::move(out_opts));
if (!dest_eng) return Void::Result::fail(std::move(dest_eng).error());
Batch batch;
std::size_t approx = 0;
for (const auto& [k, v] : kv) {
if (v.erased) {
++rep.tombstones_preserved;
continue;
}
++rep.keys_recovered;
if (batch.mutations().size() + 1 > limits.max_batch_mutations ||
approx + k.size() + v.bytes.size() + 128 > limits.max_batch_encoded_bytes) {
auto wr = dest_eng->write(std::move(batch), Durability::Sync);
if (!wr.has_value()) return Void::Result::fail(wr.error().cause.error);
batch = Batch{};
approx = 0;
}
batch.put(k, v.bytes);
approx += k.size() + v.bytes.size() + 64;
}
if (!batch.empty()) {
auto wr = dest_eng->write(std::move(batch), Durability::Sync);
if (!wr.has_value()) return Void::Result::fail(wr.error().cause.error);
}
if (auto cl = dest_eng->close(); !cl) return Void::Result::fail(std::move(cl).error());
return rep;
}
} // namespace Void::Storage
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Storage
INTERNAL_DEPS Core Functional Time Memory Binary IO Async
)
+59
View File
@@ -133,6 +133,9 @@ if(_all_generated)
if(TARGET OpenSSL::Crypto)
target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto)
endif()
if(TARGET SQLite3::SQLite3)
target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3)
endif()
add_test(NAME VoidTests COMMAND VoidTests)
@@ -249,4 +252,60 @@ if(TARGET VoidTests AND TARGET Void::Plugin)
)
add_dependencies(VoidTests VoidServicePluginV1 VoidServicePluginV2)
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()
+5 -2
View File
@@ -50,8 +50,11 @@ namespace
struct Work : State {
Task<StateKey> run()
{
auto& svc = service<VoidTest::ICalc>();
const int total = svc.accumulate(1);
auto svc = acquire_service<VoidTest::ICalc>();
if (!svc) {
co_return next<Work>();
}
const int total = (*svc)->accumulate(1);
if (total >= 500) {
co_return succeed(total);
}
@@ -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;
}
+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;
}
+78
View File
@@ -214,6 +214,84 @@ if(_has_update)
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_sqlite Sqlite Functional Time)
if(_has_sqlite)
run_consumer(SqliteOnly "${install_prefix}" "SqliteOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE)
endif()
has_modules(_has_sqlite_async SqliteAsync Sqlite Async Time Functional LogState)
if(_has_sqlite_async)
run_consumer(SqliteAsyncOnly "${install_prefix}" "SqliteAsyncOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE)
endif()
has_modules(_has_storage Storage Core Functional Time Memory Binary IO Async)
if(_has_storage)
run_consumer(StorageOnly "${install_prefix}" "StorageOnly" ${_no_external_deps})
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()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
+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,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidSqliteAsyncOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS SqliteAsync)
add_executable(void_sqlite_async_only_consumer main.cpp)
target_link_libraries(void_sqlite_async_only_consumer PRIVATE Void::SqliteAsync)
target_compile_features(void_sqlite_async_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME SqliteAsyncOnlyConsumer COMMAND void_sqlite_async_only_consumer)
+24
View File
@@ -0,0 +1,24 @@
#include <Void/Sqlite/AsyncPool.hpp>
#include <atomic>
#include <filesystem>
#include <string>
#include <unistd.h>
int main()
{
const auto dir = std::filesystem::temp_directory_path() /
("void-sqlite-async-pkg-" + std::to_string(::getpid()));
std::error_code ec;
std::filesystem::remove_all(dir, ec);
std::filesystem::create_directories(dir, ec);
Void::Sqlite::AsyncPoolOptions opts;
opts.path = dir / "pkg.db";
opts.reader_connections = 2;
auto pool = Void::Sqlite::AsyncPool::open(opts);
const bool ok = pool.has_value() && pool->stats().reader_connections == 2 &&
pool->close_and_join().has_value();
std::filesystem::remove_all(dir, ec);
return ok ? 0 : 1;
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidSqliteOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Sqlite)
add_executable(void_sqlite_only_consumer main.cpp)
target_link_libraries(void_sqlite_only_consumer PRIVATE Void::Sqlite)
target_compile_features(void_sqlite_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME SqliteOnlyConsumer COMMAND void_sqlite_only_consumer)
+19
View File
@@ -0,0 +1,19 @@
#include <Void/Sqlite/Sqlite.hpp>
int main()
{
Void::Sqlite::OpenOptions opts;
auto db = Void::Sqlite::open_database(":memory:", opts);
if (!db) return 1;
if (!db->exec("CREATE TABLE t(id INTEGER PRIMARY KEY)").has_value()) return 2;
auto tx = db->begin(Void::Sqlite::BeginMode::Immediate);
if (!tx) return 3;
auto st = db->prepare("INSERT INTO t(id) VALUES(?)");
if (!st) return 4;
if (!st->bind_checked(1, Void::Sqlite::ValueView{7}).has_value()) return 5;
if (!st->step().has_value()) return 6;
if (!st->finalize_checked().has_value()) return 7;
if (!tx->commit().has_value()) return 8;
if (!db->close().has_value()) return 9;
return 0;
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidStorageOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Storage)
add_executable(void_storage_only_consumer main.cpp)
target_link_libraries(void_storage_only_consumer PRIVATE Void::Storage)
target_compile_features(void_storage_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME StorageOnlyConsumer COMMAND void_storage_only_consumer)
+36
View File
@@ -0,0 +1,36 @@
#include <Void/Storage/Storage.hpp>
#include <filesystem>
#include <string>
#include <unistd.h>
int main()
{
if (Void::Storage::crc32c(std::string_view{"123456789"}) != 0xE3069283u) {
return 1;
}
const auto dir = std::filesystem::temp_directory_path() /
("void-storage-pkg-" + std::to_string(::getpid()));
std::error_code ec;
std::filesystem::remove_all(dir, ec);
Void::Storage::OpenOptions opts;
opts.directory = dir;
auto eng = Void::Storage::Engine::open(opts);
if (!eng) return 2;
Void::Storage::Batch b;
b.require_absent("hello").put("hello", "world");
auto wr = eng->write(std::move(b), Void::Storage::Durability::Sync);
if (!wr) return 3;
auto snap = eng->snapshot();
if (!snap) return 4;
auto val = eng->get(*snap, "hello");
const bool ok = val && val->as_string_view() == "world" && val->version == wr->sequence;
snap->reset();
const bool closed = eng->close().has_value();
std::filesystem::remove_all(dir, ec);
return (ok && closed) ? 0 : 5;
}
+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;
}
@@ -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());
}
File diff suppressed because it is too large. Load diff
+315
View File
@@ -0,0 +1,315 @@
#include <Void/Plugin/CAbi.h>
#include <Void/Plugin/CAbiAdapter.hpp>
#include <Void/Plugin/Host.hpp>
#include <Void/Plugin/Manager.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <cstring>
#include <filesystem>
#include <memory>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace Void::Plugin;
struct CabiCalcTable {
uint32_t (*version)(void_module_handle* h);
int32_t (*accumulate)(void_module_handle* h, int32_t delta);
};
const void_interface_id_v1 kCalcIfaceId{
{0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01}};
std::vector<std::uint8_t> encode_i32_le(std::int32_t v)
{
std::vector<std::uint8_t> out(4);
std::memcpy(out.data(), &v, 4);
return out;
}
std::int32_t decode_i32_le(const std::vector<std::uint8_t>& b)
{
std::int32_t v = 0;
if (b.size() >= 4) {
std::memcpy(&v, b.data(), 4);
}
return v;
}
} // namespace
#if defined(VOID_CABI_V1_PATH) && defined(VOID_CABI_V2_PATH) && \
__has_include(<dlfcn.h>)
Void::Testing::Test plugin_cabi_v1_to_v2_stateful_quiesce_and_reload()
{
PluginHostLimits limits{};
limits.allow_safe_dlclose = true;
CModuleHost host{limits};
auto id = host.load(VOID_CABI_V1_PATH);
Void::Testing::require(id.has_value());
Void::Testing::expect_eq(*id, std::string{"cabi.calc"});
auto g1 = host.acquire("cabi.calc");
Void::Testing::require(static_cast<bool>(g1));
const auto gen1 = g1.generation();
auto iface1 = g1.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable));
Void::Testing::require(iface1.has_value());
const auto* t1 = iface1->table<CabiCalcTable>();
Void::Testing::require(t1 != nullptr);
Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1});
// Run async op on V1 (kind=3 pins activity via host API, kind=2 sync).
auto op_sync = g1.run_async(2u, encode_i32_le(15));
Void::Testing::require(op_sync.has_value());
Void::Testing::expect_eq(decode_i32_le(*op_sync), 15);
auto op_async = g1.run_async(3u, encode_i32_le(25));
Void::Testing::require(op_async.has_value());
Void::Testing::expect_eq(decode_i32_le(*op_async), 40);
// Reload V1 -> V2 while g1 + iface1 are still pinned!
auto gen2_res =
host.replace("cabi.calc", VOID_CABI_V2_PATH, {}, gen1);
Void::Testing::require(gen2_res.has_value());
Void::Testing::expect(*gen2_res > gen1);
// Old generation stays mapped & live until both leases drop.
auto retained_mid = host.retained_generations("cabi.calc");
Void::Testing::expect_eq(retained_mid.size(), std::size_t{2});
// Acquire V2 interface and confirm checkpoint migrated 40 -> V2.
auto g2 = host.acquire("cabi.calc");
Void::Testing::require(static_cast<bool>(g2));
auto iface2 = g2.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable));
Void::Testing::require(iface2.has_value());
const auto* t2 = iface2->table<CabiCalcTable>();
Void::Testing::expect_eq(t2->version(nullptr), std::uint32_t{2});
auto op2 = g2.run_async(1u, encode_i32_le(5));
// V2 does not implement async ops -> UNSUPPORTED mapped to abi_mismatch.
Void::Testing::expect(!op2.has_value());
// Old iface1/g1 still pinned; V1 sees quiesced mutation return -1.
Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1});
// Drop all pins to gen1 and verify host retirement thread dlcloses gen1.
iface1 = InterfaceLease{};
g1 = GenerationLease{};
for (int i = 0; i < 100; ++i) {
if (host.retained_generations("cabi.calc").size() == 1) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
Void::Testing::expect_eq(host.retained_generations("cabi.calc").size(),
std::size_t{1});
}
Void::Testing::Test plugin_cabi_async_cancel_and_safe_dlclose_wait()
{
PluginHostLimits limits{};
limits.allow_safe_dlclose = true;
CModuleHost host{limits};
Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value());
auto lease = host.acquire("cabi.calc");
ActivityPin extra_pin = lease.acquire_activity_pin();
std::stop_source ss;
std::thread canceller([&] {
std::this_thread::sleep_for(std::chrono::milliseconds{2});
ss.request_stop();
});
Void::Async::OperationOptions opts;
opts.stop = ss.get_token();
auto res = lease.run_async(1u, encode_i32_le(1), opts);
canceller.join();
Void::Testing::expect(!res.has_value());
Void::Testing::expect_eq(
res.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::cancelled));
// Unload while extra_pin + lease still exist -> cannot destroy/dlclose yet.
Void::Testing::require(host.unload("cabi.calc").has_value());
lease = GenerationLease{};
std::this_thread::sleep_for(std::chrono::milliseconds{10});
extra_pin = ActivityPin{};
host.close_and_join();
}
Void::Testing::Test plugin_cabi_bad_abi_oversized_ckpt_and_resume_degraded()
{
CModuleHost host{PluginHostLimits{.allow_safe_dlclose = true}};
for (const char* bad_path :
{VOID_CABI_BAD_TRUNC_PATH, VOID_CABI_BAD_MAJOR_PATH,
VOID_CABI_BAD_RESERVED_PATH}) {
auto r = host.load(bad_path);
Void::Testing::expect(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::abi_mismatch));
}
// Prepublication V2 readiness failure resumes V1 cleanly.
Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value());
auto fail_v2 =
host.replace("cabi.calc", VOID_CABI_V2_PATH, "not_ready");
Void::Testing::expect(!fail_v2.has_value());
auto after = host.acquire("cabi.calc");
Void::Testing::expect(after.health() == GenerationHealth::Healthy);
Void::Testing::expect_eq(after.version(), std::string_view{"1.0.0"});
// Reload into V1 with quiesce_fail_resume_fail -> failed reload leaves old
// generation marked Degraded.
Void::Testing::require(
host.replace("cabi.calc", VOID_CABI_V1_PATH,
"quiesce_fail_resume_fail")
.has_value());
auto deg_attempt = host.replace("cabi.calc", VOID_CABI_V2_PATH);
Void::Testing::expect(!deg_attempt.has_value());
Void::Testing::expect_eq(
deg_attempt.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::resume_degraded));
Void::Testing::expect(host.acquire("cabi.calc").health() ==
GenerationHealth::Degraded);
Void::Testing::require(host.unload("cabi.calc").has_value());
// Oversized checkpoint rejected without crashing or leaking.
Void::Testing::require(
host.load(VOID_CABI_V1_PATH, "ckpt_oversized").has_value());
auto ov = host.replace("cabi.calc", VOID_CABI_V2_PATH);
Void::Testing::expect(!ov.has_value());
Void::Testing::expect_eq(
ov.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::budget_exceeded));
}
Void::Testing::Test plugin_cabi_retention_byte_budget_and_dep_batch()
{
// 4-generation retention cap + byte budget.
PluginHostLimits limits{};
limits.allow_safe_dlclose = true;
limits.max_retained_generations = 4;
CModuleHost host{limits};
Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value());
std::vector<GenerationLease> pins;
for (int i = 0; i < 3; ++i) {
pins.push_back(host.acquire("cabi.calc"));
auto next = host.replace("cabi.calc", VOID_CABI_V1_PATH);
Void::Testing::require(next.has_value());
}
pins.push_back(host.acquire("cabi.calc"));
// Now 4 distinct generations are pinned -> 5th replace fails retention_limit.
auto cap_fail = host.replace("cabi.calc", VOID_CABI_V2_PATH);
Void::Testing::expect(!cap_fail.has_value());
Void::Testing::expect_eq(
cap_fail.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::retention_limit));
Void::Testing::expect(host.mapped_bytes("cabi.calc") > 0);
pins.clear();
// Byte budget rejection.
PluginHostLimits tiny_mem{};
tiny_mem.max_mapped_bytes_per_module = 1024;
CModuleHost tight{tiny_mem};
auto too_big = tight.load(VOID_CABI_V1_PATH);
Void::Testing::expect(!too_big.has_value());
Void::Testing::expect_eq(
too_big.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::budget_exceeded));
// Dependency batch: B depends on A (supplied out of order) -> A sorted first.
CModuleHost batch_host;
auto batch_ok = batch_host.load_batch(
{{.path = VOID_CABI_DEP_B_PATH}, {.path = VOID_CABI_DEP_A_PATH}});
Void::Testing::require(batch_ok.has_value());
Void::Testing::expect_eq(batch_ok->size(), std::size_t{2});
Void::Testing::expect_eq((*batch_ok)[0], std::string{"cabi.dep.a"});
Void::Testing::expect_eq((*batch_ok)[1], std::string{"cabi.dep.b"});
// RestartRequired policy refuses live upgrade.
auto rr = batch_host.replace("cabi.dep.a", VOID_CABI_DEP_A_PATH);
Void::Testing::expect(!rr.has_value());
Void::Testing::expect_eq(
rr.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::restart_required));
// Cycle in batch rejected before activating anything.
CModuleHost cyc_host;
auto cyc_res = cyc_host.load_batch(
{{.path = VOID_CABI_CYC_A_PATH}, {.path = VOID_CABI_CYC_B_PATH}});
Void::Testing::expect(!cyc_res.has_value());
Void::Testing::expect_eq(
cyc_res.error().code().value,
static_cast<std::int32_t>(PluginErrorCode::cycle_detected));
}
Void::Testing::Test plugin_cpp_adapter_contains_exceptions_and_manager_unlocks()
{
struct ThrowingModule final : Void::Plugin::IModule {
std::string_view name() const noexcept override { return "throw"; }
Void::Result::Result<void> activate(Void::Plugin::ModuleHost&) override
{
throw std::runtime_error("boom");
}
Void::Json::Value checkpoint() const override
{
throw std::runtime_error("ckpt-boom");
}
};
Void::Plugin::CModuleAdapterBox box{.module = std::make_unique<ThrowingModule>()};
void_error_detail_v1 err{};
err.struct_size = sizeof(err);
Void::Testing::expect_eq(Void::Plugin::adapt_activate(&box, &err),
static_cast<std::int32_t>(VOID_STATUS_INTERNAL));
if (err.release != nullptr && err.message != nullptr) {
Void::Testing::expect_eq(std::string_view{err.message},
std::string_view{"boom"});
err.release(err.release_ctx, err.message);
}
void_owned_bytes_v1 ck{};
void_error_detail_v1 err2{};
err2.struct_size = sizeof(err2);
Void::Testing::expect_eq(Void::Plugin::adapt_checkpoint(&box, &ck, &err2),
static_cast<std::int32_t>(VOID_STATUS_INTERNAL));
if (err2.release != nullptr && err2.message != nullptr) {
err2.release(err2.release_ctx, err2.message);
}
// Reentrant candidate/instance validator in PluginManager must NOT deadlock
// on m_mutex.
#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH)
PluginManager* mgr_ptr = nullptr;
PluginManager mgr{{
.instance_validator = [&](IPlugin&, const PluginInfo&) {
auto current = mgr_ptr->acquire("StatefulPlugin");
auto all_names = mgr_ptr->names();
return all_names.empty() || static_cast<bool>(current);
},
.candidate_validator = [&](const PluginHandle&) {
auto current = mgr_ptr->acquire("StatefulPlugin");
return static_cast<bool>(current) || mgr_ptr->names().empty();
},
}};
mgr_ptr = &mgr;
Void::Testing::require(mgr.load(VOID_STATEFUL_V1_PATH).has_value());
Void::Testing::require(
mgr.replace("StatefulPlugin", VOID_STATEFUL_V2_PATH).has_value());
#endif
}
#endif // C ABI fixtures available
@@ -0,0 +1,451 @@
#include <Void/Service/Registry.hpp>
#include <Void/Service/Service.hpp>
#include <Void/Service/Types.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>
#include <typeindex>
#include <vector>
namespace
{
using Void::Service::ExpectedEpoch;
using Void::Service::IManagedService;
using Void::Service::IService;
using Void::Service::ProviderSet;
using Void::Service::ServiceErrorCode;
using Void::Service::ServiceLimits;
using Void::Service::ServiceRegistry;
using Void::Time::ManualClock;
struct IA {
virtual ~IA() = default;
[[nodiscard]] virtual int id() const = 0;
};
struct IB {
virtual ~IB() = default;
[[nodiscard]] virtual int tag() const = 0;
};
struct IC {
virtual ~IC() = default;
[[nodiscard]] virtual int rank() const = 0;
};
class TrackedService final : public IManagedService, public IA
{
public:
TrackedService(std::string name, int val,
std::vector<std::string>* log,
bool fail_start = false,
bool fail_ready = false,
bool throw_stop = false)
: m_name(std::move(name)), m_val(val), m_log(log),
m_fail_start(fail_start), m_fail_ready(fail_ready),
m_throw_stop(throw_stop)
{
}
[[nodiscard]] std::string_view service_name() const override
{
return m_name;
}
[[nodiscard]] int id() const override { return m_val; }
[[nodiscard]] Void::Result::Result<void> start_checked() override
{
if (m_log != nullptr) {
m_log->push_back("start:" + m_name);
}
if (m_fail_start) {
return Void::Result::fail(Void::Service::make_service_error(
ServiceErrorCode::start_failed,
"start failed for " + m_name));
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
check_readiness() const override
{
if (m_fail_ready) {
return Void::Result::fail(Void::Service::make_service_error(
ServiceErrorCode::not_ready,
"not ready: " + m_name));
}
return {};
}
void abort_start() noexcept override
{
if (m_log != nullptr) {
m_log->push_back("abort:" + m_name);
}
}
[[nodiscard]] Void::Result::Result<void> stop_checked() override
{
if (m_log != nullptr) {
m_log->push_back("stop:" + m_name);
}
if (m_throw_stop) {
return Void::Result::fail(Void::Service::make_service_error(
ServiceErrorCode::stop_failed,
"stop boom: " + m_name));
}
return {};
}
private:
std::string m_name;
int m_val;
std::vector<std::string>* m_log;
bool m_fail_start;
bool m_fail_ready;
bool m_throw_stop;
};
class DualInterfaceService final : public IManagedService, public IA, public IB
{
public:
explicit DualInterfaceService(std::vector<std::string>* log)
: m_log(log)
{
}
[[nodiscard]] std::string_view service_name() const override
{
return "Dual";
}
[[nodiscard]] int id() const override { return 10; }
[[nodiscard]] int tag() const override { return 20; }
[[nodiscard]] Void::Result::Result<void> start_checked() override
{
++starts;
if (m_log != nullptr) m_log->push_back("dual:start");
return {};
}
[[nodiscard]] Void::Result::Result<void> stop_checked() override
{
++stops;
if (m_log != nullptr) m_log->push_back("dual:stop");
return {};
}
int starts{0};
int stops{0};
std::vector<std::string>* m_log;
};
class ReentrantDtorProvider final : public IA
{
public:
ReentrantDtorProvider(ServiceRegistry& reg, int val,
std::atomic<int>* observations)
: m_reg(reg), m_val(val), m_obs(observations)
{
}
~ReentrantDtorProvider() override
{
if (auto h = m_reg.acquire<IA>(); h) {
if (m_obs != nullptr) {
m_obs->fetch_add((*h)->id(), std::memory_order_relaxed);
}
}
}
[[nodiscard]] int id() const override { return m_val; }
private:
ServiceRegistry& m_reg;
int m_val;
std::atomic<int>* m_obs;
};
class ReentrantStartService final : public IService, public IB
{
public:
ReentrantStartService(ServiceRegistry& reg, std::atomic<int>* seen)
: m_reg(reg), m_seen(seen)
{
}
[[nodiscard]] std::string_view service_name() const override
{
return "ReentrantStart";
}
void on_start() override
{
if (auto a = m_reg.acquire<IA>(); a) {
m_seen->store((*a)->id(), std::memory_order_relaxed);
}
m_reg.provide<IC>(std::make_shared<SimpleC>(99));
}
[[nodiscard]] int tag() const override { return 7; }
private:
struct SimpleC final : IC {
explicit SimpleC(int r) : rank_val(r) {}
[[nodiscard]] int rank() const override { return rank_val; }
int rank_val;
};
ServiceRegistry& m_reg;
std::atomic<int>* m_seen;
};
} // namespace
Void::Testing::Test service_concurrent_remove_acquire_and_reentrant_dtor()
{
ServiceRegistry reg;
std::atomic<int> dtor_observations{0};
reg.provide<IA>(
std::make_shared<ReentrantDtorProvider>(reg, 1, &dtor_observations));
auto held_first = reg.acquire<IA>();
Void::Testing::expect(held_first.has_value());
Void::Testing::expect_eq((*held_first)->id(), 1);
// Replace with another ReentrantDtorProvider; releasing held_first
// later must invoke ~ReentrantDtorProvider cleanly without deadlocking.
std::atomic<bool> stop{false};
std::thread writer([&] {
for (int i = 2; i < 60 && !stop.load(std::memory_order_relaxed); ++i) {
reg.provide<IA>(std::make_shared<ReentrantDtorProvider>(
reg, i, &dtor_observations));
if (i % 7 == 0) {
(void)reg.remove<IA>();
}
}
});
std::thread reader([&] {
for (int i = 0; i < 200; ++i) {
if (auto h = reg.acquire<IA>(); h) {
Void::Testing::expect((*h)->id() >= 1);
}
}
stop.store(true, std::memory_order_relaxed);
});
writer.join();
reader.join();
Void::Testing::expect_eq((*held_first)->id(), 1);
held_first = Void::Result::fail(Void::Service::make_service_error(
ServiceErrorCode::missing_service, "drop"));
Void::Testing::expect(dtor_observations.load(std::memory_order_relaxed) >=
0);
}
Void::Testing::Test service_start_all_allows_reentrant_acquire_and_provide()
{
ServiceRegistry reg;
std::vector<std::string> log;
std::atomic<int> seen{0};
reg.provide<IA>(std::make_shared<TrackedService>("A", 42, &log));
reg.provide<IB>(std::make_shared<ReentrantStartService>(reg, &seen));
reg.start_all();
Void::Testing::expect_eq(seen.load(std::memory_order_relaxed), 42);
auto c = reg.acquire<IC>();
Void::Testing::expect(c.has_value());
Void::Testing::expect_eq((*c)->rank(), 99);
}
Void::Testing::Test service_dag_ordering_aliases_cycles_and_rollback()
{
std::vector<std::string> log;
ServiceRegistry reg;
// Baseline snapshot that must remain untouched if staged batch fails.
{
ProviderSet base;
base.add<IA>("baseline", std::make_shared<TrackedService>("base", 100, &log));
auto ep = reg.start_and_publish(std::move(base));
Void::Testing::expect(ep.has_value());
Void::Testing::expect_eq(*ep, std::uint64_t{1});
}
log.clear();
// Missing dependency rejected.
{
ProviderSet bad;
bad.add<IB>("B", std::make_shared<DualInterfaceService>(&log),
{std::type_index{typeid(IC)}});
auto prep = reg.prepare_batch(std::move(bad));
Void::Testing::expect(!prep.has_value());
Void::Testing::expect_eq(prep.error().code().value,
static_cast<std::int32_t>(
ServiceErrorCode::missing_dependency));
}
// Cycle rejected.
{
ProviderSet cyc;
auto dual = std::make_shared<DualInterfaceService>(&log);
cyc.add<IA>("A", std::make_shared<TrackedService>("A", 1, &log),
{std::type_index{typeid(IB)}});
cyc.add<IB>("B", dual, {std::type_index{typeid(IA)}});
auto prep = reg.prepare_batch(std::move(cyc));
Void::Testing::expect(!prep.has_value());
Void::Testing::expect_eq(
prep.error().code().value,
static_cast<std::int32_t>(ServiceErrorCode::cycle_detected));
}
// Middle node failure aborts failed node and rolls back started nodes in
// reverse dependency order, leaving baseline untouched.
{
struct RankImpl final : IManagedService, IC {
RankImpl(std::string n, std::vector<std::string>* l, bool fail)
: impl(std::move(n), 3, l, fail) {}
std::string_view service_name() const override
{ return impl.service_name(); }
Void::Result::Result<void> start_checked() override
{ return impl.start_checked(); }
Void::Result::Result<void> check_readiness() const override
{ return impl.check_readiness(); }
void abort_start() noexcept override { impl.abort_start(); }
Void::Result::Result<void> stop_checked() override
{ return impl.stop_checked(); }
int rank() const override { return 3; }
TrackedService impl;
};
auto dual = std::make_shared<DualInterfaceService>(&log);
ProviderSet fail_batch;
// IB depends on IA; IA registered second so DAG must still start IA before IB.
fail_batch.add<IB>("B", dual, {std::type_index{typeid(IA)}});
fail_batch.add<IA>("A", std::make_shared<TrackedService>("A", 1, &log));
fail_batch.add<IC>(
"C", std::make_shared<RankImpl>("C", &log, true),
{std::type_index{typeid(IB)}});
auto res = reg.start_and_publish(std::move(fail_batch));
Void::Testing::expect(!res.has_value());
Void::Testing::expect_eq(
res.error().code().value,
static_cast<std::int32_t>(ServiceErrorCode::start_failed));
// Baseline handle still resolves to id 100.
auto active = reg.acquire<IA>();
Void::Testing::expect(active.has_value());
Void::Testing::expect_eq((*active)->id(), 100);
// Sequence: start:A, dual:start, start:C, abort:C, dual:stop, stop:A.
Void::Testing::expect_eq(log.size(), std::size_t{6});
Void::Testing::expect_eq(log[0], std::string{"start:A"});
Void::Testing::expect_eq(log[1], std::string{"dual:start"});
Void::Testing::expect_eq(log[2], std::string{"start:C"});
Void::Testing::expect_eq(log[3], std::string{"abort:C"});
Void::Testing::expect_eq(log[4], std::string{"dual:stop"});
Void::Testing::expect_eq(log[5], std::string{"stop:A"});
}
// Alias of one lifecycle object starts/stops ONCE.
log.clear();
auto dual = std::make_shared<DualInterfaceService>(&log);
ProviderSet alias_batch;
alias_batch.add<IA>("dual.svc", dual);
alias_batch.add_alias<IB>("dual.svc.alias", dual);
auto ep = reg.start_and_publish(std::move(alias_batch));
Void::Testing::expect(ep.has_value());
Void::Testing::expect_eq(dual->starts, 1);
Void::Testing::expect_eq(reg.acquire<IA>().value()->id(), 10);
Void::Testing::expect_eq(reg.acquire<IB>().value()->tag(), 20);
}
Void::Testing::Test service_snapshot_parent_survives_parent_destruction()
{
std::unique_ptr<ServiceRegistry> child;
{
ServiceRegistry parent;
ProviderSet ps;
ps.add<IA>("A", std::make_shared<TrackedService>("A", 77, nullptr));
Void::Testing::expect(
parent.start_and_publish(std::move(ps)).has_value());
auto built = ServiceRegistry::from_parent_snapshot(parent.snapshot());
Void::Testing::expect(built.has_value());
child = std::move(*built);
} // parent destroyed here!
auto h = child->acquire<IA>();
Void::Testing::expect(h.has_value());
Void::Testing::expect_eq((*h)->id(), 77);
}
Void::Testing::Test service_retention_cap_and_close_incomplete_owners()
{
ManualClock clock;
ServiceLimits limits{};
limits.max_retained_generations = 4;
ServiceRegistry reg{limits, clock};
std::vector<std::string> log;
std::vector<Void::Service::ServiceHandle<IA>> pinned;
for (int gen = 1; gen <= 4; ++gen) {
ProviderSet ps;
ps.add<IA>(
"A",
std::make_shared<TrackedService>(
"A" + std::to_string(gen), gen, &log, false, false, gen == 4));
auto ep = reg.start_and_publish(std::move(ps));
Void::Testing::expect(ep.has_value());
auto h = reg.acquire<IA>();
Void::Testing::expect(h.has_value());
Void::Testing::expect_eq(h->generation(), *ep);
pinned.push_back(std::move(*h));
}
// 4 distinct generations pinned -> 5th publication rejected with retention_limit.
{
ProviderSet ps5;
ps5.add<IA>("A", std::make_shared<TrackedService>("A5", 5, &log));
auto prep5 = reg.prepare_batch(std::move(ps5));
Void::Testing::expect(!prep5.has_value());
Void::Testing::expect_eq(
prep5.error().code().value,
static_cast<std::int32_t>(ServiceErrorCode::retention_limit));
}
// Dropping oldest handle frees generation 1, allowing generation 5.
pinned.erase(pinned.begin());
{
ProviderSet ps5;
ps5.add<IA>("A", std::make_shared<TrackedService>("A5", 5, &log));
auto ep5 = reg.start_and_publish(std::move(ps5));
Void::Testing::expect(ep5.has_value());
}
// close_and_join closes admission, reports any stop error, and reports
// surviving pinned generations in incomplete_owners without freeing them.
auto rep = reg.close_and_join();
Void::Testing::expect(rep.has_value());
Void::Testing::expect(!rep->clean());
Void::Testing::expect(!rep->incomplete_owners.empty());
auto post_close = reg.acquire<IA>();
Void::Testing::expect(!post_close.has_value());
Void::Testing::expect_eq(
post_close.error().code().value,
static_cast<std::int32_t>(ServiceErrorCode::service_stopping));
// Pinned handles remain dereferenceable until dropped.
Void::Testing::expect_eq(pinned.front()->id(), 2);
}
+469
View File
@@ -0,0 +1,469 @@
#include <Void/Sqlite/Sqlite.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <sqlite3.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>
#include <unistd.h>
#include <vector>
namespace
{
using namespace Void::Sqlite;
struct TempSqliteDir {
std::filesystem::path path;
TempSqliteDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
path = std::filesystem::temp_directory_path() /
("void-sqlite-test-" + std::to_string(::getpid()) + "-" + std::to_string(id));
std::error_code ec;
std::filesystem::remove_all(path, ec);
std::filesystem::create_directories(path, ec);
}
~TempSqliteDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
Void::Testing::Test sqlite_connection_state_lifetime_close_and_statement_limits()
{
TempSqliteDir dir;
const auto db_path = dir.path / "state.db";
std::vector<std::string> diagnostics;
OpenOptions opts;
opts.journal_mode = JournalMode::Wal;
opts.sync_mode = SyncMode::Full;
opts.foreign_keys = true;
opts.limits.max_live_statements = 2;
opts.limits.max_sql_bytes = 256;
opts.limits.max_value_bytes = 64;
opts.diagnostic_hook = [&](std::string_view msg) { diagnostics.emplace_back(msg); };
auto db_res = open_database(db_path, opts);
Void::Testing::require(db_res.has_value());
auto db = std::move(*db_res);
const auto caps = db.capabilities();
Void::Testing::expect(!caps.in_memory);
Void::Testing::expect(!caps.read_only);
Void::Testing::expect_eq(caps.journal_mode, std::string{"wal"});
Void::Testing::expect_eq(caps.synchronous_mode, 2);
Void::Testing::expect(caps.foreign_keys);
Void::Testing::expect(!caps.extension_loading_enabled);
// load_extension is disabled by default.
Void::Testing::expect(!db.exec("SELECT load_extension('nonexistent')").has_value());
Void::Testing::require(db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, val TEXT)").has_value());
// Prepare rejects trailing SQL and SQL exceeding max_sql_bytes.
auto trailing = db.prepare("SELECT 1; SELECT 2");
Void::Testing::expect(!trailing.has_value());
Void::Testing::expect(trailing.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::trailing_sql));
const std::string too_long_sql(300, ' ');
auto oversized = db.prepare("SELECT 1" + too_long_sql);
Void::Testing::expect(!oversized.has_value());
Void::Testing::expect(oversized.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::size_limit));
// Move Database and destroy original while Transaction + Statement remain alive!
auto tx = db.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
auto s1 = db.prepare("INSERT INTO t(id, val) VALUES(?, ?)");
Void::Testing::require(s1.has_value());
// Statement limit enforcement.
auto s2 = db.prepare("SELECT COUNT(*) FROM t");
Void::Testing::require(s2.has_value());
auto s3 = db.prepare("SELECT 1");
Void::Testing::expect(!s3.has_value());
Void::Testing::expect(s3.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::statement_limit));
Database moved_db{std::move(db)};
// Old moved-from handle has no connection; new handle owns it, and close()
// refuses while s1, s2, tx are live!
auto busy_close = moved_db.close();
Void::Testing::expect(!busy_close.has_value());
Void::Testing::expect(busy_close.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::busy));
Void::Testing::require(s1->bind_checked(1, ValueView{42}).has_value());
Void::Testing::require(s1->bind_checked(2, ValueView{"survived_move"}).has_value());
Void::Testing::require(s1->step().has_value());
Void::Testing::require(s1->finalize_checked().has_value());
Void::Testing::require(s2->finalize_checked().has_value());
Void::Testing::require(tx->commit().has_value());
Void::Testing::expect(tx->state() == TransactionState::Committed);
// Injected close error test, followed by real clean close.
{
ScopedFaultGuard guard{FaultConfig{.fail_next_close_rc = SQLITE_IOERR}};
auto fail_close = moved_db.close();
Void::Testing::expect(!fail_close.has_value());
Void::Testing::expect(fail_close.error().kind() == Void::Result::ErrorKind::io);
}
Void::Testing::require(moved_db.close().has_value());
Void::Testing::expect(!moved_db.is_open());
// Reopen to confirm persistence on disk after move + commit.
auto reopened = open_database(db_path, opts);
Void::Testing::require(reopened.has_value());
auto sel = reopened->prepare("SELECT val FROM t WHERE id=42");
Void::Testing::require(sel.has_value());
auto has = sel->step();
Void::Testing::require(has.has_value() && *has);
Void::Testing::expect_eq(*sel->try_column_text(0), std::string{"survived_move"});
}
Void::Testing::Test sqlite_checked_binds_borrowed_owners_typed_rows_and_query_all()
{
OpenOptions opts;
opts.limits.max_value_bytes = 32;
opts.limits.max_query_all_rows = 3;
auto db_res = open_database(":memory:", opts);
Void::Testing::require(db_res.has_value());
auto& db = *db_res;
Void::Testing::require(
db.exec("CREATE TABLE items(id INTEGER, r REAL, txt TEXT, bin BLOB)").has_value());
auto ins = db.prepare(
"INSERT INTO items(id, r, txt, bin) VALUES(:id, :r, :txt, :bin)");
Void::Testing::require(ins.has_value());
Void::Testing::expect_eq(ins->bind_parameter_count(), 4);
// Out of range & missing named param
auto bad_idx = ins->bind_checked(5, ValueView{1});
Void::Testing::expect(!bad_idx.has_value());
Void::Testing::expect(bad_idx.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::range));
auto bad_name = ins->bind_checked(":missing", ValueView{1});
Void::Testing::expect(!bad_name.has_value());
Void::Testing::expect(bad_name.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::not_found));
// Oversized value fails before bind
const std::string huge(100, 'x');
auto too_big = ins->bind_checked(":txt", ValueView{huge});
Void::Testing::expect(!too_big.has_value());
Void::Testing::expect(too_big.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::size_limit));
// Row 1: INT64_MIN, double, embedded NUL text via borrowed owner, empty blob
auto borrowed_str = std::make_shared<std::string>(std::string_view{"ab\0cd", 5});
const std::string_view borrowed_view{borrowed_str->data(), borrowed_str->size()};
const std::vector<std::byte> empty_blob{};
Void::Testing::require(ins->bind_checked(":id", ValueView{std::numeric_limits<std::int64_t>::min()}).has_value());
Void::Testing::require(ins->bind_checked(":r", ValueView{3.25}).has_value());
Void::Testing::require(ins->bind_borrowed_text(3, borrowed_view, borrowed_str).has_value());
Void::Testing::require(ins->bind_checked(":bin", ValueView{std::span<const std::byte>{empty_blob}}).has_value());
// Drop caller's shared_ptr — Statement retains borrowed_str safely until clear/finalize!
const std::weak_ptr<const std::string> weak_owner = borrowed_str;
borrowed_str.reset();
Void::Testing::expect(!weak_owner.expired());
auto step1 = ins->step();
Void::Testing::require(step1.has_value() && !*step1);
Void::Testing::require(ins->reset_checked().has_value());
// Still alive after reset because SQLite retains SQLITE_STATIC until clear_bindings/finalize!
Void::Testing::expect(!weak_owner.expired());
Void::Testing::require(ins->clear_bindings_checked().has_value());
Void::Testing::expect(weak_owner.expired());
// Row 2: numeric string "123", INT64_MAX, NULL blob
Void::Testing::require(ins->bind_checked(1, ValueView{std::numeric_limits<std::int64_t>::max()}).has_value());
Void::Testing::require(ins->bind_checked(2, ValueView{nullptr}).has_value());
Void::Testing::require(ins->bind_checked(3, ValueView{"123"}).has_value());
Void::Testing::require(ins->bind_checked(4, ValueView{nullptr}).has_value());
Void::Testing::require(ins->step().has_value());
auto sel = db.prepare("SELECT id, r, txt, bin FROM items ORDER BY id ASC");
Void::Testing::require(sel.has_value());
auto has1 = sel->step();
Void::Testing::require(has1.has_value() && *has1);
auto rv1 = sel->current_row();
Void::Testing::require(rv1.has_value() && rv1->is_valid());
Void::Testing::expect_eq(*rv1->get_int(0), std::numeric_limits<std::int64_t>::min());
Void::Testing::expect(*rv1->get_double(1) == 3.25);
const std::string got_nul_txt = *rv1->get_text(2);
Void::Testing::expect_eq(got_nul_txt.size(), static_cast<std::size_t>(5));
Void::Testing::expect_eq(got_nul_txt[2], '\0');
auto ct_blob = rv1->column_type(3);
Void::Testing::require(ct_blob.has_value() && *ct_blob == ColumnType::Blob);
Void::Testing::expect(rv1->get_blob(3)->empty());
auto has2 = sel->step();
Void::Testing::require(has2.has_value() && *has2);
// rv1 expired at next step!
Void::Testing::expect(!rv1->is_valid());
Void::Testing::expect(!rv1->get_int(0).has_value());
// Typed reads reject coercion ("123" is TEXT, not INTEGER!).
Void::Testing::expect_eq(*sel->try_column_int(0), std::numeric_limits<std::int64_t>::max());
Void::Testing::expect(!sel->try_column_optional_double(1)->has_value());
auto bad_coercion = sel->try_column_int(2);
Void::Testing::expect(!bad_coercion.has_value());
Void::Testing::expect(bad_coercion.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::type_mismatch));
Void::Testing::expect(!sel->try_column_optional_blob(3)->has_value());
// query_all row cap
for (int i = 0; i < 4; ++i) {
Void::Testing::require(db.exec("INSERT INTO items(id, txt) VALUES(1, 'z')").has_value());
}
auto all_q = db.prepare("SELECT id, txt FROM items");
Void::Testing::require(all_q.has_value());
auto over_rows = db.query_all(*all_q, 3, 4096);
Void::Testing::expect(!over_rows.has_value());
Void::Testing::expect(over_rows.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::size_limit));
}
Void::Testing::Test sqlite_transactions_busy_commit_savepoints_and_checked_migrations()
{
TempSqliteDir dir;
const auto db_path = dir.path / "tx.db";
OpenOptions opts;
opts.limits.busy_timeout = std::chrono::milliseconds{20};
auto db1_r = open_database(db_path, opts);
Void::Testing::require(db1_r.has_value());
auto& db1 = *db1_r;
Void::Testing::require(db1.exec("CREATE TABLE t(k INTEGER PRIMARY KEY, v TEXT)").has_value());
// Real two-connection BUSY test
auto db2_r = open_database(db_path, opts);
Void::Testing::require(db2_r.has_value());
auto& db2 = *db2_r;
{
auto tx1 = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx1.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(1, 'holder')").has_value());
auto tx2_busy = db2.begin(BeginMode::Immediate);
Void::Testing::expect(!tx2_busy.has_value());
Void::Testing::expect(tx2_busy.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::busy));
Void::Testing::require(tx1->commit().has_value());
}
// Faulted COMMIT leaving autocommit==0 keeps Transaction active for retry/rollback!
{
auto tx = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(2, 'retried')").has_value());
// Nested begin is rejected.
auto nested = db1.begin();
Void::Testing::expect(!nested.has_value());
Void::Testing::expect(nested.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::misuse));
{
ScopedFaultGuard guard{FaultConfig{
.fail_next_commit_rc = SQLITE_BUSY,
.auto_rollback_on_faulted_commit = false}};
auto failed_commit = tx->commit();
Void::Testing::expect(!failed_commit.has_value());
Void::Testing::expect(failed_commit.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::busy));
Void::Testing::expect(tx->state() == TransactionState::Active);
Void::Testing::expect(sqlite3_get_autocommit(db1.handle()) == 0);
}
// Now retry commit succeeds!
Void::Testing::require(tx->commit().has_value());
Void::Testing::expect(tx->state() == TransactionState::Committed);
}
// Faulted COMMIT with auto-rollback transitions to RolledBack properly!
{
auto tx = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(3, 'rolled')").has_value());
{
ScopedFaultGuard guard{FaultConfig{
.fail_next_commit_rc = SQLITE_FULL,
.auto_rollback_on_faulted_commit = true}};
auto failed_commit = tx->commit();
Void::Testing::expect(!failed_commit.has_value());
Void::Testing::expect(tx->state() == TransactionState::RolledBack);
}
}
// Savepoint rollback_to + release
{
auto tx = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(10, 'kept')").has_value());
{
auto sp = db1.savepoint("inner_sp");
Void::Testing::require(sp.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(11, 'undone')").has_value());
Void::Testing::require(sp->rollback_and_release().has_value());
}
Void::Testing::require(tx->commit().has_value());
}
auto cnt = db1.prepare("SELECT COUNT(*) FROM t WHERE k IN (1, 2, 10, 11)");
Void::Testing::require(cnt.has_value() && *cnt->step());
Void::Testing::expect_eq(*cnt->try_column_int(0), static_cast<std::int64_t>(3));
// Checked migrations: invalid order rejected before mutation, checksum drift rejected!
const auto mig_db_path = dir.path / "mig.db";
auto mdb_r = open_database(mig_db_path);
Void::Testing::require(mdb_r.has_value());
auto& mdb = *mdb_r;
const std::array<CheckedMigration, 2> bad_order{{
{2, "v2", "sum2", "CREATE TABLE x(id INTEGER)"},
{2, "v2b", "sum2b", "CREATE TABLE y(id INTEGER)"},
}};
Void::Testing::expect(!mdb.migrate_checked(bad_order).has_value());
Void::Testing::expect_eq(*mdb.user_version(), 0);
const std::array<CheckedMigration, 2> good_migs{{
{1, "init_x", "sha256:aaa", "CREATE TABLE x(id INTEGER PRIMARY KEY)"},
{2, "add_name", "sha256:bbb", "ALTER TABLE x ADD COLUMN name TEXT"},
}};
Void::Testing::require(mdb.migrate_checked(good_migs).has_value());
Void::Testing::expect_eq(*mdb.user_version(), 2);
// Checksum drift must fail without mutating.
const std::array<CheckedMigration, 2> drifted{{
{1, "init_x", "sha256:TAMPERED", "CREATE TABLE x(id INTEGER PRIMARY KEY)"},
{2, "add_name", "sha256:bbb", "ALTER TABLE x ADD COLUMN name TEXT"},
}};
auto drift_res = mdb.migrate_checked(drifted);
Void::Testing::expect(!drift_res.has_value());
Void::Testing::expect(drift_res.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::migration_error));
// Unexpected newer schema (only supplying v1 when DB is at v2) rejected.
const std::array<CheckedMigration, 1> older_plan{{good_migs[0]}};
Void::Testing::expect(!mdb.migrate_checked(older_plan).has_value());
}
Void::Testing::Test sqlite_checkpoint_wal_admission_backup_restore_and_safe_callbacks()
{
TempSqliteDir dir;
const auto db_path = dir.path / "ops.db";
const auto backup_path = dir.path / "backup.db";
OpenOptions wopts;
wopts.limits.busy_timeout = std::chrono::milliseconds{20};
wopts.limits.wal_checkpoint_threshold_bytes = 4096;
wopts.limits.wal_warn_threshold_bytes = 8192;
wopts.limits.wal_stop_writes_threshold_bytes = 16384;
auto writer_r = open_database(db_path, wopts);
Void::Testing::require(writer_r.has_value());
auto& writer = *writer_r;
Void::Testing::require(writer.exec("CREATE TABLE logs(id INTEGER PRIMARY KEY, payload TEXT)").has_value());
Void::Testing::require(writer.exec("INSERT INTO logs VALUES(1, 'seed')").has_value());
// Open a long-lived reader transaction that pins the old snapshot so WAL
// cannot truncate past it!
OpenOptions ropts;
ropts.mode = OpenMode::ReadOnly;
auto reader_r = open_database(db_path, ropts);
Void::Testing::require(reader_r.has_value());
auto rtx = reader_r->begin(BeginMode::Deferred);
Void::Testing::require(rtx.has_value());
{
auto rsel = reader_r->prepare("SELECT COUNT(*) FROM logs");
Void::Testing::require(rsel.has_value() && *rsel->step());
}
// Write > 16 KiB across commits to push WAL past wal_stop_writes_threshold_bytes.
{
auto tx = writer.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
auto ins = writer.prepare("INSERT INTO logs(payload) VALUES(?)");
Void::Testing::require(ins.has_value());
const std::string blob(1024, 'W');
for (int i = 0; i < 40; ++i) {
Void::Testing::require(ins->bind_checked(1, ValueView{blob}).has_value());
Void::Testing::require(ins->step().has_value());
Void::Testing::require(ins->reset_checked().has_value());
}
Void::Testing::require(tx->commit().has_value());
}
// While reader holds snapshot, FULL/TRUNCATE checkpoint reports busy!
auto blocked_ckpt = writer.checkpoint(CheckpointMode::Truncate);
Void::Testing::require(blocked_ckpt.has_value());
Void::Testing::expect(blocked_ckpt->busy);
const auto h1 = writer.health();
Void::Testing::expect(h1.wal_write_admission_blocked);
auto rejected_begin = writer.begin(BeginMode::Immediate);
Void::Testing::expect(!rejected_begin.has_value());
Void::Testing::expect(rejected_begin.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::overloaded));
// Backup while reader+writer active still copies consistent committed state.
auto bkup = writer.backup_to(backup_path);
Void::Testing::require(bkup.has_value());
Void::Testing::expect_eq(bkup->remaining_pages, 0);
// Release reader snapshot and truncate checkpoint -> unblocks write admission!
Void::Testing::require(rtx->commit().has_value());
auto ok_ckpt = writer.checkpoint(CheckpointMode::Truncate);
Void::Testing::require(ok_ckpt.has_value());
Void::Testing::expect(!writer.health().wal_write_admission_blocked);
auto unblocked_tx = writer.begin(BeginMode::Immediate);
Void::Testing::require(unblocked_tx.has_value());
Void::Testing::require(writer.exec("INSERT INTO logs(payload) VALUES('after_ckpt')").has_value());
Void::Testing::require(unblocked_tx->commit().has_value());
// Restore from earlier backup into another DB and verify count matches 41!
const auto restored_path = dir.path / "restored.db";
auto restored_r = open_database(restored_path);
Void::Testing::require(restored_r.has_value());
Void::Testing::require(restored_r->restore_from(backup_path).has_value());
auto rcnt = restored_r->prepare("SELECT COUNT(*) FROM logs");
Void::Testing::require(rcnt.has_value() && *rcnt->step());
Void::Testing::expect_eq(*rcnt->try_column_int(0), static_cast<std::int64_t>(41));
// Throwing scalar function & authorizer never unwind across SQLite C frames.
Void::Testing::require(writer.create_scalar_function(
"boom_fn", 0,
[](std::span<const ValueView>) -> Result<OwnedValue> {
throw std::runtime_error{"boom"};
}).has_value());
auto boom = writer.prepare("SELECT boom_fn()");
Void::Testing::require(boom.has_value());
auto boom_step = boom->step();
Void::Testing::expect(!boom_step.has_value());
Void::Testing::require(writer.set_authorizer(
[](int action, std::string_view arg1, std::string_view, std::string_view, std::string_view) {
if (action == SQLITE_DROP_TABLE || arg1 == "blocked_tbl") {
throw std::runtime_error{"auth boom converts to deny"};
}
return AuthorizerDecision::Allow;
}).has_value());
Void::Testing::expect(!writer.exec("DROP TABLE logs").has_value());
}
} // namespace
@@ -0,0 +1,250 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Sqlite/AsyncPool.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <stop_token>
#include <string>
#include <thread>
#include <unistd.h>
namespace
{
using namespace Void::Sqlite;
struct TempPoolDir {
std::filesystem::path path;
TempPoolDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
path = std::filesystem::temp_directory_path() /
("void-sqlite-async-" + std::to_string(::getpid()) + "-" + std::to_string(id));
std::error_code ec;
std::filesystem::remove_all(path, ec);
std::filesystem::create_directories(path, ec);
}
~TempPoolDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
Void::Coro::Task<void> run_pool_crud_and_backpressure(
AsyncPool& pool,
Void::Async::ManualExecutor& exec)
{
(void)exec;
auto init = co_await pool.run_write_void([](Database& db) {
return db.exec("CREATE TABLE kv(k INTEGER PRIMARY KEY, v TEXT)");
});
Void::Testing::require(init.has_value());
// Write transaction commit
auto tx_ok = co_await pool.run_write_transaction<int>(
BeginMode::Immediate,
[](Database& db, Transaction&) -> Result<int> {
auto r1 = db.exec("INSERT INTO kv VALUES(1, 'one')");
if (!r1) return Void::Result::fail(std::move(r1).error());
auto r2 = db.exec("INSERT INTO kv VALUES(2, 'two')");
if (!r2) return Void::Result::fail(std::move(r2).error());
return 2;
});
Void::Testing::require(tx_ok.has_value() && *tx_ok == 2);
// Write transaction error rolls back cleanly inside same lease
auto tx_err = co_await pool.run_write_transaction<int>(
BeginMode::Immediate,
[](Database& db, Transaction&) -> Result<int> {
auto r1 = db.exec("INSERT INTO kv VALUES(3, 'rolled')");
if (!r1) return Void::Result::fail(std::move(r1).error());
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::constraint, "intentional rollback"));
});
Void::Testing::expect(!tx_err.has_value());
// 4 concurrent reads via coroutine calls
for (int i = 0; i < 4; ++i) {
auto count = co_await pool.run_read<std::int64_t>([](Database& db) -> Result<std::int64_t> {
auto st = db.prepare("SELECT COUNT(*) FROM kv");
if (!st) return Void::Result::fail(std::move(st).error());
auto s = st->step();
if (!s) return Void::Result::fail(std::move(s).error());
return st->try_column_int(0);
});
Void::Testing::require(count.has_value());
Void::Testing::expect_eq(*count, static_cast<std::int64_t>(2));
}
// Oversized input bytes rejected before queueing
auto over_bytes = co_await pool.run_read_void(
[](Database&) -> Result<void> { return {}; },
{},
4096);
Void::Testing::expect(!over_bytes.has_value());
Void::Testing::expect(over_bytes.error().kind() == Void::Result::ErrorKind::overloaded);
}
Void::Coro::Task<void> run_heavy_query(
AsyncPool& pool,
std::stop_token st,
Result<std::int64_t>* out)
{
Void::Async::OperationOptions op;
op.stop = st;
*out = co_await pool.run_read<std::int64_t>(
[](Database& db) -> Result<std::int64_t> {
auto stmt = db.prepare(
"WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt WHERE x < 20000000) "
"SELECT MAX(x) FROM cnt");
if (!stmt) return Void::Result::fail(std::move(stmt).error());
auto s = stmt->step();
if (!s) return Void::Result::fail(std::move(s).error());
return stmt->try_column_int(0);
},
op);
}
Void::Coro::Task<void> verify_follow_up_reads(AsyncPool& pool)
{
for (int i = 0; i < 10; ++i) {
auto r = co_await pool.run_read<std::int64_t>(
[](Database& db) -> Result<std::int64_t> {
auto st = db.prepare("SELECT 42");
if (!st) return Void::Result::fail(std::move(st).error());
auto has = st->step();
if (!has) return Void::Result::fail(std::move(has).error());
return st->try_column_int(0);
});
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(*r, static_cast<std::int64_t>(42));
}
}
Void::Coro::Task<void> drive_pool_crud(
AsyncPool& pool,
Void::Async::ManualExecutor& exec,
bool* done)
{
co_await run_pool_crud_and_backpressure(pool, exec);
*done = true;
}
Void::Coro::Task<void> drive_warmup(AsyncPool& pool, bool* done)
{
auto r = co_await pool.run_write_void([](Database& db) {
return db.exec("CREATE TABLE dummy(id INTEGER)");
});
Void::Testing::require(r.has_value());
*done = true;
}
Void::Coro::Task<void> drive_heavy_query(
AsyncPool& pool,
std::stop_token st,
Result<std::int64_t>* out,
bool* done)
{
co_await run_heavy_query(pool, st, out);
*done = true;
}
Void::Coro::Task<void> drive_followups(AsyncPool& pool, bool* done)
{
co_await verify_follow_up_reads(pool);
*done = true;
}
Void::Testing::Test sqlite_async_pool_readers_writer_transactions_and_backpressure()
{
TempPoolDir dir;
Void::Async::ManualExecutor exec;
AsyncPoolOptions opts;
opts.path = dir.path / "pool.db";
opts.reader_connections = 4;
opts.max_queued_jobs = 8;
opts.max_pending_input_bytes = 1024;
auto pool_r = AsyncPool::open(opts, &exec);
Void::Testing::require(pool_r.has_value());
auto pool = std::move(*pool_r);
bool done = false;
auto t = drive_pool_crud(pool, exec, &done);
t.handle().resume();
while (!done) {
if (exec.drain() == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
const auto st = pool.stats();
Void::Testing::expect_eq(st.reader_connections, static_cast<std::size_t>(4));
Void::Testing::expect(st.completed_jobs >= 7);
Void::Testing::expect(st.rejected_jobs >= 1);
Void::Testing::require(pool.close_and_join().has_value());
}
Void::Testing::Test sqlite_async_pool_cancellation_no_cross_query_interrupt_leak()
{
TempPoolDir dir;
Void::Async::ManualExecutor exec;
AsyncPoolOptions opts;
opts.path = dir.path / "cancel.db";
opts.reader_connections = 1; // force all follow-up reads onto the exact same connection
opts.progress_handler_steps = 32;
auto pool_r = AsyncPool::open(opts, &exec);
Void::Testing::require(pool_r.has_value());
auto pool = std::move(*pool_r);
// Warm up DB with initial table/checkpoint
{
bool warmup_done = false;
auto wt = drive_warmup(pool, &warmup_done);
wt.handle().resume();
while (!warmup_done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
std::stop_source ss;
Result<std::int64_t> cancel_res = Void::Result::fail("uninitialized");
bool cancel_done = false;
auto rt = drive_heavy_query(pool, ss.get_token(), &cancel_res, &cancel_done);
rt.handle().resume();
// Wait until reader is actively running, then interrupt it.
for (int i = 0; i < 100 && pool.stats().active_read_jobs == 0 && !cancel_done; ++i) {
exec.drain();
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
ss.request_stop();
while (!cancel_done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
Void::Testing::expect(!cancel_res.has_value());
Void::Testing::expect(cancel_res.error().kind() == Void::Result::ErrorKind::cancelled);
// Immediately run 10 follow-up queries on the same single reader connection;
// zero interrupts may leak to subsequent borrowers!
bool followup_done = false;
auto ft = drive_followups(pool, &followup_done);
ft.handle().resume();
while (!followup_done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
Void::Testing::require(pool.close_and_join().has_value());
}
} // namespace
+855
View File
@@ -0,0 +1,855 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Core/Uuid.hpp>
#include <Void/Storage/Storage.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <limits>
#include <map>
#include <random>
#include <stop_token>
#include <string>
#include <thread>
#include <unistd.h>
#include <vector>
namespace
{
using namespace Void::Storage;
struct TempStorageDir {
std::filesystem::path path;
TempStorageDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
path = std::filesystem::temp_directory_path() /
("void-storage-test-" + std::to_string(::getpid()) + "-" + std::to_string(id));
std::error_code ec;
std::filesystem::remove_all(path, ec);
std::filesystem::create_directories(path, ec);
}
~TempStorageDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
void write_raw_bytes(const std::filesystem::path& p, ByteView data)
{
auto port = make_posix_file_port();
(void)port->unlink_file(p);
auto f = port->open_file(p, FileOpenMode::CreateNew);
Void::Testing::require(f.has_value());
Void::Testing::require((*f)->append_all(data).has_value());
Void::Testing::require((*f)->sync().has_value());
}
Void::Coro::Task<void> run_async_stop_before_append(
AsyncStorageAdapter& adapter,
std::expected<CommitReceipt, WriteFailure>* out,
bool* done)
{
std::stop_source ss;
ss.request_stop();
Batch b;
b.put("k_cancelled", "never_written");
Void::Async::OperationOptions op;
op.stop = ss.get_token();
*out = co_await adapter.write_async(std::move(b), Durability::Sync, op);
*done = true;
}
Void::Coro::Task<void> run_async_write_tracked(
AsyncStorageAdapter& adapter,
std::string key,
std::string val,
std::stop_token st,
std::expected<CommitReceipt, WriteFailure>* out,
std::atomic<int>* deliveries,
bool* done)
{
Batch b;
b.put(key, val);
Void::Async::OperationOptions op;
op.stop = st;
*out = co_await adapter.write_async(std::move(b), Durability::Sync, op);
deliveries->fetch_add(1, std::memory_order_acq_rel);
*done = true;
}
Void::Testing::Test storage_crc32c_golden_and_v1_format_codecs()
{
// Golden CRC32C check (Cyphal / Castagnoli)
Void::Testing::expect_eq(crc32c(std::string_view{"123456789"}), 0xE3069283u);
Void::Testing::expect_eq(crc32c(std::string_view{""}), 0u);
// Incremental chunked update must match single-pass CRC32C
std::uint32_t st = crc32c_init();
st = crc32c_update(st, std::string_view{"1234"});
st = crc32c_update(st, std::string_view{"56789"});
Void::Testing::expect_eq(crc32c_finalize(st), 0xE3069283u);
// Limits validation rejects zero fields
Limits bad_lim;
bad_lim.max_key_bytes = 0;
Void::Testing::expect(!validate_limits(bad_lim).has_value());
// WAL segment header encode/decode + corruption & unknown major/flags rejection
auto uuid = Void::Uuid::try_v4();
Void::Testing::require(uuid.has_value());
WalSegmentHeader wsh;
wsh.database_uuid = *uuid;
wsh.segment_id = 7;
wsh.previous_segment_id = 6;
wsh.first_candidate_sequence = 42;
auto raw_seg = encode_wal_segment_header(wsh);
Void::Testing::require(raw_seg.has_value());
Void::Testing::expect_eq(raw_seg->size(), static_cast<std::size_t>(kWalSegmentHeaderSize));
auto dec_seg = decode_wal_segment_header(*raw_seg);
Void::Testing::require(dec_seg.has_value());
Void::Testing::expect_eq(dec_seg->segment_id, static_cast<std::uint64_t>(7));
// Flip a byte in segment header -> corrupt
auto flipped_seg = *raw_seg;
flipped_seg[20] ^= std::byte{0x01};
auto bad_seg = decode_wal_segment_header(flipped_seg);
Void::Testing::expect(!bad_seg.has_value());
Void::Testing::expect(bad_seg.error().kind() == Void::Result::ErrorKind::corrupt);
// WAL record header checks header CRC BEFORE trusting huge payload_length!
auto mp = encode_wal_mutation_payload(false, to_byte_view("k"), to_byte_view("v"));
Void::Testing::require(mp.has_value());
auto frame = encode_wal_record_frame(WalRecordType::Put, 5, 1, *mp);
Void::Testing::require(frame.has_value());
auto rh = decode_wal_record_header(
std::span<const std::byte>{frame->data(), kWalRecordHeaderSize}, 65536);
Void::Testing::require(rh.has_value());
Void::Testing::require(verify_wal_record_frame(*rh, *frame).has_value());
// Flip header payload_len without updating header CRC -> rejected before allocation
auto huge_len_hdr = *frame;
huge_len_hdr[28] = std::byte{0xFF};
huge_len_hdr[29] = std::byte{0xFF};
huge_len_hdr[30] = std::byte{0xFF};
huge_len_hdr[31] = std::byte{0x7F};
auto bad_rh = decode_wal_record_header(
std::span<const std::byte>{huge_len_hdr.data(), kWalRecordHeaderSize}, 1024);
Void::Testing::expect(!bad_rh.has_value());
// Erase payload with non-zero value fails decode
auto bad_erase = encode_wal_mutation_payload(true, to_byte_view("k"), to_byte_view("nonempty"));
Void::Testing::expect(!bad_erase.has_value());
}
Void::Testing::Test storage_model_atomic_batches_preconditions_snapshots_and_scans()
{
TempStorageDir dir;
OpenOptions opts;
opts.directory = dir.path;
opts.limits.max_snapshots = 8;
opts.limits.max_cursors = 8;
auto eng_r = Engine::open(opts);
Void::Testing::require(eng_r.has_value());
auto& eng = *eng_r;
// Reference model: key -> (value, version_seq)
struct RefVal {
OwnedBytes val;
Sequence seq;
};
std::map<OwnedBytes, RefVal, ByteLess> ref;
// Test empty key and empty value distinct from absence, plus binary 0x00/0xFF keys.
const OwnedBytes k_empty{};
const OwnedBytes k_nul{std::byte{0x00}, std::byte{0x41}, std::byte{0x00}};
const OwnedBytes k_ff{std::byte{0xFF}, std::byte{0xFF}};
{
Batch b;
b.require_absent(k_empty)
.put(k_empty, OwnedBytes{})
.put(k_nul, to_byte_view("zero"))
.put(k_ff, to_byte_view("ffval"));
auto r = eng.write(std::move(b), Durability::Sync);
Void::Testing::require(r.has_value());
ref[k_empty] = RefVal{{}, r->sequence};
ref[k_nul] = RefVal{to_owned_bytes("zero"), r->sequence};
ref[k_ff] = RefVal{to_owned_bytes("ffval"), r->sequence};
}
// Duplicate key & duplicate precondition rejected cleanly as NotCommitted
{
Batch dup_mut;
dup_mut.put("a", "1").put("a", "2");
auto r = eng.write(std::move(dup_mut), Durability::Sync);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().outcome == Outcome::NotCommitted);
Batch dup_cond;
dup_cond.require_absent("a").require_value("a", "1").put("b", "2");
auto r2 = eng.write(std::move(dup_cond), Durability::Sync);
Void::Testing::expect(!r2.has_value());
Void::Testing::expect(r2.error().outcome == Outcome::NotCommitted);
}
// Delete + reinsert ABA version check: old sequence must fail after delete!
Sequence seq_a1 = 0;
{
Batch b;
b.put("aba", "v1");
auto r = eng.write(std::move(b), Durability::Sync);
Void::Testing::require(r.has_value());
seq_a1 = r->sequence;
}
{
Batch b;
b.require_version("aba", seq_a1).erase("aba");
Void::Testing::require(eng.write(std::move(b), Durability::Sync).has_value());
}
{
// Obsolete version check after delete MUST fail!
Batch b;
b.require_version("aba", seq_a1).put("aba", "should_fail");
auto r = eng.write(std::move(b), Durability::Sync);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().outcome == Outcome::NotCommitted);
Void::Testing::expect(r.error().cause.code == StorageErrorCode::conflict);
}
// Take Snapshot before randomized model mutations!
auto early_snap = eng.snapshot();
Void::Testing::require(early_snap.has_value());
{
auto g = eng.get(*early_snap, k_empty);
Void::Testing::require(g.has_value());
Void::Testing::expect(g->bytes.empty());
}
// Deterministic RNG model check comparing EVERY snapshot against ordered std::map!
std::mt19937 rng{20261126u};
{
auto s0 = eng.snapshot();
Void::Testing::require(s0.has_value());
auto cur0 = eng.scan(std::move(*s0), ScanBounds::all());
Void::Testing::require(cur0.has_value());
for (;;) {
auto pg = cur0->next_page();
Void::Testing::require(pg.has_value());
for (const auto& e : pg->entries) {
ref[e.key] = RefVal{e.value, e.version};
}
if (!pg->has_more) break;
}
}
for (int step = 0; step < 60; ++step) {
const auto kb = to_owned_bytes("m/" + std::to_string(rng() % 7));
Batch b;
const bool do_erase = (rng() % 3) == 0;
const std::string val_str = "val_" + std::to_string(step);
if ((rng() % 4) == 0) {
if (auto it = ref.find(kb); it != ref.end()) {
b.require_value(kb, it->second.val);
} else {
b.require_absent(kb);
}
}
if (do_erase) {
b.erase(kb);
} else {
b.put(ByteView{kb}, to_byte_view(val_str));
}
auto wr = eng.write(std::move(b), (step % 2 == 0) ? Durability::Sync : Durability::Buffered);
Void::Testing::require(wr.has_value());
if (do_erase) {
ref.erase(kb);
} else {
ref[kb] = RefVal{to_owned_bytes(val_str), wr->sequence};
}
auto s = eng.snapshot();
Void::Testing::require(s.has_value());
auto cur = eng.scan(std::move(*s), ScanBounds::all());
Void::Testing::require(cur.has_value());
std::map<OwnedBytes, RefVal, ByteLess> got;
for (;;) {
auto pg = cur->next_page();
Void::Testing::require(pg.has_value());
for (const auto& e : pg->entries) {
got[e.key] = RefVal{e.value, e.version};
}
if (!pg->has_more) break;
}
Void::Testing::expect_eq(got.size(), ref.size());
for (const auto& [k, rv] : ref) {
Void::Testing::require(got.contains(k));
Void::Testing::expect(got[k].val == rv.val);
Void::Testing::expect_eq(got[k].seq, rv.seq);
}
}
// Prefix scan including 0xFF prefix and close()-while-snapshot-live -> Busy!
{
auto cur = eng.scan(std::move(*early_snap), ScanBounds::prefix(k_ff));
Void::Testing::require(cur.has_value());
auto busy = eng.close();
Void::Testing::expect(!busy.has_value());
Void::Testing::expect(busy.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::busy));
auto pg = cur->next_page();
Void::Testing::require(pg.has_value());
Void::Testing::expect_eq(pg->entries.size(), static_cast<std::size_t>(1));
Void::Testing::expect(pg->entries[0].key == k_ff);
cur->close();
}
// PageTooSmall reported when entry exceeds ScanBounds::page_bytes
{
Batch big_b;
const std::string big_v(2048, 'B');
big_b.put("big_key", big_v);
Void::Testing::require(eng.write(std::move(big_b), Durability::Sync).has_value());
auto s = eng.snapshot();
Void::Testing::require(s.has_value());
ScanBounds sb = ScanBounds::prefix("big_key");
sb.page_bytes = 512;
auto cur = eng.scan(std::move(*s), sb);
Void::Testing::require(cur.has_value());
auto pg = cur->next_page();
Void::Testing::expect(!pg.has_value());
Void::Testing::expect(pg.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::page_too_small));
}
// Sequence counter exhaustion returns sequence_exhausted without wrapping
{
TempStorageDir max_dir;
OpenOptions mopts;
mopts.directory = max_dir.path;
mopts.initial_sequence = std::numeric_limits<Sequence>::max();
auto meng = Engine::open(mopts);
Void::Testing::require(meng.has_value());
Batch b;
b.put("x", "1");
auto wr = meng->write(std::move(b), Durability::Sync);
Void::Testing::expect(!wr.has_value());
Void::Testing::expect(wr.error().outcome == Outcome::NotCommitted);
Void::Testing::expect(wr.error().cause.code == StorageErrorCode::sequence_exhausted);
}
Void::Testing::require(eng.close().has_value());
}
Void::Testing::Test storage_wal_recovery_byte_truncation_corruption_and_rotation()
{
// 1. Orphan manifest without CURRENT -> incomplete_init (never adopts orphan!)
{
TempStorageDir dir;
auto uuid = Void::Uuid::try_v4();
Void::Testing::require(uuid.has_value());
ManifestData m;
m.database_uuid = *uuid;
m.generation = 5;
m.wal_segments = {1};
auto enc = encode_manifest(m, 65536);
Void::Testing::require(enc.has_value());
write_raw_bytes(dir.path / make_manifest_filename(5), *enc);
OpenOptions opts;
opts.directory = dir.path;
auto r = Engine::open(opts);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::incomplete_init));
}
// 2. Truncate EVERY byte offset across a multi-batch WAL & test reopen recovery!
TempStorageDir base_dir;
OpenOptions base_opts;
base_opts.directory = base_dir.path;
base_opts.limits.max_batch_encoded_bytes = 4096;
base_opts.limits.wal_segment_target_bytes = 4096; // force small target for rotation later
std::vector<Sequence> expected_seqs;
{
auto eng = Engine::open(base_opts);
Void::Testing::require(eng.has_value());
for (int i = 1; i <= 2; ++i) {
Batch b;
b.put(std::string(1, static_cast<char>('a' + i - 1)), std::to_string(i));
auto wr = eng->write(std::move(b), Durability::Sync);
Void::Testing::require(wr.has_value());
expected_seqs.push_back(wr->sequence);
}
Void::Testing::require(eng->close().has_value());
}
const auto orig_wal_path = base_dir.path / make_wal_filename(1);
OwnedBytes orig_wal_bytes;
{
auto port = make_posix_file_port();
auto sz = port->file_size(orig_wal_path);
Void::Testing::require(sz.has_value());
orig_wal_bytes.resize(*sz);
auto f = port->open_file(orig_wal_path, FileOpenMode::ReadOnly);
Void::Testing::require(f.has_value());
Void::Testing::require((*f)->pread_exact(0, orig_wal_bytes).has_value());
}
// Sweep EVERY truncation length from kWalSegmentHeaderSize up to orig_wal_bytes.size()
for (std::size_t cut = kWalSegmentHeaderSize; cut <= orig_wal_bytes.size(); ++cut) {
TempStorageDir copy_dir;
std::filesystem::copy(
base_dir.path, copy_dir.path,
std::filesystem::copy_options::recursive |
std::filesystem::copy_options::overwrite_existing);
(void)std::filesystem::remove(copy_dir.path / "LOCK");
{
auto port = make_posix_file_port();
auto wf = port->open_file(
copy_dir.path / make_wal_filename(1), FileOpenMode::ReadWriteExisting);
Void::Testing::require(wf.has_value());
Void::Testing::require((*wf)->truncate(cut).has_value());
Void::Testing::require((*wf)->sync().has_value());
}
OpenOptions ropts;
ropts.directory = copy_dir.path;
ropts.limits = base_opts.limits;
auto eng = Engine::open(ropts);
Void::Testing::require(eng.has_value());
const auto st1 = eng->stats();
Void::Testing::expect(st1.committed_sequence <= 3);
Void::Testing::require(eng->close().has_value());
// Idempotent second recovery!
auto eng2 = Engine::open(ropts);
Void::Testing::require(eng2.has_value());
Void::Testing::expect_eq(eng2->stats().committed_sequence, st1.committed_sequence);
Void::Testing::expect_eq(eng2->stats().recovery_truncated_bytes, static_cast<std::uint64_t>(0));
Void::Testing::require(eng2->close().has_value());
}
// 3. Complete record with single-bit corruption (including final byte!) MUST fail closed (Corrupt)
{
TempStorageDir bad_dir;
std::filesystem::copy(base_dir.path, bad_dir.path,
std::filesystem::copy_options::overwrite_existing);
(void)std::filesystem::remove(bad_dir.path / "LOCK");
{
auto port = make_posix_file_port();
auto wf = port->open_file(
bad_dir.path / make_wal_filename(1), FileOpenMode::ReadWriteExisting);
Void::Testing::require(wf.has_value());
auto b = orig_wal_bytes;
b[b.size() - 12] ^= std::byte{0x04}; // flip inside final complete COMMIT trailer/payload
Void::Testing::require((*wf)->pwrite_all(0, b).has_value());
Void::Testing::require((*wf)->sync().has_value());
}
OpenOptions ropts = base_opts;
ropts.directory = bad_dir.path;
auto r = Engine::open(ropts);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().kind() == Void::Result::ErrorKind::corrupt);
}
// 4. WAL segment rotation across multiple small batches preserves full recovery
{
TempStorageDir rot_dir;
OpenOptions ropts;
ropts.directory = rot_dir.path;
ropts.limits.max_batch_encoded_bytes = 256;
ropts.limits.wal_segment_target_bytes = 384; // rotate every ~2 batches!
auto eng = Engine::open(ropts);
Void::Testing::require(eng.has_value());
for (int i = 0; i < 10; ++i) {
Batch b;
b.put("r/" + std::to_string(i), std::string(48, static_cast<char>('A' + i)));
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->close().has_value());
auto reopened = Engine::open(ropts);
Void::Testing::require(reopened.has_value());
Void::Testing::expect_eq(reopened->stats().committed_sequence, static_cast<Sequence>(10));
auto s = reopened->snapshot();
Void::Testing::require(s.has_value());
Void::Testing::expect_eq(
reopened->get(*s, "r/9")->as_string_view(),
std::string_view{std::string(48, 'J')});
s->reset();
Void::Testing::require(reopened->close().has_value());
}
}
Void::Testing::Test storage_fault_injected_crashes_sync_unknown_checkpoint_and_compaction()
{
// 1. Initial CURRENT creation failure -> directory fails incomplete_init on reopen
{
TempStorageDir dir;
auto fp = std::make_shared<FaultInjectingFilePort>();
fp->add_rule(FaultRule{
.op = FaultOp::Rename,
.path_contains = "CURRENT",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
OpenOptions opts;
opts.directory = dir.path;
opts.file_port = fp;
Void::Testing::expect(!Engine::open(opts).has_value());
OpenOptions clean_opts;
clean_opts.directory = dir.path;
auto reopen = Engine::open(clean_opts);
Void::Testing::expect(!reopen.has_value());
Void::Testing::expect(reopen.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::incomplete_init));
}
// 2. Sync failure AFTER append -> Outcome::Unknown + RecoveryRequired,
// existing snapshots keep reading last published state, reopen recovers persisted batch!
{
TempStorageDir dir;
auto fp = std::make_shared<FaultInjectingFilePort>();
OpenOptions opts;
opts.directory = dir.path;
opts.file_port = fp;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
{
Batch b1;
b1.put("k", "v1");
Void::Testing::require(eng->write(std::move(b1), Durability::Sync).has_value());
}
auto pre_snap = eng->snapshot();
Void::Testing::require(pre_snap.has_value());
// Inject fsync failure on next WAL sync!
fp->add_rule(FaultRule{
.op = FaultOp::SyncFile,
.path_contains = "WAL-",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
{
Batch b2;
b2.put("k", "v2");
auto wr = eng->write(std::move(b2), Durability::Sync);
Void::Testing::expect(!wr.has_value());
Void::Testing::expect(wr.error().outcome == Outcome::Unknown);
}
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
// Existing snapshot still sees pre-failure published v1!
Void::Testing::expect_eq(eng->get(*pre_snap, "k")->as_string_view(), std::string_view{"v1"});
// Further writes rejected cleanly
{
Batch b3;
b3.put("k", "v3");
auto wr3 = eng->write(std::move(b3), Durability::Sync);
Void::Testing::expect(!wr3.has_value());
Void::Testing::expect(wr3.error().outcome == Outcome::NotCommitted);
}
pre_snap->reset();
(void)eng->close();
// Clean reopen recovers v2 because COMMIT was appended before fsync error!
OpenOptions clean_opts;
clean_opts.directory = dir.path;
auto eng2 = Engine::open(clean_opts);
Void::Testing::require(eng2.has_value());
auto s2 = eng2->snapshot();
Void::Testing::require(s2.has_value());
Void::Testing::expect_eq(eng2->get(*s2, "k")->as_string_view(), std::string_view{"v2"});
s2->reset();
Void::Testing::require(eng2->close().has_value());
}
// 3. Checkpoint failure before CURRENT rename leaves previous generation intact,
// and slow Snapshot pins keep obsolete compacted tables alive until released!
{
TempStorageDir dir;
auto fp = std::make_shared<FaultInjectingFilePort>();
OpenOptions opts;
opts.directory = dir.path;
opts.file_port = fp;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
// Create key k across 2 checkpoints so we have 2 immutable tables + a pinned snapshot!
{
Batch b;
b.put("alpha", "gen1");
b.put("beta", "keep");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->checkpoint().has_value());
auto snap_v1 = eng->snapshot();
Void::Testing::require(snap_v1.has_value());
{
Batch b;
b.put("alpha", "gen2");
b.erase("beta");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->checkpoint().has_value());
// Inject checkpoint rename failure on CURRENT -> old generation remains authoritative on reopen!
{
Batch b;
b.put("alpha", "gen3_in_wal");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
fp->add_rule(FaultRule{
.op = FaultOp::Rename,
.path_contains = "CURRENT",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
Void::Testing::expect(!eng->checkpoint().has_value());
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
snap_v1->reset();
(void)eng->close();
// Clean reopen still recovers gen3 cleanly!
OpenOptions clean_opts;
clean_opts.directory = dir.path;
auto eng2 = Engine::open(clean_opts);
Void::Testing::require(eng2.has_value());
auto s_latest = eng2->snapshot();
Void::Testing::require(s_latest.has_value());
Void::Testing::expect_eq(eng2->get(*s_latest, "alpha")->as_string_view(),
std::string_view{"gen3_in_wal"});
Void::Testing::require(eng2->checkpoint().has_value());
// Now pin s_latest and trigger compaction across multiple tables!
Void::Testing::require(eng2->stats().active_table_count >= 2);
Void::Testing::require(eng2->compact().has_value());
Void::Testing::expect(eng2->stats().obsolete_pinned_bytes > 0);
Void::Testing::expect_eq(eng2->get(*s_latest, "alpha")->as_string_view(),
std::string_view{"gen3_in_wal"});
// Dropping s_latest releases the pin and lets obsolete files be reclaimed!
s_latest->reset();
Void::Testing::expect_eq(eng2->stats().obsolete_pinned_bytes, static_cast<std::uint64_t>(0));
Void::Testing::require(eng2->close().has_value());
}
}
Void::Coro::Task<void> drive_stop_before_append_test(
AsyncStorageAdapter& adapter,
std::expected<CommitReceipt, WriteFailure>* out,
bool* done)
{
co_await run_async_stop_before_append(adapter, out, done);
}
Void::Coro::Task<void> drive_tracked_write_test(
AsyncStorageAdapter& adapter,
std::string key,
std::string val,
std::stop_token st,
std::expected<CommitReceipt, WriteFailure>* out,
std::atomic<int>* deliveries,
bool* done)
{
co_await run_async_write_tracked(
adapter, std::move(key), std::move(val), st, out, deliveries, done);
}
Void::Testing::Test storage_tools_verify_backup_restore_salvage_and_async_stop_races()
{
TempStorageDir dir;
TempStorageDir backup_dir;
TempStorageDir restore_dir;
TempStorageDir salvage_dir;
// 1. Live export_backup, offline verify_directory, block-level corruption detection, restore & salvage
{
OpenOptions opts;
opts.directory = dir.path;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
{
Batch b;
b.put("t1", std::string(1024, 'X'));
b.put("t2", std::string(1024, 'Y'));
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->checkpoint().has_value());
{
Batch b;
b.put("w1", "after_ckpt");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
// Backup while engine remains open
Void::Testing::require(eng->export_backup(backup_dir.path).has_value());
Void::Testing::require(eng->close().has_value());
// Offline verify_directory passes on backup
auto vr = verify_directory(backup_dir.path);
Void::Testing::require(vr.has_value());
Void::Testing::expect(vr->tables_verified >= 1);
Void::Testing::expect(vr->blocks_verified >= 1);
// Restore backup into restore_dir and verify data
Void::Testing::require(restore_backup(backup_dir.path, restore_dir.path).has_value());
OpenOptions r_opts;
r_opts.directory = restore_dir.path;
auto reng = Engine::open(r_opts);
Void::Testing::require(reng.has_value());
auto rs = reng->snapshot();
Void::Testing::require(rs.has_value());
Void::Testing::expect_eq(reng->get(*rs, "w1")->as_string_view(), std::string_view{"after_ckpt"});
Void::Testing::expect_eq(reng->get(*rs, "t1")->bytes.size(), static_cast<std::size_t>(1024));
rs->reset();
Void::Testing::require(reng->close().has_value());
// Corrupt a single bit inside table data block in dir -> verify_directory fails!
for (const auto& entry : std::filesystem::directory_iterator(dir.path)) {
const auto name = entry.path().filename().string();
if (name.starts_with("TABLE-") && name.ends_with(".vtbl")) {
auto port = make_posix_file_port();
auto tf = port->open_file(entry.path(), FileOpenMode::ReadWriteExisting);
Void::Testing::require(tf.has_value());
std::byte b{};
Void::Testing::require((*tf)->pread_exact(kTableHeaderSize + 12, std::span{&b, 1}).has_value());
b ^= std::byte{0x01};
Void::Testing::require((*tf)->pwrite_all(kTableHeaderSize + 12, ByteView{&b, 1}).has_value());
Void::Testing::require((*tf)->sync().has_value());
break;
}
}
auto bad_vr = verify_directory(dir.path);
Void::Testing::expect(!bad_vr.has_value());
Void::Testing::expect(bad_vr.error().kind() == Void::Result::ErrorKind::corrupt);
// Same-directory salvage refused
auto same_sal = salvage_directory(dir.path, dir.path);
Void::Testing::expect(!same_sal.has_value());
// Salvage backup (or WAL) to separate salvage_dir succeeds!
auto sal = salvage_directory(backup_dir.path, salvage_dir.path);
Void::Testing::require(sal.has_value());
Void::Testing::expect(sal->keys_recovered >= 3);
}
// 2. AsyncStorageAdapter C-03 stop-race conformance
{
TempStorageDir adir;
auto fp = std::make_shared<FaultInjectingFilePort>();
OpenOptions opts;
opts.directory = adir.path;
opts.file_port = fp;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
Void::Async::ManualExecutor exec;
AsyncStorageAdapter adapter{*eng, AsyncAdapterOptions{}, &exec};
// Case A: stop before append -> Outcome::NotCommitted
{
std::expected<CommitReceipt, WriteFailure> out = CommitReceipt{};
bool done = false;
auto t = drive_stop_before_append_test(adapter, &out, &done);
t.handle().resume();
Void::Testing::expect(done);
Void::Testing::expect(!out.has_value());
Void::Testing::expect(out.error().outcome == Outcome::NotCommitted);
}
// Case B: stop requested WHILE WAL sync is pending, then sync SUCCEEDS ->
// must still publish index and deliver CommitReceipt once (no stolen cancel!)
{
std::atomic<bool> in_sync{false};
std::atomic<bool> release_sync{false};
fp->set_pause_before_sync([&]() {
in_sync.store(true, std::memory_order_release);
while (!release_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
});
std::stop_source ss;
std::expected<CommitReceipt, WriteFailure> out =
std::unexpected{WriteFailure{{}, Outcome::Unknown}};
std::atomic<int> deliveries{0};
bool done = false;
auto t = drive_tracked_write_test(
adapter, "race_ok", "persisted", ss.get_token(), &out, &deliveries, &done);
t.handle().resume();
while (!in_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
// Stop while sync is pending: nothing delivered yet!
ss.request_stop();
exec.drain();
Void::Testing::expect(!done);
Void::Testing::expect_eq(deliveries.load(), 0);
// Let sync succeed -> CommitReceipt delivered exactly once & visible!
release_sync.store(true, std::memory_order_release);
while (!done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
fp->set_pause_before_sync({});
Void::Testing::expect_eq(deliveries.load(), 1);
Void::Testing::require(out.has_value());
auto snap = eng->snapshot();
Void::Testing::require(snap.has_value());
Void::Testing::expect_eq(eng->get(*snap, "race_ok")->as_string_view(),
std::string_view{"persisted"});
}
// Case C: sync FAILS after append while stop requested -> Outcome::Unknown + RecoveryRequired, single delivery
{
std::atomic<bool> in_sync{false};
std::atomic<bool> release_sync{false};
fp->set_pause_before_sync([&]() {
in_sync.store(true, std::memory_order_release);
while (!release_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
});
fp->add_rule(FaultRule{
.op = FaultOp::SyncFile,
.path_contains = "WAL-",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
std::stop_source live_ss;
std::expected<CommitReceipt, WriteFailure> out = CommitReceipt{};
std::atomic<int> deliveries{0};
bool done = false;
auto t = drive_tracked_write_test(
adapter, "race_fail", "uncertain", live_ss.get_token(), &out, &deliveries, &done);
t.handle().resume();
while (!in_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
live_ss.request_stop();
release_sync.store(true, std::memory_order_release);
while (!done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
fp->set_pause_before_sync({});
Void::Testing::expect_eq(deliveries.load(), 1);
Void::Testing::expect(!out.has_value());
Void::Testing::expect(out.error().outcome == Outcome::Unknown);
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
}
adapter.close_and_join();
}
}
} // namespace