Author SHA1 Message Date
faumaray 76ad7d1b39 docs(workflow): record Wave 7 verification evidence and tasks 2026-11-26 15:48:13 +03:00
faumaray 84e6fe81ed fix(sqlite): eliminate lock-order inversion between progress trampoline and interrupt_mu 2026-11-26 15:43:02 +03:00
faumaray fdf0da5ca8 feat(storage): implement original V1 durable Storage engine, tools, and async adapter 2026-11-26 15:32:43 +03:00
faumaray 427cc9a843 feat(sqlite): harden Sqlite lifecycle/transactions/migrations/ops and add SqliteAsync pool 2026-11-26 15:17:59 +03:00
faumaray 9925ea1764 docs(workflow): add Wave 7 task specs for Sqlite, SqliteAsync, and Storage 2026-11-25 21:15:10 +03:00
faumaray 43922d1ad4 merge: Wave 6B P2 Crypto, Security, Archive, and Update hardening 2026-11-25 21:12:30 +03:00
faumaray 9ef425c36c docs(workflow): record Wave 6B verification evidence and tasks 2026-11-25 21:12:30 +03:00
faumaray 47736cb6ce feat(update): fix schema-3 verify-before-parse and add replay floor, TrustStore, pin pruning, and InstallCoordinator 2026-11-25 21:04:52 +03:00
faumaray 00d7478335 feat(archive): add streaming Reader, atomic StagedTree publication, reproducible creation, and isolated worker 2026-11-25 20:54:10 +03:00
faumaray 713d2dc656 feat(security): add SecureBuffer, VSEC envelopes, authorization, and SecurityAsync Authenticator 2026-11-25 20:44:31 +03:00
faumaray eb42228604 feat(crypto): harden Crypto primitives and add optional CryptoAsync adapter 2026-11-25 06:28:50 +03:00
faumaray 8a1c15f9c0 docs(workflow): add Wave 6B task specs for Crypto, Security, Archive, Update 2026-11-25 06:03:36 +03:00
faumaray acd77ee67a feat(data): support RFC 8259 decimal numbers in StrictJson 2026-11-25 05:59:21 +03:00
faumaray 9931c5ffc4 Merge feat/roadmap-p2-wave6a: P2 System, SystemAsync, and IPC 2026-11-24 15:37:17 +03:00
faumaray e43eee738c docs(workflow): record Wave 6A verification evidence and tasks 2026-11-24 15:36:45 +03:00
faumaray 39a48d5c0a feat(IPC): add V1 VDIP framed codec, quota reservations, local UDS/pipe transport, full-duplex Session, and IPCOnly consumer (S-IPC-01..03) 2026-11-24 15:27:40 +03:00
faumaray 9a3c5d86ef feat(SystemAsync): add async IO ProcessManager/communicate and shared WatcherService with WatchSubscription (M-SYSTEM-03, M-SYSTEM-04) 2026-11-24 14:46:46 +03:00
faumaray fcdbc063b2 feat(System): harden OwnedFd/Child process spawn, full-duplex bounds, durable replace_file, safe TempFile/TempDir, and SystemOnly consumer (M-SYSTEM-01, M-SYSTEM-02, M-SYSTEM-05) 2026-11-24 14:32:05 +03:00
faumaray 3f67b1ecb7 chore(wave6a): reserve P2 error domains, guard IO pipe SIGPIPE, extend ProcessHelper, and add Wave 6A specs 2026-11-24 10:56:39 +03:00
faumaray 44799602c9 Merge feat/roadmap-p2-wave5: P2 Observability, Resilience, Log, and Stacktrace 2026-11-24 10:39:26 +03:00
136 changed files with 35163 additions and 1214 deletions

No files matched your search

+101 -6
View File
@@ -1,8 +1,8 @@
# Workflow state
Updated: 2026-11-24.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave5` (from `main`
at `1e901ce`, merged Waves 1–4B and pushed to `origin/main`).
Updated: 2026-11-26.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave7` (from `main`
at `43922d1`, merged Waves 1–6B and pushed to `origin/main`).
## Completed objective
@@ -215,8 +215,103 @@ while leaving local untracked files untouched.
`binary_reader_u64_be` 2.24 ns, `data_json_parse_small_object` 576.81 ns,
`data_json_serialize_small_object` 284.87 ns.
## Verification already observed (Wave 6A — P2 System, SystemAsync, IPC)
- Wave 6A prep & P2/P3 error domains (`3f67b1e`): reserved `kIpcErrorDomain = 16`..
`kSqliteErrorDomain = 21` in `Error.hpp`, added thread-safe pipe `ENOTSOCK` fallback in
`EpollDriver.cpp`, enabled `VoidProcessHelper` for `Void::System` OR `Void::IPC`, added
`M-SYSTEM-01-05.md` and `S-IPC-01-03.md`.
- `System` (`fcdbc06`): `System;Testing` (`/tmp/void-w6a-system`, `-Werror`) `System*`
53/53 passed (226.6 ms); `ctest` 2/2 (`VoidTests` 0.57 s,
`VoidInstalledComponentConsumers` including `SystemOnly` 3.95 s).
- `SystemAsync` (`9a3c5d8`): `SystemAsync;Testing` (`/tmp/void-w6a-sysasync`, `-Werror`)
`SystemAsync*` 2/2 passed (211.5 ms); `ctest` 2/2 (`VoidTests` 1.15 s,
`VoidInstalledComponentConsumers` including `SystemAsyncOnly` 9.43 s).
- `IPC` (`39a48d5`): `IPC;Testing` (`/tmp/void-w6a-ipc`, `-Werror`) `Ipc*` 3/3 passed
(8.8 ms); `ctest` 2/2 (`VoidTests` 0.49 s, `VoidInstalledComponentConsumers` including
`IPCOnly` 12.20 s, total 12.70 s).
- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6a-full`, 39 modules,
`39a48d5`): `VoidTests` 1,386 tests — 1,383 passed, 3 intentional skips
(`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (4.68 s);
`ctest` 2/2 passed (`VoidTests` 4.58 s, `VoidInstalledComponentConsumers` 19 consumer
builds incl. `SystemOnly`, `SystemAsyncOnly`, `IPCOnly`, `RelocatedFoundation`,
`RelocatedExternal`, 31.05 s, total 35.63 s).
- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6a-asan`, 39
modules, `39a48d5`): `VoidTests` 1,386 tests — 1,383 passed, 3 skipped, 0 failed
(19.34 s), 0 ASan/LSan leaks, 0 UBSan errors.
- Wave 6A Debug TSan subset (`/tmp/void-w6a-tsan`, 14 modules, `39a48d5`):
`Process*|SystemHardening*|SystemAsync*|Ipc*|FileWatcher*|IoDriver*|OperationScope*`
35/35 passed (609.4 ms), 0 TSan data races.
- `VoidFoundationBench` post-W6A (`rev=39a48d5c0a72`, `/tmp/void-w6a-full/post-w6a.json`):
`harness_empty_loop` 0.38 ns, `core_uuid_parse_hyphenated` 24.92 ns,
`core_uuid_to_string` 17.45 ns, `core_hash_fnv1a64_256b` 181.41 ns,
`core_hash_murmur3_256b` 67.93 ns, `functional_result_ok_chain` 1.13 ns,
`functional_error_with_context` 58.77 ns, `math_checked_add_loop` 0.47 ns,
`containers_spsc_ring_push_pop` 8.80 ns, `containers_lru_get_put` 20.61 ns,
`binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 311.16 ns,
`data_json_serialize_small_object` 162.52 ns.
## Verification already observed (StrictJson RFC 8259 decimals — `acd77ee`, on `main`)
- Added `ParseOptions{maximumDepth, allowDecimals = true}` and `double` variant
alternative to `Void::Json::Strict` (`include/Void/Data/StrictJson.hpp`) for LSP
messages while preserving exact `int64_t` integer semantics and `allowDecimals = false`
opt-out (`tests/standalone/Data/StrictJson.cpp` 6/6 tests).
- Verified in RelWithDebInfo `-Werror` (`49/49`, `ctest` 2/2) and Debug ASan+UBSan
`-Werror` (`/tmp/void-strictjson-asan`, `49/49` in 7.0 ms, 0 leaks, 0 UB); pushed to
`origin/main`.
## Verification already observed (Wave 6B — P2 Crypto, Security, Archive, Update)
- Wave 6B task specs (`8a1c15f`): added `M-CRYPTO-01-05.md`, `M-SECURITY-01-04.md`,
`M-ARCHIVE-01-05.md`, and `M-UPDATE-01-06.md`.
- `Crypto` & `CryptoAsync` (`eb42228`): `Crypto;CryptoAsync;Testing` (`/tmp/void-w6b-crypto`,
`-Werror`, `-p openssl`, 10 modules) `Crypto*|crypto_*` 8/8 (`Crypto` 3,
`CryptoHardening` 3, `CryptoAsync` 2); `ctest` 2/2 (`7.22 s`, including `CryptoOnly` &
`CryptoAsyncOnly`).
- `Security` & `SecurityAsync` (`713d2dc`): `Security;SecurityAsync;Testing`
(`/tmp/void-w6b-security`, `-Werror`, `-p libsodium`, 10 modules) `Security*|security_*`
14/14 (`720.7 ms`: `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2);
`ctest` 2/2 (`8.46 s`, including `SecurityOnly` & `SecurityAsyncOnly`).
- `Archive` (`00d7478`): `Archive;Testing` (`/tmp/void-w6b-archive`, `-Werror`,
`-p libarchive`, 7 modules) `Archive*|archive_*` 9/9 (`259.0 ms`: `Archive` 6,
`ArchiveHardening` 3); `ctest` 2/2 (`5.76 s`, including `ArchiveOnly`).
- `Update` (`47736cb`): `Update;Testing` (`/tmp/void-w6b-update`, `-Werror`,
`-p libarchive -p openssl`, 12 modules) `Update*|update_*|component_feed_*|readable_component_*|version_store_*`
25/25 (`1.91 s`: `Update` 22, `UpdateHardening` 3); `ctest` 2/2 (`10.64 s`, including
`UpdateOnly`).
- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6b-full`, 41 modules,
`47736cb`): `VoidTests` 1,406 tests — 1,403 passed, 3 intentional skips
(`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed
(`6.26 s`); `ctest` 2/2 passed (`VoidTests` 7.34 s, `VoidInstalledComponentConsumers`
all 25 consumers incl. `CryptoOnly`, `CryptoAsyncOnly`, `SecurityOnly`,
`SecurityAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `RelocatedFoundation`,
`RelocatedExternal`, 40.73 s, total 48.07 s).
- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6b-asan`, 41
modules, `47736cb`): `VoidTests` 1,406 tests — 1,403 passed, 3 skipped, 0 failed
(`21.78 s`), 0 ASan/LSan leaks, 0 UBSan errors.
- Wave 6B Debug TSan subset (`CryptoAsync;SecurityAsync;Update;Testing`,
`/tmp/void-w6b-tsan`, 20 modules, `47736cb`): 56/56 passed (`4.86 s`), 0 TSan data races.
- `VoidFoundationBench` post-W6B (`rev=47736cb6ce2f`, `/tmp/void-w6b-full/post-w6b.json`):
`harness_empty_loop` 0.38 ns, `core_uuid_parse_hyphenated` 24.52 ns,
`core_uuid_to_string` 16.53 ns, `core_hash_fnv1a64_256b` 179.95 ns,
`core_hash_murmur3_256b` 67.37 ns, `functional_result_ok_chain` 1.12 ns,
`functional_error_with_context` 58.37 ns, `math_checked_add_loop` 0.47 ns,
`containers_spsc_ring_push_pop` 8.76 ns, `containers_lru_get_put` 21.02 ns,
`binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 333.32 ns,
`data_json_serialize_small_object` 165.99 ns.
### Wave 7 (P2 Persistence & Storage: `Sqlite`, `SqliteAsync`, and NEW Original `Storage` — `G-STORE` Gate)
- Task specs committed on `feat/roadmap-p2-wave7` (`9925ea1`): `tasks/M-SQLITE-01-05.md`, `tasks/S-STORAGE-01-06.md`.
- **`Void::Sqlite` & `Void::SqliteAsync`** (`427cc9a`, TSan lock-order fix `84e6fe8`): hardened `ConnectionState`, `open_database`/`OpenOptions` with checked WAL/FULL/`foreign_keys` pragmas and disabled extension loading, checked positional/named binds, borrowed lifetime owners, strict typed `RowView`/getters, `Transaction` (`sqlite3_get_autocommit`), `Savepoint`, `close()` busy guard, `migrate_checked` with `_void_schema_migrations`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, plus optional `Void::SqliteAsync` (`AsyncPool`, bounded workers, leased interrupt cleanup) and `SqliteOnly`/`SqliteAsyncOnly` installed consumers.
- **`Void::Storage` (`G-STORE` Gate)** (`fdf0da5`): built NEW original durable single-writer key-value storage engine with zero SQLite or external dependencies (`Crc32c`, `Types`, `FilePort`/`PosixFilePort`/`FaultInjectingFilePort`, V1 binary codecs `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1`, `Batch` with preconditions, `Engine` with bootstrap/recovery/tail-truncation/checkpoint/incremental compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance) and `StorageOnly` installed consumer.
- Integrated verification (`84e6fe8`): `VoidTests` 1,417 tests (1,414 passed, 3 intentionally skipped hardware/root checks, 0 failed across 43 modules in 21.06s), `ctest` 2/2 (all 28 installed consumers in 65.05s), Debug ASan+UBSan 1,417 tests (0 leaks, 0 UB in 36.47s), TSan (`SqliteAsync;Storage;Testing`) 19/19 in 15.38s with 0 warnings, and post-Wave-7 `VoidFoundationBench`.
## Ownership and next step
Waves 1–5 (`P0`, `P1`, and `P2` Operations Foundations: `Observability`, `Resilience`,
`Log`, `Stacktrace`) are complete and verified on `feat/roadmap-p2-wave5`, ready to merge
into `main`, push to `origin`, and proceed continuously to **P2 Wave 6**.
Waves 1–7 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`,
`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`, and
`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`) are complete and verified on
`feat/roadmap-p2-wave7`, ready to merge `--no-ff` into `main`, push to `origin`, and
proceed continuously to **Wave 8 (`Configuration`, `Fsm`, `Plugin`, `Service`)**.
+31
View File
@@ -70,6 +70,37 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| CMake test header check fix | Track `VOID_ACTIVE_PUBLIC_HEADERS` in `cmake/Module.cmake` so `tests/CMakeLists.txt` maps split `EXTRA_HEADERS` (e.g. `Void/Log/Log.hpp` -> `LogState`) accurately (`3d8dfb0`) | — | VERIFIED | `Stacktrace;Testing` discovers and passes `Stacktrace*` 4/4 without `Log`; full suite discovers all 1,378 tests |
| M-STACKTRACE-01..04 | `src/Stacktrace/module.cmake` (`INTERNAL_DEPS Functional Time LogState`), split `capture()` (<=256 frames, zero log/source IO) & `Resolver` (1024-entry / 4 MiB cache, `invalidate_module`), `Capabilities`, checked `read_source_snippet_checked` (roots, symlink-escape & `..` rejection, overflow-safe `int64_t` math), `format_resolved_trace`, `write_fatal_signal_marker`, `tests/standalone/Stacktrace/Stacktrace.cpp` (`7b57b35`) | [M-STACKTRACE-01-04](tasks/M-STACKTRACE-01-04.md) | VERIFIED | `Stacktrace;Testing` `Stacktrace*` 4/4 (374.2ms), full RelWithDebInfo (1,375 ✔) & ASan+UBSan (0 leaks/UB) |
## Wave 6A — P2 System, SystemAsync, IPC (`feat/roadmap-p2-wave6a`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| Wave 6A prep, error domains & helper modes | Reserved P2/P3 domain IDs (`kIpcErrorDomain = 16`..`kSqliteErrorDomain = 21`) in `Error.hpp`, thread-safe pipe `ENOTSOCK` fallback in `EpollDriver.cpp`, enabled `VoidProcessHelper` for `Void::System` OR `Void::IPC` with `ignore-sigterm`, `simultaneous-io`, `flood`, `long-line`, `check-fds`, `env-dump`, `cwd`, `ipc-pipe-echo`, task specs (`3f67b1e`) | — | VERIFIED | Compiled cleanly with `-Werror`; verified via Wave 6A `System`, `SystemAsync`, `IPC`, ASan+UBSan, and TSan suites |
| M-SYSTEM-01..05 | Hardened `System` (`Types.hpp`, `Process.{hpp,cpp}`, `Path.hpp`, `Query.hpp`, `TempFile.hpp`, `TempDir.hpp`, `Metrics.hpp`), strict non-shell spawning + fd hygiene, pipe/arg limits, duplex `communicate()` & bounded escalation, `query_process` /proc validation, symlink-safe atomic `TempFile`/`TempDir`, `/bin/sh`-free `ProcessStream.cpp`, `SystemHardening.cpp`, `SystemOnly` consumer (`fcdbc06`) | [M-SYSTEM-01-05](tasks/M-SYSTEM-01-05.md) | VERIFIED | `System*` 53/53 (`226.6ms`), `ctest` 2/2 (`SystemOnly` `3.95s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `16/16` (0 races) |
| M-SYSTEM-06 | Split async `SystemAsync` (`INTERNAL_DEPS System Async IO Time Functional LogState`, `EXTRA_HEADERS` `AsyncProcess.hpp`/`AsyncWatcher.hpp`), `ProcessManager`, `ManagedChild`, async `communicate`/`wait`/`close_and_join`, `WatcherService`/`WatchSubscription`, `SystemAsync.cpp`, `SystemAsyncOnly` consumer (`9a3c5d8`) | [M-SYSTEM-01-05](tasks/M-SYSTEM-01-05.md) | VERIFIED | `SystemAsync*` 2/2 (`211.5ms`), `ctest` 2/2 (`SystemAsyncOnly` `9.43s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `2/2` (0 races) |
| S-IPC-01..03 | New `IPC` module (`src/IPC/module.cmake`, `Types.hpp`, `Codec.hpp`, `Transport.hpp`, `Session.hpp`, `IPC.hpp`), V1 `VDIP` 24B big-endian framing & pre-alloc `BufferQuota`/`QuotaPermit`, `LocalListener`/`connect_local` (`O_NOFOLLOW`, `0700`/`0600`, `flock`, `SO_PEERCRED` fail-closed), `adopt_pipe_pair`/`create_socket_pair_transports`, full-duplex `Session` with control lane/tombstones/token-bucket/graceful drain, `Ipc.cpp`, `IPCOnly` consumer (`39a48d5`) | [S-IPC-01-03](tasks/S-IPC-01-03.md) | VERIFIED | `Ipc*` 3/3 (`8.8ms`), `ctest` 2/2 (`IPCOnly` `12.20s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `3/3` (0 races) |
## Out-of-band Priority Fix (`main`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| StrictJson decimals | RFC 8259 decimal numbers (`double` variant alternative + `ParseOptions::allowDecimals = true`) in `Void::Json::Strict` (`include/Void/Data/StrictJson.hpp`, `tests/standalone/Data/StrictJson.cpp`) (`acd77ee`) | — | VERIFIED | `StrictJson` 6/6 (`49/49` Data suite, `ctest` 2/2), Debug ASan+UBSan `49/49` (0 leaks/UB); pushed to `origin/main` |
## Wave 6B — P2 Crypto, Security, Archive, Update (`feat/roadmap-p2-wave6b`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| M-CRYPTO-01..05 | Hardened `Crypto` (OpenSSL 3.5.9 non-deprecated `EVP_MD`/`EVP_MAC`/`EVP_KDF`/`EVP_PKEY`, poisoned `Hasher`, 16 MiB Ed25519 cap, 4 KiB HKDF cap & overlap/wipe guards, `constant_time_equal`, `secure_wipe`, `kCryptoErrorDomain = 18`) + optional `CryptoAsync` (`hash_stream`, `AsyncFileHasher` 8/32/8 MiB budget, `close_and_join`), `CryptoOnly` & `CryptoAsyncOnly` consumers (`8a1c15f`, `eb42228`) | [M-CRYPTO-01-05](tasks/M-CRYPTO-01-05.md) | VERIFIED | `Crypto` 3 + `CryptoHardening` 3 + `CryptoAsync` 2 = 8/8, `ctest` 2/2 (`7.22s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 8/8 (0 races) |
| M-SECURITY-01..04 | Hardened `Security` (`kSecurityErrorDomain = 19`, `SecureBuffer` with lock policies & wipe counter, input caps, `parse_argon2id_cost`, `verify_password_budgeted`, `VSEC` v1 `xchacha20poly1305_ietf` `Envelope`/`SecretKeyRing` without legacy fallback, bounded default-deny `Authorization`) + `SecurityAsync` (`Authenticator`, `AccountSessionPort`, fail-closed `AuditSink`, `PasswordJobBudget`, `SessionPolicy`, dummy-hash parity, version CAS, `close_and_join`), `SecurityOnly` & `SecurityAsyncOnly` consumers (`713d2dc`) | [M-SECURITY-01-04](tasks/M-SECURITY-01-04.md) | VERIFIED | `SecurityTests` 8 + `SecurityHardening` 4 + `SecurityAsync` 2 = 14/14 (`720.7ms`), `ctest` 2/2 (`8.46s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 14/14 (0 races) |
| M-ARCHIVE-01..05 | Hardened `Archive` (`kArchiveErrorDomain = 17`, streaming `Reader` + forensic listing, file-as-parent conflict rejection, exclusive `0700` `StagedTree` + bottom-up `fsync` + Linux `SYS_renameat2(RENAME_NOREPLACE)` atomic `publish()` with `PublicationOutcome::Unknown`, `cleanup_stale_staging`, reproducible `O_NOFOLLOW` `create_archive`, isolated `VoidArchiveWorker` extraction with rlimits + RSS check + parent inventory verification), `ArchiveOnly` consumer (`00d7478`) | [M-ARCHIVE-01-05](tasks/M-ARCHIVE-01-05.md) | VERIFIED | `Archive` 6 + `ArchiveHardening` 3 = 9/9 (`259.0ms`), `ctest` 2/2 (`5.76s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 9/9 (0 races) |
| M-UPDATE-01..06 | Hardened `Update` (`kUpdateErrorDomain = 20`, schema-3 verify-before-payload-parse fix, `StrictJsonProfile` integer-only option, non-forgeable `VerifiedSelection`, `VersionStore::pruneWithPins`, atomic checksummed `ReplayFloorStore`, Ed25519 `TrustStore` rotation/revocation, `ArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` halting with `RecoveryRequired`, `InstallCoordinator` with staged archive + `CleanupPending` + idempotent `reconcile`/`retry_cleanup`), `UpdateOnly` consumer (`47736cb`) | [M-UPDATE-01-06](tasks/M-UPDATE-01-06.md) | VERIFIED | `Update` 22 + `UpdateHardening` 3 = 25/25 (`1.91s`), `ctest` 2/2 (`10.64s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 25/25 (0 races) |
## Wave 7 — P2 Sqlite, SqliteAsync, and Storage (`feat/roadmap-p2-wave7`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| M-SQLITE-01..05 | Hardened `Sqlite` (`kSqliteErrorDomain = 21`, `ConnectionState`, `OpenOptions` checked WAL/FULL/FK pragmas & disabled extension loading, checked binds & borrowed lifetime owners, typed `RowView`, `Transaction` autocommit/busy guards, `Savepoint`, `migrate_checked`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, TSan lock-order fix outside `interrupt_mu`) + optional `SqliteAsync` (`AsyncPool`), `SqliteOnly` & `SqliteAsyncOnly` consumers (`427cc9a`, `84e6fe8`) | [M-SQLITE-01-05](tasks/M-SQLITE-01-05.md) | VERIFIED | Standalone `Sqlite` 14/14 (`426.5ms`), `ctest` 2/2 (`5.11s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) |
| S-STORAGE-01..06 | NEW original `Void::Storage` (`kStorageErrorDomain = 9`, zero SQLite/external deps, `Crc32c`, `PosixFilePort`/`FaultInjectingFilePort`, V1 `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1` codecs, `Batch` preconditions, single-writer `Engine` with recovery/tail-truncation/checkpoint/compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance), `G-STORE` gate, `StorageOnly` consumer (`fdf0da5`) | [S-STORAGE-01-06](tasks/S-STORAGE-01-06.md) | VERIFIED | Standalone zero-ext-deps `Storage` 5/5 (`14.53s`), `ctest` 2/2 (`24.07s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) |
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
+43
View File
@@ -230,3 +230,46 @@ Branch: `feat/roadmap-p2-wave5` (branched from `main` at `1e901ce`, which was pu
| Full Integrated ASan+UBSan (`7b57b35`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w5-asan`, 37 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w5-asan/tests/VoidTests` | Initial run hit 1 timing assertion in unrelated existing `internal_fsm_service_hot_reload_under_load` (`FsmServiceHotReload.cpp:119`, 0 leaks/UB); full re-run on same binary passed 1,378 tests — 1,375 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (50.16s), 0 ASan/LSan leaks, 0 UBSan errors |
| Wave 5 TSan Subset (`7b57b35`) | `dev cpp-gcc -c` Debug (`Observability;ResilienceAsync;Log;IO;Async;Time;Testing`, `/tmp/void-w5-tsan`, 15 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w5-tsan/tests/VoidTests --filter "Observability*\|ResilienceHardening*\|AsyncPolicy*\|Log*\|AsyncLogger*\|LogScopeSnapshot*\|Io*\|OperationScope*"` | 68/68 passed (7.01s, including `AsyncLogger::async_multi_producer_no_loss` 6.53s, `Observability` 4/4, `ResilienceHardening` 4/4, `AsyncPolicy` 2/2, `Log` 12/12, `LogHardening` 4/4, `LogScopeSnapshot` 3/3, `IoDriver` 4/4, `OperationScope` 5/5), 0 TSan data races |
| Post-W5 Benchmark (`7b57b35`, `rev=7b57b355cd75`) | `/tmp/void-w5-full/benchmarks/VoidFoundationBench --json /tmp/void-w5-full/post-w5.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.75ns, `core_uuid_parse_hyphenated` 43.49ns, `core_uuid_to_string` 32.51ns, `core_hash_fnv1a64_256b` 213.37ns, `core_hash_murmur3_256b` 92.34ns, `functional_result_ok_chain` 1.65ns, `functional_error_with_context` 94.82ns, `math_checked_add_loop` 0.86ns, `containers_spsc_ring_push_pop` 10.76ns, `containers_lru_get_put` 31.99ns, `binary_reader_u64_be` 2.24ns, `data_json_parse_small_object` 576.81ns, `data_json_serialize_small_object` 284.87ns |
## Wave 6A / P2 System, SystemAsync, IPC Verification (2026-11-24)
Branch: `feat/roadmap-p2-wave6a` (branched from `main` at `4479960`, which was pushed to `origin/main`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2.
| Scope | Command & configuration | Observed outcome |
| --- | --- | --- |
| M-SYSTEM-01..05 (`3f67b1e`, `fcdbc06`) | `System;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-system` (`VoidTests --filter "System*"`, `ctest`) | `System*` 53/53 passed (226.6ms); `ctest` 2/2 passed (`VoidTests` 0.57s, `VoidInstalledComponentConsumers` including `SystemOnly` 3.95s) |
| M-SYSTEM-06 (`9a3c5d8`) | `SystemAsync;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-sysasync` (`VoidTests --filter "SystemAsync*"`, `ctest`) | `SystemAsync*` 2/2 passed (211.5ms); `ctest` 2/2 passed (`VoidTests` 1.15s, `VoidInstalledComponentConsumers` including `SystemAsyncOnly` 9.43s) |
| S-IPC-01..03 (`39a48d5`) | `IPC;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w6a-ipc` (`VoidTests --filter "Ipc*"`, `ctest`) | `Ipc*` 3/3 passed (8.8ms); `ctest` 2/2 passed (`VoidTests` 0.49s, `VoidInstalledComponentConsumers` including `IPCOnly` 12.20s, total 12.70s) |
| Full Integrated RelWithDebInfo (`39a48d5`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w6a-full`, 39 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w6a-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w6a-full --output-on-failure --timeout 300` | `VoidTests`: 1,386 tests — 1,383 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (4.68s); `ctest`: 2/2 passed (`VoidTests` 4.58s + `VoidInstalledComponentConsumers` 31.05s across 19 consumer runs incl. `SystemOnly`, `SystemAsyncOnly`, `IPCOnly`, `RelocatedFoundation`, `RelocatedExternal`, total 35.63s) |
| Full Integrated ASan+UBSan (`39a48d5`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6a-asan`, 39 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-asan/tests/VoidTests` | 1,386 tests — 1,383 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (19.34s), 0 ASan/LSan leaks, 0 UBSan errors |
| Wave 6A TSan Subset (`39a48d5`) | `dev cpp-gcc -c` Debug (`SystemAsync;IPC;IO;Async;Resilience;Testing`, `/tmp/void-w6a-tsan`, 14 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-tsan/tests/VoidTests --filter "Process*\|SystemHardening*\|SystemAsync*\|Ipc*\|FileWatcher*\|IoDriver*\|OperationScope*"` | 35/35 passed (609.4ms: `OperationScope` 5, `IoDriver` 4, `Ipc` 3, `FileWatcher` 5, `Process` 10, `ProcessStream` 3, `SystemHardening` 3, `SystemAsync` 2), 0 TSan data races |
| Post-W6A Benchmark (`39a48d5`, `rev=39a48d5c0a72`) | `/tmp/void-w6a-full/benchmarks/VoidFoundationBench --json /tmp/void-w6a-full/post-w6a.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.92ns, `core_uuid_to_string` 17.45ns, `core_hash_fnv1a64_256b` 181.41ns, `core_hash_murmur3_256b` 67.93ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.77ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.61ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 311.16ns, `data_json_serialize_small_object` 162.52ns |
## StrictJson RFC 8259 Decimal Verification (2026-11-25)
Branch: `main` (`acd77ee`, pushed to `origin/main`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2.
| Scope | Command & configuration | Observed outcome |
| --- | --- | --- |
| StrictJson decimals (`acd77ee`) | RelWithDebInfo `-Werror` Data suite & `ctest`, plus Debug ASan+UBSan `-Werror` (`/tmp/void-strictjson-asan`) | RelWithDebInfo: `49/49` (`StrictJson` 6/6), `ctest` 2/2 passed; Debug ASan+UBSan: `49/49` (7.0ms), 0 leaks, 0 UB |
## Wave 6B / P2 Crypto, Security, Archive, Update Verification (2026-11-25)
Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2, OpenSSL 3.5.9, libsodium 1.0.22, libarchive 3.8.10, SQLite 3.54.0.
| Scope | Command & configuration | Observed outcome |
| --- | --- | --- |
| M-CRYPTO-01..05 (`8a1c15f`, `eb42228`) | `Crypto;CryptoAsync;Testing` RelWithDebInfo `-Werror` `-p openssl` `/tmp/void-w6b-crypto` (10 modules, `VoidTests`, `ctest`) | `CryptoHardening` 3 + `CryptoAsync` 2 (+ `Crypto` 3) passed; `ctest` 2/2 passed (`7.22s`, incl. `CryptoOnly` & `CryptoAsyncOnly`) |
| M-SECURITY-01..04 (`713d2dc`) | `Security;SecurityAsync;Testing` RelWithDebInfo `-Werror` `-p libsodium` `/tmp/void-w6b-security` (10 modules, `VoidTests`, `ctest`) | `Security*\|security_*` 14/14 passed (`720.7ms`: `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2); `ctest` 2/2 passed (`8.46s`, incl. `SecurityOnly` & `SecurityAsyncOnly`) |
| M-ARCHIVE-01..05 (`00d7478`) | `Archive;Testing` RelWithDebInfo `-Werror` `-p libarchive` `/tmp/void-w6b-archive` (7 modules, `VoidTests`, `ctest`) | `Archive*\|archive_*` 9/9 passed (`259.0ms`: `Archive` 6, `ArchiveHardening` 3); `ctest` 2/2 passed (`5.76s`, incl. `ArchiveOnly`) |
| M-UPDATE-01..06 (`47736cb`) | `Update;Testing` RelWithDebInfo `-Werror` `-p libarchive -p openssl` `/tmp/void-w6b-update` (12 modules, `VoidTests`, `ctest`) | `Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*` 25/25 passed (`1.91s`: `Update` 22, `UpdateHardening` 3); `ctest` 2/2 passed (`10.64s`, incl. `UpdateOnly`) |
| Full Integrated RelWithDebInfo (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w6b-full`, 41 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w6b-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w6b-full --output-on-failure --timeout 300` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`6.26s`); `ctest`: 2/2 passed (`VoidTests` 7.34s + `VoidInstalledComponentConsumers` 40.73s across 25 consumer runs incl. `CryptoOnly`, `CryptoAsyncOnly`, `SecurityOnly`, `SecurityAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `RelocatedFoundation`, `RelocatedExternal`, total `48.07s`) |
| Full Integrated ASan+UBSan (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6b-asan`, 41 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w6b-asan/tests/VoidTests` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`21.78s`), 0 ASan/LSan leaks, 0 UBSan errors |
| Wave 6B TSan Subset (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p libsodium` Debug (`CryptoAsync;SecurityAsync;Update;Testing`, `/tmp/void-w6b-tsan`, 20 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6b-tsan/tests/VoidTests --filter "Crypto*\|crypto_*\|Security*\|security_*\|Archive*\|archive_*\|Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*"` | 56/56 passed (`4.86s`: `Archive` 6, `ArchiveHardening` 3, `Crypto` 3, `CryptoHardening` 3, `CryptoAsync` 2, `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2, `Update` 22, `UpdateHardening` 3), 0 TSan data races |
| Post-W6B Benchmark (`47736cb`, `rev=47736cb6ce2f`) | `/tmp/void-w6b-full/benchmarks/VoidFoundationBench --json /tmp/void-w6b-full/post-w6b.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.52ns, `core_uuid_to_string` 16.53ns, `core_hash_fnv1a64_256b` 179.95ns, `core_hash_murmur3_256b` 67.37ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 58.37ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.76ns, `containers_lru_get_put` 21.02ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 333.32ns, `data_json_serialize_small_object` 165.99ns |
| Wave 7 `Sqlite` & `SqliteAsync` standalone (`84e6fe8`) | `dev cpp-gcc -p sqlite` RelWithDebInfo (`-Werror`, `/tmp/void-w7-sqlite`), 8 modules, `VoidTests --filter 'Sqlite*\|...'` + `ctest` | **PASSED**: `SqliteTests` 8 + `SqliteHardening` 4 + `SqliteAsync` 2 = 14/14 in `426.5ms`; `ctest` 2/2 in `5.11s` (`VoidTests` 0.87s, `VoidInstalledComponentConsumers` including `SqliteOnly` & `SqliteAsyncOnly` 4.23s) |
| Wave 7 `Storage` standalone (`fdf0da5`, `G-STORE`) | `dev cpp-gcc` zero `-p` external deps RelWithDebInfo (`-Werror`, `/tmp/void-w7-storage`), 10 modules, `VoidTests --filter '^storage_'` + `ctest` | **PASSED**: `Storage` 5/5 in `14.53s`; `ctest` 2/2 in `24.07s` (`StorageOnly` verified with Boost/LibArchive/OpenSSL/PkgConfig/SQLite3/Threads disabled) |
| Wave 7 TSan (`84e6fe8`) | `dev cpp-gcc -p sqlite` Debug TSan (`-Werror`, `/tmp/void-w7-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 12 modules (`SqliteAsync;Storage;Testing`) | **PASSED**: 19/19 in `15.38s` (`SqliteTests` 8, `SqliteHardening` 4, `SqliteAsync` 2, `Storage` 5), exit 0, 0 TSan data races / lock-order warnings |
| Wave 7 integrated RelWithDebInfo + consumers (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w7-full`), 43 modules, `VoidTests` + `ctest` | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `21.06s`; `ctest` 2/2 in `65.05s` (`VoidTests` 20.95s, all 28 installed consumers 44.10s) |
| Wave 7 full Debug ASan+UBSan (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w7-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 43 modules | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `36.47s`, 0 leaks, 0 UB |
| Post-W7 Benchmark (`84e6fe8`, `VOID_GIT_REV=fdf0da5ca883`) | `/tmp/void-w7-full/benchmarks/VoidFoundationBench --json /tmp/void-w7-full/post-w7.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 25.06ns, `core_uuid_to_string` 16.69ns, `core_hash_fnv1a64_256b` 181.03ns, `core_hash_murmur3_256b` 67.90ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.24ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.62ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 310.70ns, `data_json_serialize_small_object` 160.98ns |
@@ -0,0 +1,26 @@
# Archive Streaming Reader, Atomic Staged Publication, Reproducible Creation & Child Isolation
Task ID: M-ARCHIVE-01..05
Phase: P2 (Wave 6B)
Status: APPROVED
Contracts: C-02, C-03, C-04, C-05, C-06, C-07
## 1. Context and baseline
`Void::Archive` preserves the existing incremental `extract(path, destination, ExtractionOptions)` API and anti-traversal/symlink-swap/size-limit tests while adding typed error reporting (`kArchiveErrorDomain = 17`), bounded streaming `Reader` (`open_reader`, `next_entry`, `read_chunk`, `skip_entry`, normal/forensic `list_entries`), atomic staged extraction and no-replace directory publication (`StagedTree`, `extract_staged`, `publish`, `cleanup_stale_staging`), reproducible tar/tar.zstd creation (`create_archive`), and hardened child-process isolated extraction (`extract_staged_isolated`, `run_isolated_worker_main`).
## 2. Deliverables
- `src/Archive/module.cmake` (`INTERNAL_DEPS Functional Time System`, `EXTERNAL_DEPS LibArchive::LibArchive`).
- `include/Void/Archive/Types.hpp`: `kArchiveErrorDomain = 17`, `ArchiveErrorCode`, `make_archive_error`, `ReadLimits` (10,000 entries, 512 MiB file, 2 GiB total, 1 GiB compressed, 8 MiB metadata, 64 KiB transfer chunk, 4 KiB path, 255B component, 64 components), `EntryInfo`, `ProgressEvent`, `PublicationOutcome`, `PublicationReceipt`, `CreationOptions`, `IsolationOptions` (128 MiB RSS, 60s timeout), `ByteSource`/`ByteSink` + span/vector/file adapters.
- `include/Void/Archive/Archive.hpp`, `src/Archive/Archive.cpp`, `src/Archive/StagedArchive.cpp`: preserve `extract()`; add `Reader`, `list_entries` (normal + opt-in forensic), `StagedTree`, `extract_staged` (exclusive `0700` dir, `O_NOFOLLOW`, `0644`/`0755`, bottom-up dir `fsync`, completion inventory, no-follow cleanup), `publish` via Linux `renameat2(..., RENAME_NOREPLACE)` (`unsupported_capability` on `ENOSYS`/`EINVAL`, `PublicationOutcome::Unknown` on post-rename parent `fsync` failure), `cleanup_stale_staging`, reproducible `create_archive`, and `extract_staged_isolated` / `run_isolated_worker_main` via `Void::Process::spawn` (ASan-safe rlimits + parent verification of staged inventory).
- `tests/helpers/ArchiveWorker.cpp` wired as `VoidArchiveWorker` in `tests/CMakeLists.txt`, `tests/standalone/Archive/ArchiveHardening.cpp`, `tests/package/ArchiveOnly/*`, registered in `tests/package/InstalledComponents.cmake`.
## 3. Edge cases
- `skip_entry` still decodes and accounts for actual decompressed bytes against per-entry and total limits.
- File-as-parent path conflicts (e.g. file `a` followed by `a/b`, or `a/b` followed by file `a`) and non-zero/zero invalid limits are rejected cleanly.
- Diagnostics cap path rendering at 4 KiB and escape control characters / attacker newlines.
- Post-rename parent `fsync` failure reports `PublicationOutcome::Unknown` without falsely claiming rollback; pre-publish failure cleans only the owned staging descriptor and preserves primary error + staging id if cleanup fails.
- Under `__SANITIZE_ADDRESS__`, child worker avoids fatal `RLIMIT_AS` and enforces `RLIMIT_CPU`/`RLIMIT_FSIZE`/`RLIMIT_NOFILE` + `/proc/self/statm` RSS enforcement.
## 4. Verification commands
```sh
dev cpp-gcc -p libarchive -c bash -lc 'cmake -S . -B /tmp/void-w6b-archive -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Archive;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-archive && /tmp/void-w6b-archive/tests/VoidTests --filter "Archive*|archive_*" && ctest --test-dir /tmp/void-w6b-archive --output-on-failure --timeout 120'
```
@@ -0,0 +1,26 @@
# Crypto Hardening, Signing, MAC/KDF & Optional Async Hash Adapter
Task ID: M-CRYPTO-01..05
Phase: P2 (Wave 6B)
Status: APPROVED
Contracts: C-02, C-03, C-07, C-13
## 1. Context and baseline
`Void::Crypto` preserves all 1.x APIs (`Hasher`, `Digest`, `HashAlgorithm`, `hash`, `hashFile`, `sha1`/`sha256`/`sha512`, `sha*File`, `verifyEd25519` exact-byte false-vs-error semantics) while hardening `Hasher` state poisoning (`Ready -> Updating -> Finalized | Failed`), adding per-context OpenSSL 3 `ProviderOptions` (no process-wide provider mutation), typed Ed25519 wrappers (`Ed25519PublicKey`, `Ed25519Signature`, `Ed25519Seed`, move-only `Ed25519PrivateKey`), `sign_ed25519`, `hmac_sha256`/`hmac_sha256_into`, `hkdf_sha256`, `constant_time_equal`, backend fault injection, and a separate optional `CryptoAsync` module (`hash_stream`, `AsyncFileHasher`) so `Crypto` remains runtime-free.
## 2. Deliverables
- `src/Crypto/module.cmake` (`INTERNAL_DEPS Functional`, `EXTERNAL_DEPS OpenSSL::Crypto`, `EXCLUDE_HEADERS Void/Crypto/AsyncHash.hpp`) & `src/CryptoAsync/module.cmake` (`INTERNAL_DEPS Crypto IO Async Time Functional`, `EXTRA_HEADERS Void/Crypto/AsyncHash.hpp`).
- `include/Void/Crypto/Types.hpp`: `kCryptoErrorDomain = 18`, `CryptoErrorCode`, `make_crypto_error`, `HasherState`, `ProviderOptions`, `CryptoLimits` (`kMaxOneShotMessageBytes = 16 MiB`, `kMaxHkdfOutputBytes = 4 KiB`, `kStreamChunkBytes = 64 KiB`, `kDefaultMaxConcurrentFileHashes = 8`, `kDefaultMaxWaitingFileHashes = 32`, `kDefaultAsyncBufferBudgetBytes = 8 MiB`), `Ed25519PublicKey`, `Ed25519Signature`, `Ed25519Seed` (with explicit wipe).
- `include/Void/Crypto/Crypto.hpp` & `src/Crypto/Crypto.cpp`: OpenSSL 3 non-deprecated EVP APIs (`EVP_MD_fetch`, `EVP_MAC_fetch`, `EVP_KDF_fetch`, `EVP_PKEY_new_raw_*_ex`, `EVP_DigestSignInit_ex`, `EVP_DigestVerifyInit_ex`, `CRYPTO_memcmp`, `OPENSSL_cleanse`), poisoned `Hasher` + `state()`, `Ed25519PrivateKey` (`generate`, `from_raw_seed`, `public_key`, `export_raw_seed`), `sign_ed25519`, typed `verify_ed25519`, `hmac_sha256`, `hmac_sha256_into`, `hkdf_sha256` (4 KiB cap, overlap rejection, wipe-on-error), `constant_time_equal`, and thread-local/scoped backend fault hook.
- `include/Void/Crypto/AsyncHash.hpp` & `src/CryptoAsync/AsyncHash.cpp`: `hash_stream` (64 KiB `BufferLease` chunks, stop/deadline checks between chunks, clean-EOF-only finalize) and `AsyncFileHasher` (8 concurrent / 32 waiters / 8 MiB buffer budget, `close_and_join`).
- `tests/standalone/Crypto/CryptoHardening.cpp`, `tests/standalone/CryptoAsync/CryptoAsync.cpp`, `tests/package/{CryptoOnly,CryptoAsyncOnly}/*`, registered in `tests/package/InstalledComponents.cmake`.
## 3. Edge cases
- Invalid key/signature sizes return `invalid_argument` before touching OpenSSL; well-formed invalid Ed25519 signatures return `true`/`false` (not error).
- One-shot `sign_ed25519`/`verify_ed25519` enforce `16 MiB` limit; `hkdf_sha256` rejects zero/oversized (`> 4 KiB`) output and overlapping input/salt/context/output spans, wiping output on failure.
- Backend error during `Hasher::update`/`finalize` transitions state to `Failed`, rejecting further `update`/`finalize` calls.
- `hash_stream` never returns a digest on partial read + error or stop/EOF cancellation race; `AsyncFileHasher::close_and_join` stops admission and drains in-flight work before returning.
## 4. Verification commands
```sh
dev cpp-gcc -p openssl -c bash -lc 'cmake -S . -B /tmp/void-w6b-crypto -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Crypto;CryptoAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-crypto && /tmp/void-w6b-crypto/tests/VoidTests --filter "Crypto*|crypto_*" && ctest --test-dir /tmp/void-w6b-crypto --output-on-failure --timeout 120'
```
@@ -0,0 +1,29 @@
# Security Hardening, SecureBuffer, Versioned Envelopes, Authorization & Authenticator
Task ID: M-SECURITY-01..04
Phase: P2 (Wave 6B)
Status: APPROVED
Contracts: C-02, C-03, C-04, C-05, C-07, C-09, C-13
## 1. Context and baseline
`Void::Security` preserves all 1.x APIs (`generateToken`, `hashToken`, `verifyToken`, `hashPassword`, `verifyPassword`, `generateSecretKey`, `sealSecret`, `openSecret`) and the exact legacy secret envelope format (`24B nonce || secretbox_easy(16B MAC + ciphertext)`), while adding `SecureBuffer`, input/cost validation (`parse_argon2id_cost`, `verify_password_budgeted`), versioned `VSEC` v1 AEAD envelopes + `SecretKeyRing` rotation, typed default-deny `Authorization`, and a separate `SecurityAsync` module (`Authenticator`, `AccountSessionPort`, `InMemoryAccountSessionStore`, `PasswordJobBudget`, `AuditSink`) so primitive `Security` remains free of Async/Resilience/Storage dependencies.
## 2. Deliverables
- `src/Security/module.cmake` (`INTERNAL_DEPS Functional Time`, `EXTERNAL_DEPS Sodium::Sodium`, `EXCLUDE_HEADERS Void/Security/Authenticator.hpp`) & `src/SecurityAsync/module.cmake` (`INTERNAL_DEPS Security Async Time Resilience Functional`, `EXTRA_HEADERS Void/Security/Authenticator.hpp`).
- `include/Void/Security/Types.hpp`: `kSecurityErrorDomain = 19`, `SecurityErrorCode`, `make_security_error`, `SecurityLimits` (1 KiB password/hash, 512 B token, 16 MiB plaintext, 64 roles, 4096 rules, 16 predicate depth), `PasswordVerifyBudget`, `Argon2idCost`.
- `include/Void/Security/SecureBuffer.hpp` & `src/Security/SecureBuffer.cpp`: move-only `SecureBuffer` with `LockPolicy::{StandardWiped, LockedOptional, LockedRequired}` (fail-closed if locked allocation fails), `sodium_memzero` wipe on release/move, optional fault hook.
- `include/Void/Security/Security.hpp` & `src/Security/Security.cpp`: preserve 1.x surface + enforce input caps, `parse_argon2id_cost`, `verify_password_budgeted` rejecting excessive `m`/`t` before Argon2id allocation, backend init/randomness fault seam.
- `include/Void/Security/Envelope.hpp` & `src/Security/Envelope.cpp`: versioned `VSEC` v1 `crypto_aead_xchacha20poly1305_ietf` envelope authenticating header + `key_id` + `aad`, `SecretKeyRing` (active-key writes, multi-key reads, checked retirement), zero silent legacy fallback.
- `include/Void/Security/Authorization.hpp` & `src/Security/Authorization.cpp`: `Principal` (<=64 roles), typed `Predicate` (depth <=16), `PolicySnapshot` (<=4096 rules, default-deny, deny-overrides-allow, `authorize`).
- `include/Void/Security/Authenticator.hpp` & `src/SecurityAsync/Authenticator.cpp`: `AccountSessionPort`, `InMemoryAccountSessionStore`, `PasswordJobBudget` (512 MiB / 2 active / 32 waiters), `SessionPolicy` (10,000 total / 16 per subject / 1h TTL / 60s civil-clock rollback check / 256 cleanup batch), mandatory `AuditSink`, `Authenticator` (dummy-hash timing-work parity, credential-version CAS, non-interruptible drain-on-stop, zero positive session cache, `close_and_join`).
- `tests/standalone/Security/SecurityHardening.cpp`, `tests/standalone/SecurityAsync/SecurityAsync.cpp`, `tests/package/{SecurityOnly,SecurityAsyncOnly}/*`, registered in `tests/package/InstalledComponents.cmake`.
## 3. Edge cases
- Legacy `sealSecret`/`openSecret` bytes remain bit-for-bit compatible; `Envelope` never guesses legacy decoding after AEAD failure.
- Unknown account and wrong password execute comparable Argon2id work via a precomputed dummy hash and return identical public denial while recording distinct internal audit reasons.
- Cancelling during password verification returns cancelled, retains budget/buffers until the Argon2id job completes, discards output, and never writes a session.
- Civil-clock rollback exceeding configured tolerance (default 60s) fails session admission until reconciled.
## 4. Verification commands
```sh
dev cpp-gcc -p libsodium -c bash -lc 'cmake -S . -B /tmp/void-w6b-security -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Security;SecurityAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-security && /tmp/void-w6b-security/tests/VoidTests --filter "Security*|security_*" && ctest --test-dir /tmp/void-w6b-security --output-on-failure --timeout 120'
```
@@ -0,0 +1,26 @@
# M-SQLITE-01..05 — Hardened Sqlite C API Integration & Optional SqliteAsync Pool
- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`)
- **Roadmap reference**: `docs/roadmap/modules/Sqlite.md`, `docs/roadmap/DEPENDENCIES.md`
- **Supported runtime observed**: SQLite 3.54.0 via Nix `sqlite` package
## Scope & Ownership
- `src/Sqlite/module.cmake`: `INTERNAL_DEPS Functional Time`, `EXTERNAL_DEPS SQLite3::SQLite3`, `EXCLUDE_HEADERS Void/Sqlite/AsyncPool.hpp`.
- `include/Void/Sqlite/Types.hpp`: `kSqliteErrorDomain = 21`, `SqliteErrorCode`, `JournalMode`, `SyncMode`, `BeginMode`, `CheckpointMode`, `TransactionState`, `SqliteLimits`, `OpenOptions`, `EffectiveCapabilities`, `ColumnType`, `ValueView`, `OwnedValue`, `OwnedRow`, `CheckpointReport`, `BackupOptions`, `BackupReport`, `CheckedMigration`, `ConnectionHealth`, `ScopedFaultGuard`.
- `include/Void/Sqlite/Sqlite.hpp` + `src/Sqlite/Sqlite.cpp`:
- Shared `ConnectionState` held by `Database`, `Statement`, `Transaction`, and `Savepoint` so moving/destroying `Database` never leaves dangling pointers.
- Preserve 1.x APIs (`Database::open`, `exec`, `prepare`, `begin`, `last_insert_rowid`, `changes`, `user_version`, `migrate`, `Statement::bind`/`step`/`reset`/`clear_bindings`/column getters, `Transaction::commit`/`rollback`, `Migration`, `OpenMode`).
- Add `open_database(path, OpenOptions)` validating limits/pragmas (`WAL`, `FULL`, `foreign_keys`, disabling extension loading by default, querying effective pragma results).
- Add checked `bind_checked` (positional & named, `ValueView`, `max_value_bytes` cap), borrowed lifetime-owned bindings, `reset_checked`, `clear_bindings_checked`, `finalize_checked`, strict single-statement `prepare` (rejecting non-whitespace trailing SQL), `RowView` with expiration generation, strict typed column reads rejecting coercion, `query_all` with row/byte caps.
- Transaction state machine (`Active`, `Committed`, `RolledBack`, `RecoveryRequired`): never mark `Committed` before `COMMIT` succeeds; inspect `sqlite3_get_autocommit` on error; reject nested `begin`; add RAII `Savepoint`.
- Checked `Database::close()` rejecting with `busy` while statements/transactions/savepoints remain open; deferred close in destructor reports errors to optional diagnostic hook.
- Validate migration lists before any SQL; add `migrate_checked` recording `id`+`checksum` in `_void_schema_migrations` in the same transaction as `PRAGMA user_version` and rejecting newer schemas and checksum drift.
- Operational methods: `checkpoint()`, `backup_to()`, `restore_from()`, `health()`, WAL write-admission threshold gating, and exception-safe `create_scalar_function` / `set_authorizer` adapters.
- `src/SqliteAsync/module.cmake` + `include/Void/Sqlite/AsyncPool.hpp` + `src/SqliteAsync/AsyncPool.cpp`:
- Optional async leased connection pool (default 4 readers + 1 writer, bounded blocking workers, `max_queued_jobs = 1024`, `max_pending_input_bytes = 64 MiB`).
- Leases one connection for the complete read/write/transaction with serialized progress/interrupt cleanup so cancellation never leaks to the next borrower.
- Tests & consumers: `tests/standalone/Sqlite/SqliteHardening.cpp`, `tests/standalone/SqliteAsync/SqliteAsync.cpp`, `tests/package/SqliteOnly/*`, `tests/package/SqliteAsyncOnly/*`, updated `tests/package/InstalledComponents.cmake`.
## Verification Criteria
- Standalone `Sqlite;SqliteAsync;Testing` RelWithDebInfo `-Werror` (`-p sqlite`): all `Sqlite*` tests + `ctest` 2/2 (`SqliteOnly`, `SqliteAsyncOnly`).
- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset.
@@ -0,0 +1,27 @@
# System Process, Shared Watcher, Durable Filesystem & Temp Factories
Task ID: M-SYSTEM-01..05
Phase: P2 (Wave 6A)
Status: APPROVED
Contracts: C-01, C-02, C-03, C-04, C-05
## 1. Context and baseline
`Void::System` preserves 1.x APIs (`Void::Process::{run,run_streaming,shell,reexec}`, `Void::FileSystem::{FileWatcher,Path,Query,TempFile,TempDir}`, `Void::SystemInfo::CpuSampler`) while fixing legacy bugs (zero-timeout 30s cutoff, full-duplex pipe deadlock, unescalated `SIGTERM` wait hangs, `SIGPIPE` on pipes, TOCTOU temp creation, unsafe `atomic_write`) and adding `System` (`Types`, `OwnedFd`, `Child`, `spawn`, `communicate_blocking`, `replace_file`, bounded `read_file`/`list_directory`, valid `CpuSampler::sample`) plus `Void::SystemAsync` (`ProcessManager`, async `communicate`/`wait`, shared `WatcherService`, `WatchSubscription`).
## 2. Deliverables
- `src/System/module.cmake` (`INTERNAL_DEPS Functional Time LogState`, `EXCLUDE_HEADERS Void/System/AsyncProcess.hpp Void/System/AsyncWatcher.hpp`) & `src/SystemAsync/module.cmake` (`INTERNAL_DEPS System Async IO Time Functional LogState`).
- `include/Void/System/Types.hpp`: `kSystemErrorDomain = 10`, `SystemErrorCode`, `make_system_error`, move-only `OwnedFd`.
- `include/Void/System/Process.hpp` & `src/System/Process.cpp`: legacy compatibility fixes + `SpawnOptions`, `EnvironmentPolicy`, `CaptureLimits`, `OverflowPolicy`, `kMaxSpawnInputBytes = 256 KiB`, move-only `Child`, `spawn`, `communicate_blocking`, `reexec(..., close_extra_fds)`.
- `include/Void/System/{Path,Query,TempFile,TempDir,Metrics}.hpp`: `read_file_bounded`, `list_directory_bounded`, `replace_file` with `ReplaceDurability`/`ReplacePhase`/`ReplaceFaultHook`, atomic `0600`/`0700` `TempFile`/`TempDir` verified by `(dev, ino)` before removal, `CpuSample`.
- `include/Void/System/{AsyncProcess,AsyncWatcher}.hpp` & `src/SystemAsync/{AsyncProcess,AsyncWatcher}.cpp`: `ProcessManager`, async `communicate`/`wait`/`close_and_join`, shared `WatcherService`, `WatchSubscription`.
- `tests/helpers/ProcessHelper.cpp`, `tests/standalone/System/{ProcessStream,SystemHardening}.cpp`, `tests/standalone/SystemAsync/SystemAsync.cpp`, `tests/package/{SystemOnly,SystemAsyncOnly}/*`.
## 3. Edge cases
- Between `fork()` and `exec*()`, strictly async-signal-safe operations only; `exec_failed` preserves `errno` via `CLOEXEC` error pipe and never collides with child exit `127`.
- `replace_file` cleans only owned temp files before rename and reports `visible_on_disk = true, durability_unknown = true` if post-rename directory `fsync` fails.
- `WatcherService::close_and_join()` drains admitted callbacks and rejects self-join.
## 4. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-system -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-system && /tmp/void-w6a-system/tests/VoidTests --filter "Process*|SystemHardening*|Path*|Query*|TempDir*|TempFile*|Metrics*|FileWatcher*|SignalWatcher*" && ctest --test-dir /tmp/void-w6a-system --output-on-failure --timeout 120'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-sysasync -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="SystemAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-sysasync && /tmp/void-w6a-sysasync/tests/VoidTests --filter "SystemAsync*" && ctest --test-dir /tmp/void-w6a-sysasync --output-on-failure --timeout 120'
```
@@ -0,0 +1,28 @@
# Update Verify-Before-Parse, Replay Floor, Trust Store, Pinned Pruning & Recoverable Install Coordinator
Task ID: M-UPDATE-01..06
Phase: P2 (Wave 6B)
Status: APPROVED
Contracts: C-02, C-03, C-04, C-05, C-06, C-07, C-09, C-10
## 1. Context and baseline
`Void::Update` preserves existing feed/component verification, readable envelopes, greatest-compatible-version selection, and `VersionStore` durable activation/commit/rollback/reconcile/external-health semantics while fixing the schema-3 verify-before-payload-parse bug in `src/Update/Feed.cpp`, introducing explicit `SchemaParsePolicy` (`LegacyGeneralJson` vs `StrictJsonProfile`), non-forgeable `VerifiedSelection`, durable monotonic `ReplayFloorStore`, explicit `TrustStore` rotation/revocation, pin-aware bounded `VersionStore::pruneWithPins`, checksummed `OperationJournal`, and `InstallCoordinator` integrating `Archive`'s staged atomic publication and `VersionStore`'s single commit boundary.
## 2. Deliverables
- `src/Update/module.cmake` (`INTERNAL_DEPS Archive Crypto Data Functional System Text Time`).
- `include/Void/Update/Types.hpp`: `kUpdateErrorDomain = 20`, `UpdateErrorCode`, `make_update_error`, `SchemaParsePolicy`, `InstallState`, `ActivationMode`, `ReleaseIdentity`, `InstallReceipt`, `InstallOptions` (1 active, 8 queued, 2 concurrent downloads, 512 MiB artifact, 2 GiB staging quota, 32 components, 256 edges, 10m deadline, 30s readiness, 1s probe interval, 3 consecutive healthy, 2 retained previous, 16 prune batch).
- `include/Void/Update/Feed.hpp` & `src/Update/Feed.cpp`: move `Crypto::verifyEd25519` strictly BEFORE payload JSON parsing/comparison in schema-3 `verifyEnvelope`, support `SchemaParsePolicy::StrictJsonProfile` (integer-only strict JSON via `Void::Json::Strict::ParseOptions{.allowDecimals = false}`), add non-forgeable `VerifiedSelection` + `verify_and_select_release` / `verify_and_select_component_set`.
- `include/Void/Update/VersionStore.hpp` & `src/Update/VersionStore.cpp`: add `PruneReport` and `pruneWithPins(retainedPreviousVersions, pinnedVersions, batchLimit = 16)`.
- `include/Void/Update/Install.hpp` & `src/Update/Install.cpp` (included from `Update.hpp`): `ReplayFloorStore` (atomic via `Void::FileSystem::replace_file`, monotonic across restarts/key rotations/clock rollback), `TrustStore` (bootstrap, authenticated rotation, revocation), `ArtifactTransport` + `LocalFileArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` (`RecoveryRequired` on unknown/corrupt), and `InstallCoordinator` (`install`, idempotent `reconcile`, `retry_cleanup`, `shutdown`).
- `tests/standalone/Update/UpdateHardening.cpp`, `tests/package/UpdateOnly/*`, registered in `tests/package/InstalledComponents.cmake`.
## 3. Edge cases
- Invalid signature over malformed JSON payload in schema-3 envelopes fails at signature verification without ever invoking payload JSON parsing.
- Replay floor never decreases on restart, key rotation, or civil-clock rollback.
- Post-commit cleanup/prune failures transition receipt to `CleanupPending` with retryable diagnostics and NEVER trigger rollback; calling `rollback` after durable healthy marker preserves the committed candidate.
- Unknown/corrupt operation journal entries halt automation with `RecoveryRequired` without discarding evidence.
- Pinned versions cannot be pruned; prune reports skipped-pin pressure rather than breaking live pins.
## 4. Verification commands
```sh
dev cpp-gcc -p libarchive -p openssl -c bash -lc 'cmake -S . -B /tmp/void-w6b-update -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Update;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-update && /tmp/void-w6b-update/tests/VoidTests --filter "Update*|update_*|component_feed_*|readable_component_*|version_store_*" && ctest --test-dir /tmp/void-w6b-update --output-on-failure --timeout 120'
```
+27
View File
@@ -0,0 +1,27 @@
# IPC Wire Codec, Quota Reservations, Local UDS/Pipe Transport, and Session
Task ID: S-IPC-01..03
Phase: P2 (Wave 6A)
Status: APPROVED
Contracts: C-01, C-02, C-03, C-04, C-05
## 1. Context and baseline
New subsystem `Void::IPC` (`src/IPC/module.cmake`, `INTERNAL_DEPS Core Functional Memory Time Binary Async IO Resilience`) providing V1 `VDIP` 24-byte big-endian framed RPC/messaging over pathname `AF_UNIX` `SOCK_STREAM` and supervised child pipe pairs (`adopt_pipe_pair`).
## 2. Deliverables
- `include/Void/Functional/Error.hpp`: reserve `kIpcErrorDomain = 16` (plus remaining P2 domains `17..21`).
- `include/Void/IPC/{Types,Codec,Transport,Session,IPC}.hpp` & `src/IPC/{Codec,Transport,Session}.cpp`:
- `IpcErrorCode`, `IpcLimits`, `EffectStatus`, `CallFailure`, `PeerCredentials`, `PeerPolicy`, `HelloInfo`.
- V1 24B `VDIP` codec + `BufferQuota`/`QuotaPermit` + incremental `FrameDecoder` validating magic/version/flags/stream/request ID/limits and reserving global (`64 MiB`) + per-session quotas before payload allocation.
- `LocalListener` (0700 owned parent dir, `sun_path < 108`, startup `flock` + failed `connect` stale cleanup, `SOCK_NONBLOCK|SOCK_CLOEXEC`, `fchmod(0600)` before `bind()`, `SO_PEERCRED`), `connect_local`, `adopt_pipe_pair` (`PeerCredentials::available == false`).
- Full-duplex `Session` (`handshake`, `start`, `request`, `send_one_way`, `send_goaway`, `close_and_join` rejecting `self_join`), monotonic request IDs, `TokenBucket` per-peer rate limit, reserved control lane (`8 KiB`/`16` frames), `256` late-response tombstones, advisory `cancel`, single terminal completion, zero auto-replay.
- `tests/standalone/IPC/Ipc.cpp` & `tests/package/IPCOnly/*`.
## 3. Edge cases
- Oversize/corrupt headers fail before any payload allocation or quota charge.
- Saturated data lane still delivers reserved control-lane `cancel`/`overloaded`/`rate_limited` replies without deadlock.
- Peer disconnect faults active requests once with `transport_lost` and `EffectStatus::unknown`.
## 4. Verification commands
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w6a-ipc -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="IPC;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6a-ipc && /tmp/void-w6a-ipc/tests/VoidTests --filter "Ipc*" && ctest --test-dir /tmp/void-w6a-ipc --output-on-failure --timeout 120'
```
@@ -0,0 +1,27 @@
# S-STORAGE-01..06 — Original Durable Key-Value Storage Engine (`G-STORE`)
- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`)
- **Roadmap reference**: `docs/roadmap/subsystems/Storage.md`, `docs/roadmap/DEPENDENCIES.md`
## Scope & Ownership
- Zero SQLite dependency (`src/Storage/module.cmake`: `INTERNAL_DEPS Core Functional Time Memory Binary IO Async`, zero external deps).
- `include/Void/Storage/Crc32c.hpp`: native Castagnoli CRC32C (`0x1EDC6F41` / reflected `0x82F63B78`, golden `"123456789"` == `0xE3069283`).
- `include/Void/Storage/Types.hpp`: `kStorageErrorDomain = 9`, `StorageErrorCode`, `Sequence`, `ByteView`, `OwnedBytes`, `OwnedValue`, `Durability::{Sync,Buffered}`, `Outcome::{NotCommitted,Committed,Unknown}`, `Limits` (all roadmap defaults + non-zero validation), `CommitReceipt`, `WriteFailure`, `ScanBounds` (with `prefix`), `ScanEntry`, `ScanPage`, `EngineState`, `EngineStats`, unsigned-byte lexicographic comparator.
- `include/Void/Storage/FilePort.hpp` + `src/Storage/FilePort.cpp`: `FilePort`, `FileHandle`, `PosixFilePort` (exclusive `flock`, `EINTR`/short-write loops, file & dir `fsync`, atomic same-dir rename capability check), and `FaultInjectingFilePort` for deterministic power-loss / short-write / sync-failure / rename-failure / unsynced-discard simulation.
- `include/Void/Storage/Format.hpp` + `src/Storage/Format.cpp`:
- V1 WAL (`VOIDWAL1` 64B segment header with CRC32C, 36B `VWR1` record header with header CRC32C checked before allocating payload, 8B trailer with record CRC32C + repeated length, `BEGIN`/`PUT`/`ERASE`/`COMMIT` payloads with aggregate CRC32C).
- V1 Immutable Sorted Table (`VOIDTBL1` header, 32 KiB target sorted blocks with per-block CRC32C, sparse block index, checksummed `VOIDTBF1` footer).
- V1 Immutable Manifest (`VOIDMNF1`) and atomic `CURRENT` (`VOIDCUR1`).
- `include/Void/Storage/Batch.hpp`, `include/Void/Storage/Engine.hpp`, `src/Storage/Engine.cpp`:
- Conditional atomic `Batch` (`put`, `erase`, `require_absent`, `require_version`, `require_value`; rejects duplicate keys/conditions; sequence-based versioning prevents ABA).
- Exclusive directory lock, minimal `CURRENT`/manifest bootstrap & WAL segment rotation publication before write admission, deterministic recovery with tail-only truncation of final active segment and fail-closed `corrupt` on damaged complete records or earlier closed segments.
- Single serialized writer, pre-append reservation/encoding, infallible visibility publication, `RecoveryRequired` + `Outcome::Unknown` on post-append failure, pinned `Snapshot`/`Cursor` with continuation scans and `page_too_small` enforcement.
- `checkpoint()` freezing memtable -> immutable table -> manifest -> `CURRENT` -> deferred retirement after snapshot pins release; bounded incremental `compact()` merging <= 4 overlapping runs while preserving versions needed by live snapshots.
- `include/Void/Storage/Tools.hpp` + `src/Storage/Tools.cpp`: `verify_directory` (full block-level read-only verification), pinned `export_backup` / `restore_backup`, offline `salvage_directory` into a separate destination.
- `include/Void/Storage/AsyncAdapter.hpp` + `src/Storage/AsyncAdapter.cpp`: bounded blocking async adapter following C-03 domain-result classification (`stop before append -> NotCommitted`, `stop during sync -> retain until settled`, `sync succeeds after stop -> CommitReceipt`, `sync fails after append -> Unknown + RecoveryRequired`, single delivery).
- `include/Void/Storage/Storage.hpp`: umbrella header.
- Tests & consumer: `tests/standalone/Storage/Storage.cpp` (CRC32C golden, format/overflow, model checker vs reference map, byte-offset truncation, corruption, fault-injected creation/rotation/sync/checkpoint/compaction crashes, retention under slow snapshots, async stop-race conformance, verify/backup/salvage), `tests/package/StorageOnly/*`, updated `tests/package/InstalledComponents.cmake`.
## Verification Criteria
- Standalone `Storage;Testing` RelWithDebInfo `-Werror` (zero external deps!): `storage_*` tests + `ctest` 2/2 (`StorageOnly`).
- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset.
+176 -4
View File
@@ -1,11 +1,19 @@
#pragma once
#include <Void/Archive/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string_view>
#include <vector>
namespace Void::Archive
{
@@ -21,12 +29,176 @@ namespace Void::Archive
std::uint64_t bytes{0};
};
/// Extract a tar/tar.zst archive without invoking an external process.
/// Only regular files and directories are accepted. Absolute/traversal
/// paths, links, special files, duplicates and configured size/count
/// overages fail the whole operation.
/// Extract a tar/tar.zst archive incrementally into `destination` without
/// invoking an external process. Preserved 1.x incremental API; callers
/// requiring all-or-nothing directory visibility should use
/// `extract_staged` + `StagedTree::publish`.
[[nodiscard]] Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path& archivePath,
const std::filesystem::path& destination,
const ExtractionOptions& options = {});
/// Caller-driven bounded tar/tar.zst reader. Maintains one active entry at
/// a time; callers must drain (`read_chunk` returning 0) or call
/// `skip_entry()` before advancing with `next_entry()`.
class Reader
{
public:
~Reader();
Reader(Reader&&) noexcept;
Reader& operator=(Reader&&) noexcept;
Reader(const Reader&) = delete;
Reader& operator=(const Reader&) = delete;
[[nodiscard]] static Void::Result::Result<Reader> open(
ByteSource& source, ReadLimits limits = {},
std::stop_token stop = {},
std::optional<Void::Time::MonotonicClock::time_point> deadline =
std::nullopt,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
[[nodiscard]] static Void::Result::Result<Reader> open_file(
const std::filesystem::path& archive_path,
ReadLimits limits = {}, std::stop_token stop = {},
std::optional<Void::Time::MonotonicClock::time_point> deadline =
std::nullopt,
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
/// Advance to the next archive entry. Returns std::nullopt on clean
/// EOF.
[[nodiscard]] Void::Result::Result<std::optional<EntryInfo>>
next_entry();
/// Read up to dst.size() decompressed bytes of the active regular
/// file entry. Returns 0 on entry EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read_chunk(std::span<std::byte> dst);
/// Drain and discard remaining bytes of the active entry while
/// still accounting decompressed bytes against policy limits.
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry();
[[nodiscard]] std::size_t entries_seen() const noexcept;
[[nodiscard]] std::uint64_t total_decompressed_bytes() const noexcept;
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit Reader(std::unique_ptr<Impl> impl) noexcept;
};
/// Bounded metadata listing of archive entries. Normal mode (`forensic =
/// false`) rejects unsafe/duplicate/conflicting entries. Opt-in forensic
/// mode reports rejected entries without writing to disk.
[[nodiscard]] Void::Result::Result<std::vector<EntryInfo>>
list_entries(ByteSource& source, ReadLimits limits = {},
bool forensic = false);
[[nodiscard]] Void::Result::Result<std::vector<EntryInfo>>
list_entries(const std::filesystem::path& archive_path,
ReadLimits limits = {}, bool forensic = false);
/// Move-only handle owning an unpublished private staging directory beneath
/// a pinned parent directory. Unlinks only names under its staging
/// descriptor without following links if destroyed before publication.
class StagedTree
{
public:
StagedTree() noexcept = default;
~StagedTree() noexcept;
StagedTree(StagedTree&&) noexcept;
StagedTree& operator=(StagedTree&&) noexcept;
StagedTree(const StagedTree&) = delete;
StagedTree& operator=(const StagedTree&) = delete;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool published() const noexcept;
[[nodiscard]] std::string_view staging_id() const noexcept;
[[nodiscard]] const std::filesystem::path&
staging_root() const noexcept;
[[nodiscard]] const std::filesystem::path&
tree_path() const noexcept;
[[nodiscard]] std::size_t entries() const noexcept;
[[nodiscard]] std::uint64_t bytes() const noexcept;
[[nodiscard]] const std::vector<EntryInfo>&
inventory() const noexcept;
/// Publish the staged tree into a previously absent immediate child
/// of the pinned parent directory using atomic no-replace rename
/// (`renameat2(..., RENAME_NOREPLACE)`). Never overwrites existing
/// directories or falls back to a racy existence check.
[[nodiscard]] Void::Result::Result<PublicationReceipt>
publish(std::string_view new_child_name);
/// Explicitly discard an unpublished staging tree.
[[nodiscard]] Void::Result::Result<void> discard();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit StagedTree(std::unique_ptr<Impl> impl) noexcept;
friend Void::Result::Result<StagedTree>
extract_staged(ByteSource& source,
const std::filesystem::path& parent_directory,
const StagedExtractionOptions& options);
friend Void::Result::Result<StagedTree>
extract_staged_isolated(
const std::filesystem::path& archive_path,
const std::filesystem::path& parent_directory,
const IsolationOptions& options);
};
/// Extract a tar/tar.zst stream into an exclusive 0700 staging directory
/// beneath `parent_directory`, fsync files and directories bottom-up, write
/// a bounded completion inventory, and return an unpublished StagedTree.
[[nodiscard]] Void::Result::Result<StagedTree>
extract_staged(ByteSource& source,
const std::filesystem::path& parent_directory,
const StagedExtractionOptions& options = {});
[[nodiscard]] Void::Result::Result<StagedTree>
extract_staged(const std::filesystem::path& archive_path,
const std::filesystem::path& parent_directory,
const StagedExtractionOptions& options = {});
/// Remove abandoned staging directories under `parent_directory` that carry
/// a valid exclusive operation marker owned by the current user and are at
/// least `min_age` old. Never touches directories without a valid marker.
[[nodiscard]] Void::Result::Result<std::size_t>
cleanup_stale_staging(const std::filesystem::path& parent_directory,
std::chrono::seconds min_age =
std::chrono::seconds{300});
/// Create a bounded, optionally reproducible tar or tar.zst archive from
/// regular file and directory entries. Sorts normalized paths, rejects
/// duplicates/conflicts, and opens source files with O_NOFOLLOW.
[[nodiscard]] Void::Result::Result<void>
create_archive(ByteSink& sink, std::span<const CreateEntry> entries,
const CreationOptions& options = {});
[[nodiscard]] Void::Result::Result<void>
create_archive(const std::filesystem::path& output_path,
std::span<const CreateEntry> entries,
const CreationOptions& options = {});
/// Hardened untrusted-input profile: extracts the archive in an isolated
/// System child process with bounded execution time and RSS checks, then
/// independently verifies the staged tree and inventory in the parent
/// before returning StagedTree.
[[nodiscard]] Void::Result::Result<StagedTree>
extract_staged_isolated(const std::filesystem::path& archive_path,
const std::filesystem::path& parent_directory,
const IsolationOptions& options);
/// Entry point invoked by the isolated archive decoder worker binary.
[[nodiscard]] int run_isolated_worker_main(int argc, char** argv);
} // namespace Void::Archive
+342
View File
@@ -0,0 +1,342 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>
namespace Void::Archive
{
enum class ArchiveErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
unsafe_entry = 2,
unsupported_format = 3,
corrupt_archive = 4,
limit_exceeded = 5,
permission_denied = 6,
no_space = 7,
io_error = 8,
cancelled = 9,
timeout = 10,
unknown_publication = 11,
unsupported_capability = 12,
already_exists = 13,
conflict = 14,
isolation_failed = 15
};
[[nodiscard]] inline Void::Result::Error
make_archive_error(ArchiveErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case ArchiveErrorCode::none:
kind = ErrorKind::internal;
break;
case ArchiveErrorCode::invalid_argument:
case ArchiveErrorCode::unsafe_entry:
kind = ErrorKind::invalid_argument;
break;
case ArchiveErrorCode::unsupported_format:
case ArchiveErrorCode::unsupported_capability:
kind = ErrorKind::unsupported;
break;
case ArchiveErrorCode::corrupt_archive:
kind = ErrorKind::corrupt;
break;
case ArchiveErrorCode::limit_exceeded:
case ArchiveErrorCode::no_space:
kind = ErrorKind::exhausted;
break;
case ArchiveErrorCode::permission_denied:
case ArchiveErrorCode::io_error:
kind = ErrorKind::io;
break;
case ArchiveErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case ArchiveErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case ArchiveErrorCode::already_exists:
case ArchiveErrorCode::conflict:
kind = ErrorKind::conflict;
break;
case ArchiveErrorCode::unknown_publication:
case ArchiveErrorCode::isolation_failed:
kind = ErrorKind::internal;
break;
}
const ErrorCode domain_code{Void::Result::kArchiveErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
/// Render an untrusted archive entry path safely for diagnostics: capped at
/// 4 KiB with control characters and newlines escaped.
[[nodiscard]] std::string
sanitize_diagnostic_path(std::string_view raw) noexcept;
struct ReadLimits {
std::size_t max_entries{10'000};
bool allow_zero_entries{false};
std::uint64_t max_file_bytes{512ULL * 1024 * 1024};
std::uint64_t max_total_bytes{2ULL * 1024 * 1024 * 1024};
std::uint64_t max_compressed_bytes{1ULL * 1024 * 1024 * 1024};
std::size_t max_metadata_bytes{8ULL * 1024 * 1024};
std::size_t transfer_buffer_bytes{64ULL * 1024};
std::size_t max_path_bytes{4096};
std::size_t max_component_bytes{255};
std::size_t max_path_components{64};
[[nodiscard]] Void::Result::Result<void> validate() const
{
if ((max_entries == 0 && !allow_zero_entries) ||
max_file_bytes == 0 || max_total_bytes == 0 ||
max_compressed_bytes == 0 || max_metadata_bytes == 0 ||
transfer_buffer_bytes == 0 || max_path_bytes == 0 ||
max_component_bytes == 0 || max_path_components == 0) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::invalid_argument,
"Archive::ReadLimits: limits must be non-zero unless "
"allow_zero_entries is explicitly enabled")};
}
return {};
}
};
enum class EntryType : std::uint8_t {
RegularFile = 0,
Directory,
Symlink,
Hardlink,
Other
};
struct EntryInfo {
std::string path{};
EntryType type{EntryType::RegularFile};
std::uint64_t declared_size{0};
std::uint32_t safe_mode{0644};
bool executable{false};
bool accepted{true};
std::string rejection_reason{};
};
struct ProgressEvent {
std::size_t entries_processed{0};
std::uint64_t bytes_extracted{0};
std::string current_path{};
};
using ProgressCallback = std::function<void(const ProgressEvent&)>;
enum class PublicationOutcome : std::uint8_t {
Published = 0,
NotPublished,
Unknown
};
struct PublicationReceipt {
PublicationOutcome outcome{PublicationOutcome::NotPublished};
std::filesystem::path destination_path{};
std::string staging_id{};
std::size_t entries{0};
std::uint64_t bytes{0};
std::string diagnostic{};
};
struct StagedExtractionOptions {
ReadLimits limits{};
bool preserve_executable_bit{true};
std::stop_token stop{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
const Void::Time::MonotonicClock* clock{nullptr};
ProgressCallback on_progress{};
};
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd };
struct CreationOptions {
ArchiveCompression compression{ArchiveCompression::Zstd};
bool reproducible{true};
ReadLimits limits{};
std::stop_token stop{};
};
struct CreateEntry {
std::string path{};
EntryType type{EntryType::RegularFile};
bool executable{false};
std::vector<std::byte> content{};
std::optional<std::filesystem::path> source_file{};
};
struct IsolationOptions {
std::filesystem::path worker_executable{};
std::uint64_t max_rss_bytes{128ULL * 1024 * 1024};
std::chrono::milliseconds timeout{std::chrono::seconds{60}};
StagedExtractionOptions extraction{};
};
/// Synchronous byte source interface borrowed through completion.
class ByteSource
{
public:
virtual ~ByteSource() = default;
/// Read up to dst.size() bytes. Returns 0 on clean EOF.
[[nodiscard]] virtual Void::Result::Result<std::size_t>
read(std::span<std::byte> dst) = 0;
};
/// Synchronous byte sink interface borrowed through completion.
class ByteSink
{
public:
virtual ~ByteSink() = default;
[[nodiscard]] virtual Void::Result::Result<void>
write(std::span<const std::byte> src) = 0;
};
class SpanByteSource final : public ByteSource
{
public:
explicit SpanByteSource(std::span<const std::byte> data) noexcept
: m_data(data)
{
}
[[nodiscard]] Void::Result::Result<std::size_t>
read(std::span<std::byte> dst) override;
private:
std::span<const std::byte> m_data{};
std::size_t m_offset{0};
};
class FileByteSource final : public ByteSource
{
public:
[[nodiscard]] static Void::Result::Result<FileByteSource>
open(const std::filesystem::path& path);
FileByteSource(FileByteSource&&) noexcept;
FileByteSource& operator=(FileByteSource&&) noexcept;
~FileByteSource() override;
FileByteSource(const FileByteSource&) = delete;
FileByteSource& operator=(const FileByteSource&) = delete;
[[nodiscard]] Void::Result::Result<std::size_t>
read(std::span<std::byte> dst) override;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit FileByteSource(std::unique_ptr<Impl> impl) noexcept;
};
class VectorByteSink final : public ByteSink
{
public:
explicit VectorByteSink(
std::size_t max_bytes = 256ULL * 1024 * 1024) noexcept
: m_max_bytes(max_bytes)
{
}
[[nodiscard]] Void::Result::Result<void>
write(std::span<const std::byte> src) override;
[[nodiscard]] const std::vector<std::byte>& bytes() const noexcept
{
return m_bytes;
}
[[nodiscard]] std::vector<std::byte> take_bytes() noexcept
{
return std::move(m_bytes);
}
private:
std::size_t m_max_bytes{256ULL * 1024 * 1024};
std::vector<std::byte> m_bytes{};
};
class FileByteSink final : public ByteSink
{
public:
[[nodiscard]] static Void::Result::Result<FileByteSink>
create(const std::filesystem::path& path);
FileByteSink(FileByteSink&&) noexcept;
FileByteSink& operator=(FileByteSink&&) noexcept;
~FileByteSink() override;
FileByteSink(const FileByteSink&) = delete;
FileByteSink& operator=(const FileByteSink&) = delete;
[[nodiscard]] Void::Result::Result<void>
write(std::span<const std::byte> src) override;
[[nodiscard]] Void::Result::Result<void> sync_and_close();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit FileByteSink(std::unique_ptr<Impl> impl) noexcept;
};
enum class FaultPoint : std::uint8_t {
none = 0,
rename_enosys,
post_rename_parent_sync,
staging_cleanup_fail
};
class ScopedFaultGuard
{
public:
explicit ScopedFaultGuard(FaultPoint point) noexcept;
~ScopedFaultGuard() noexcept;
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
private:
FaultPoint m_previous{FaultPoint::none};
};
} // namespace Void::Archive
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
namespace Void::CryptoAsync
{
struct StreamHashOptions {
std::size_t chunk_bytes{
Void::Crypto::CryptoLimits::kStreamChunkBytes};
Void::Crypto::ProviderOptions provider{};
};
/// Incrementally hash an IO::ByteStream using a Driver-owned BufferLease
/// (default 64 KiB). Checks stop/deadline between chunks and finalizes only
/// on clean EOF without cancellation.
[[nodiscard]] Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
hash_stream(Void::Crypto::HashAlgorithm algorithm,
Void::IO::Driver& driver, Void::IO::ByteStream& stream,
Void::Async::OperationOptions options = {},
StreamHashOptions hash_options = {});
struct FileHasherOptions {
std::size_t max_concurrent{
Void::Crypto::CryptoLimits::kDefaultMaxConcurrentFileHashes};
std::size_t max_waiting{
Void::Crypto::CryptoLimits::kDefaultMaxWaitingFileHashes};
std::size_t buffer_budget_bytes{
Void::Crypto::CryptoLimits::kDefaultAsyncBufferBudgetBytes};
std::size_t chunk_bytes{
Void::Crypto::CryptoLimits::kStreamChunkBytes};
Void::Crypto::ProviderOptions provider{};
};
struct FileHasherStats {
std::size_t active{0};
std::size_t waiting{0};
std::size_t reserved_buffer_bytes{0};
std::uint64_t completed{0};
std::uint64_t rejected{0};
bool closing{false};
};
/// Bounded asynchronous file-hashing service with concurrency, queue, and
/// owned buffer-budget limits plus explicit stop/join shutdown.
class AsyncFileHasher
{
public:
explicit AsyncFileHasher(
Void::Async::Executor& executor,
FileHasherOptions options = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~AsyncFileHasher();
AsyncFileHasher(const AsyncFileHasher&) = delete;
AsyncFileHasher& operator=(const AsyncFileHasher&) = delete;
AsyncFileHasher(AsyncFileHasher&&) = delete;
AsyncFileHasher& operator=(AsyncFileHasher&&) = delete;
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Crypto::Digest>>
hash_file(Void::Crypto::HashAlgorithm algorithm,
std::filesystem::path path,
Void::Async::OperationOptions options = {});
void request_stop() noexcept;
[[nodiscard]] Void::Result::Result<void> close_and_join();
[[nodiscard]] FileHasherStats stats() const noexcept;
private:
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::CryptoAsync
+92 -5
View File
@@ -1,5 +1,6 @@
#pragma once
#include <Void/Crypto/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
@@ -21,18 +22,23 @@ namespace Void::Crypto
[[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm);
[[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm,
const ProviderOptions& provider);
~Hasher();
Hasher(Hasher&&) noexcept;
Hasher& operator=(Hasher&&) noexcept;
Hasher(const Hasher&) = delete;
Hasher& operator=(const Hasher&) = delete;
[[nodiscard]] HasherState state() const noexcept;
[[nodiscard]] Void::Result::Result<void>
update(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void>
update(std::string_view data);
/// Finalize this hash. Calling finalize or update again is an
/// error.
/// error. Backend update/finalize failures poison the hasher.
[[nodiscard]] Void::Result::Result<Digest> finalize();
private:
@@ -44,10 +50,16 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest>
hash(HashAlgorithm algorithm, std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest>
hash(HashAlgorithm algorithm, std::span<const std::byte> data,
const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest> hash(HashAlgorithm algorithm,
std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest>
sha1(std::span<const std::byte> data);
@@ -65,14 +77,89 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest>
sha512File(const std::filesystem::path& path);
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
/// Move-only owning Ed25519 private key handle. Has no implicit copy,
/// string conversion, or secret formatting.
class Ed25519PrivateKey
{
public:
Ed25519PrivateKey() noexcept = default;
~Ed25519PrivateKey();
Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept;
Ed25519PrivateKey& operator=(Ed25519PrivateKey&&) noexcept;
Ed25519PrivateKey(const Ed25519PrivateKey&) = delete;
Ed25519PrivateKey& operator=(const Ed25519PrivateKey&) = delete;
[[nodiscard]] static Void::Result::Result<Ed25519PrivateKey>
generate(const ProviderOptions& provider = {});
[[nodiscard]] static Void::Result::Result<Ed25519PrivateKey>
from_raw_seed(std::span<const std::byte> seed,
const ProviderOptions& provider = {});
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] Void::Result::Result<Ed25519PublicKey>
public_key() const;
/// Explicit secret export into a move-only self-wiping seed handle.
[[nodiscard]] Void::Result::Result<Ed25519Seed>
export_raw_seed() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept;
friend Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> message,
const Ed25519PrivateKey& private_key,
const ProviderOptions& provider);
};
/// Sign exact message bytes (up to CryptoLimits::kMaxOneShotMessageBytes)
/// with an owning Ed25519 private key.
[[nodiscard]] Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> message,
const Ed25519PrivateKey& private_key,
const ProviderOptions& provider = {});
/// Verify an Ed25519 detached signature over the exact message bytes.
/// Invalid key/signature sizes are errors; a well-formed but invalid
/// signature returns false.
/// Invalid key/signature sizes or oversized messages are errors; a
/// well-formed but invalid signature returns false.
[[nodiscard]] Void::Result::Result<bool>
verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> publicKey);
[[nodiscard]] Void::Result::Result<bool>
verify_ed25519(std::span<const std::byte> message,
const Ed25519Signature& signature,
const Ed25519PublicKey& public_key,
const ProviderOptions& provider = {});
/// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer.
/// Wipes output on backend failure and rejects overlapping buffers.
[[nodiscard]] Void::Result::Result<void>
hmac_sha256_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned
/// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping
/// buffers and wipes secret_output on any failure after validation.
[[nodiscard]] Void::Result::Result<void>
hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output,
const ProviderOptions& provider = {});
} // namespace Void::Crypto
+287
View File
@@ -0,0 +1,287 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <system_error>
#include <utility>
namespace Void::Crypto
{
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
inline constexpr std::size_t Ed25519SeedSize = 32;
inline constexpr std::size_t HmacSha256Size = 32;
struct CryptoLimits {
static constexpr std::size_t kMaxOneShotMessageBytes =
16ULL * 1024ULL * 1024ULL;
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
static constexpr std::size_t kDefaultAsyncBufferBudgetBytes =
8ULL * 1024ULL * 1024ULL;
};
enum class CryptoErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
invalid_key_size = 2,
invalid_signature_size = 3,
message_too_large = 4,
output_too_large = 5,
overlapping_buffers = 6,
invalid_state = 7,
unsupported_algorithm = 8,
provider_error = 9,
backend_error = 10,
io_error = 11,
cancelled = 12,
timeout = 13,
overloaded = 14,
resource_exhausted = 15,
closed = 16
};
[[nodiscard]] inline Void::Result::Error
make_crypto_error(CryptoErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case CryptoErrorCode::none:
kind = ErrorKind::internal;
break;
case CryptoErrorCode::invalid_argument:
case CryptoErrorCode::invalid_key_size:
case CryptoErrorCode::invalid_signature_size:
case CryptoErrorCode::message_too_large:
case CryptoErrorCode::output_too_large:
case CryptoErrorCode::overlapping_buffers:
kind = ErrorKind::invalid_argument;
break;
case CryptoErrorCode::invalid_state:
kind = ErrorKind::conflict;
break;
case CryptoErrorCode::unsupported_algorithm:
kind = ErrorKind::unsupported;
break;
case CryptoErrorCode::provider_error:
case CryptoErrorCode::backend_error:
kind = ErrorKind::internal;
break;
case CryptoErrorCode::io_error:
kind = ErrorKind::io;
break;
case CryptoErrorCode::cancelled:
case CryptoErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case CryptoErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case CryptoErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case CryptoErrorCode::resource_exhausted:
kind = ErrorKind::exhausted;
break;
}
const ErrorCode domain_code{Void::Result::kCryptoErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
enum class HasherState : std::uint8_t {
Ready = 0,
Updating,
Finalized,
Failed,
MovedFrom
};
/// Per-operation OpenSSL 3 provider selection. Never mutates process-wide
/// provider state.
struct ProviderOptions {
std::string property_query{};
};
struct Ed25519PublicKey {
std::array<std::byte, Ed25519PublicKeySize> bytes{};
[[nodiscard]] std::span<const std::byte> view() const noexcept
{
return bytes;
}
[[nodiscard]] static Void::Result::Result<Ed25519PublicKey>
from_bytes(std::span<const std::byte> raw)
{
if (raw.size() != Ed25519PublicKeySize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
"Ed25519PublicKey requires exactly 32 bytes")};
}
Ed25519PublicKey key;
for (std::size_t i = 0; i < Ed25519PublicKeySize; ++i) {
key.bytes[i] = raw[i];
}
return key;
}
[[nodiscard]] constexpr bool
operator==(const Ed25519PublicKey&) const noexcept = default;
};
struct Ed25519Signature {
std::array<std::byte, Ed25519SignatureSize> bytes{};
[[nodiscard]] std::span<const std::byte> view() const noexcept
{
return bytes;
}
[[nodiscard]] static Void::Result::Result<Ed25519Signature>
from_bytes(std::span<const std::byte> raw)
{
if (raw.size() != Ed25519SignatureSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_signature_size,
"Ed25519Signature requires exactly 64 bytes")};
}
Ed25519Signature sig;
for (std::size_t i = 0; i < Ed25519SignatureSize; ++i) {
sig.bytes[i] = raw[i];
}
return sig;
}
[[nodiscard]] constexpr bool
operator==(const Ed25519Signature&) const noexcept = default;
};
/// Securely wipe a mutable byte buffer using the crypto backend's
/// non-elidable cleanse routine.
void secure_wipe(std::span<std::byte> buffer) noexcept;
/// Constant-time equality comparison for equal-length digests/MACs.
[[nodiscard]] bool
constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept;
/// Move-only 32-byte Ed25519 raw seed cleared on release.
class Ed25519Seed
{
public:
Ed25519Seed() noexcept = default;
~Ed25519Seed() noexcept { clear(); }
Ed25519Seed(Ed25519Seed&& other) noexcept
: m_bytes(other.m_bytes), m_valid(other.m_valid)
{
other.clear();
}
Ed25519Seed& operator=(Ed25519Seed&& other) noexcept
{
if (this != &other) {
clear();
m_bytes = other.m_bytes;
m_valid = other.m_valid;
other.clear();
}
return *this;
}
Ed25519Seed(const Ed25519Seed&) = delete;
Ed25519Seed& operator=(const Ed25519Seed&) = delete;
[[nodiscard]] static Void::Result::Result<Ed25519Seed>
from_bytes(std::span<const std::byte> raw)
{
if (raw.size() != Ed25519SeedSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
"Ed25519Seed requires exactly 32 bytes")};
}
Ed25519Seed seed;
for (std::size_t i = 0; i < Ed25519SeedSize; ++i) {
seed.m_bytes[i] = raw[i];
}
seed.m_valid = true;
return seed;
}
[[nodiscard]] bool valid() const noexcept { return m_valid; }
[[nodiscard]] std::span<const std::byte> view() const noexcept
{
return m_valid ? std::span<const std::byte>{m_bytes}
: std::span<const std::byte>{};
}
void clear() noexcept
{
secure_wipe(m_bytes);
m_valid = false;
}
private:
std::array<std::byte, Ed25519SeedSize> m_bytes{};
bool m_valid{false};
};
enum class FaultOperation : std::uint8_t {
none = 0,
any,
hash_create,
hash_update,
hash_finalize,
ed25519_keygen,
ed25519_import,
ed25519_sign,
ed25519_verify,
hmac,
hkdf
};
struct FaultConfig {
FaultOperation op{FaultOperation::none};
CryptoErrorCode code{CryptoErrorCode::provider_error};
std::size_t fail_after{0};
};
/// RAII thread-local backend fault injection guard for deterministic
/// provider/backend failure testing.
class ScopedFaultGuard
{
public:
explicit ScopedFaultGuard(FaultConfig config) noexcept;
~ScopedFaultGuard() noexcept;
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
private:
FaultConfig m_previous{};
std::size_t m_previous_hits{0};
};
} // namespace Void::Crypto
+77 -18
View File
@@ -1,6 +1,7 @@
#pragma once
#include <charconv>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <expected>
@@ -16,6 +17,11 @@ namespace Void::Json::Strict
{
inline constexpr std::size_t default_maximum_depth{64U};
struct ParseOptions {
std::size_t maximumDepth{default_maximum_depth};
bool allowDecimals{true};
};
struct ParseError {
std::size_t offset{};
std::string message;
@@ -24,8 +30,8 @@ namespace Void::Json::Strict
struct Value {
using Array = std::vector<Value>;
using Object = std::map<std::string, Value, std::less<>>;
std::variant<std::nullptr_t, bool, std::int64_t, std::string, Array,
Object>
std::variant<std::nullptr_t, bool, std::int64_t, double,
std::string, Array, Object>
value;
};
@@ -40,8 +46,8 @@ namespace Void::Json::Strict
public:
explicit Parser(const std::string_view input,
const std::size_t maximumDepth)
: input_{input}, maximumDepth_{maximumDepth}
const ParseOptions options)
: input_{input}, options_{options}
{
}
@@ -231,6 +237,21 @@ namespace Void::Json::Strict
}
}
[[nodiscard]] static bool isDigit(const char ch) noexcept
{
return ch >= '0' && ch <= '9';
}
[[nodiscard]] std::size_t consumeDigits() noexcept
{
const std::size_t begin = position_;
while (position_ < input_.size() &&
isDigit(input_[position_])) {
++position_;
}
return position_ - begin;
}
[[nodiscard]] Value parseNumber()
{
const std::size_t start = position_;
@@ -242,21 +263,52 @@ namespace Void::Json::Strict
}
if (input_[position_] == '0') {
++position_;
if (position_ < input_.size() &&
isDigit(input_[position_])) {
fail("leading zero in number");
}
} else {
if (input_[position_] < '1' ||
input_[position_] > '9') {
fail("invalid number");
}
while (position_ < input_.size() &&
input_[position_] >= '0' &&
input_[position_] <= '9') {
++position_;
static_cast<void>(consumeDigits());
}
bool isDecimal = false;
if (position_ < input_.size() && input_[position_] == '.') {
isDecimal = true;
++position_;
if (consumeDigits() == 0U) {
fail("incomplete fractional part");
}
}
if (position_ < input_.size() &&
(input_[position_] == '.' || input_[position_] == 'e' ||
input_[position_] == 'E')) {
fail("floating-point numbers are not supported");
(input_[position_] == 'e' || input_[position_] == 'E')) {
isDecimal = true;
++position_;
if (position_ < input_.size() &&
(input_[position_] == '+' ||
input_[position_] == '-')) {
++position_;
}
if (consumeDigits() == 0U) {
fail("incomplete exponent");
}
}
if (isDecimal) {
if (!options_.allowDecimals) {
fail("floating-point numbers are not supported");
}
double value{};
const auto result = std::from_chars(
input_.data() + start, input_.data() + position_,
value, std::chars_format::general);
if (result.ec != std::errc{} ||
result.ptr != input_.data() + position_ ||
!std::isfinite(value)) {
fail("number is out of range");
}
return Value{value};
}
std::int64_t value{};
const auto result =
@@ -330,7 +382,8 @@ namespace Void::Json::Strict
[[nodiscard]] Value parseValue(const std::size_t depth)
{
if (depth > maximumDepth_ || position_ >= input_.size()) {
if (depth > options_.maximumDepth ||
position_ >= input_.size()) {
fail("nesting limit or unexpected end of input");
}
switch (input_[position_]) {
@@ -351,8 +404,7 @@ namespace Void::Json::Strict
return Value{nullptr};
default:
if (input_[position_] == '-' ||
(input_[position_] >= '0' &&
input_[position_] <= '9')) {
isDigit(input_[position_])) {
return parseNumber();
}
fail("invalid value");
@@ -360,20 +412,27 @@ namespace Void::Json::Strict
}
std::string_view input_;
std::size_t maximumDepth_;
ParseOptions options_;
std::size_t position_{};
};
} // namespace Detail
[[nodiscard]] inline std::expected<Value, ParseError>
parse(const std::string_view input,
const std::size_t maximumDepth = default_maximum_depth)
parse(const std::string_view input, const ParseOptions options)
{
try {
return Detail::Parser{input, maximumDepth}.parse();
return Detail::Parser{input, options}.parse();
} catch (const Detail::ParseFailure& failure) {
return std::unexpected{failure.error};
}
}
[[nodiscard]] inline std::expected<Value, ParseError>
parse(const std::string_view input,
const std::size_t maximumDepth = default_maximum_depth)
{
return parse(input, ParseOptions{.maximumDepth = maximumDepth,
.allowDecimals = true});
}
} // namespace Void::Json::Strict
+6
View File
@@ -65,6 +65,12 @@ namespace Void::Result
inline constexpr std::uint32_t kStacktraceErrorDomain = 13;
inline constexpr std::uint32_t kObservabilityErrorDomain = 14;
inline constexpr std::uint32_t kResilienceErrorDomain = 15;
inline constexpr std::uint32_t kIpcErrorDomain = 16;
inline constexpr std::uint32_t kArchiveErrorDomain = 17;
inline constexpr std::uint32_t kCryptoErrorDomain = 18;
inline constexpr std::uint32_t kSecurityErrorDomain = 19;
inline constexpr std::uint32_t kUpdateErrorDomain = 20;
inline constexpr std::uint32_t kSqliteErrorDomain = 21;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
+189
View File
@@ -0,0 +1,189 @@
#pragma once
#include <Void/Binary/ByteBuffer.hpp>
#include <Void/IPC/Types.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <memory_resource>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::IPC
{
struct FrameHeader {
std::uint16_t version{kWireVersion};
std::uint8_t flags{0};
FrameType type{FrameType::request};
std::uint32_t payload_len{0};
std::uint32_t stream_id{0};
std::uint64_t request_id{0};
};
class BufferQuota;
class QuotaPermit
{
public:
QuotaPermit() noexcept = default;
~QuotaPermit() noexcept;
QuotaPermit(const QuotaPermit&) = delete;
QuotaPermit& operator=(const QuotaPermit&) = delete;
QuotaPermit(QuotaPermit&& other) noexcept;
QuotaPermit& operator=(QuotaPermit&& other) noexcept;
[[nodiscard]] bool valid() const noexcept { return bytes_ > 0; }
[[nodiscard]] std::size_t bytes() const noexcept { return bytes_; }
void reset() noexcept;
private:
friend class BufferQuota;
std::weak_ptr<BufferQuota> quota_{};
std::size_t bytes_{0};
};
class BufferQuota : public std::enable_shared_from_this<BufferQuota>
{
public:
explicit BufferQuota(std::size_t capacity_bytes);
[[nodiscard]] static std::shared_ptr<BufferQuota>
create(std::size_t capacity_bytes);
[[nodiscard]] Void::Result::Result<QuotaPermit, Void::Result::Error>
reserve(std::size_t bytes);
[[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
[[nodiscard]] std::size_t used() const noexcept;
private:
friend class QuotaPermit;
void release(std::size_t bytes) noexcept;
std::size_t capacity_{0};
mutable std::mutex mu_{};
std::size_t used_{0};
};
struct DecodedFrame {
FrameHeader header{};
Void::Binary::FrozenBytes payload{};
QuotaPermit global_permit{};
QuotaPermit session_permit{};
};
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
validate_frame_header(const FrameHeader& header, const IpcLimits& limits);
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
encode_frame_header(const FrameHeader& header,
std::span<std::byte, kFrameHeaderSize> out);
[[nodiscard]] Void::Result::Result<FrameHeader, Void::Result::Error>
decode_frame_header(std::span<const std::byte, kFrameHeaderSize> in);
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_frame(
const FrameHeader& header,
std::span<const std::byte> payload = {},
const IpcLimits& limits = {},
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_hello(const HelloInfo& info,
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<HelloInfo, Void::Result::Error>
decode_hello(std::span<const std::byte> payload,
std::size_t max_bytes = 4096);
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_error_payload(
IpcErrorCode code,
std::string_view message,
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<std::pair<IpcErrorCode, std::string>,
Void::Result::Error>
decode_error_payload(std::span<const std::byte> payload);
[[nodiscard]] Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_goaway_payload(
IpcErrorCode code,
std::uint64_t last_request_id,
std::string_view reason,
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] Void::Result::Result<
std::tuple<IpcErrorCode, std::uint64_t, std::string>,
Void::Result::Error>
decode_goaway_payload(std::span<const std::byte> payload);
class FrameDecoder
{
public:
explicit FrameDecoder(
IpcLimits limits = {},
std::shared_ptr<BufferQuota> global_quota = {},
std::shared_ptr<BufferQuota> session_quota = {},
std::pmr::memory_resource* mr = std::pmr::get_default_resource());
[[nodiscard]] static constexpr std::size_t
frame_quota_cost(std::size_t payload_len) noexcept
{
return kFrameHeaderSize + payload_len;
}
[[nodiscard]] Void::Result::Result<std::vector<DecodedFrame>,
Void::Result::Error>
feed(std::span<const std::byte> chunk);
[[nodiscard]] std::size_t header_bytes_buffered() const noexcept
{
return header_len_;
}
[[nodiscard]] std::size_t payload_bytes_buffered() const noexcept
{
return has_header_ ? payload_written_ : 0;
}
[[nodiscard]] bool in_mid_frame() const noexcept
{
return header_len_ > 0 || has_header_;
}
private:
enum class State {
reading_header,
reading_payload,
failed,
};
IpcLimits limits_{};
std::shared_ptr<BufferQuota> global_quota_{};
std::shared_ptr<BufferQuota> session_quota_{};
std::pmr::memory_resource* mr_{nullptr};
State state_{State::reading_header};
std::array<std::byte, kFrameHeaderSize> header_buf_{};
std::size_t header_len_{0};
bool has_header_{false};
FrameHeader current_header_{};
QuotaPermit current_global_permit_{};
QuotaPermit current_session_permit_{};
std::optional<Void::Binary::ByteBuffer> payload_buf_{};
std::size_t payload_written_{0};
void reset_frame_state() noexcept;
};
} // namespace Void::IPC
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include <Void/IPC/Codec.hpp>
#include <Void/IPC/Session.hpp>
#include <Void/IPC/Transport.hpp>
#include <Void/IPC/Types.hpp>
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Binary/ByteBuffer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IPC/Codec.hpp>
#include <Void/IPC/Transport.hpp>
#include <Void/IPC/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <expected>
#include <functional>
#include <memory>
#include <stop_token>
namespace Void::IPC
{
using RequestHandler = std::function<Void::Coro::Task<
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>>(
Void::Binary::FrozenBytes payload, std::stop_token cancel)>;
using OneWayHandler = std::function<void(Void::Binary::FrozenBytes payload)>;
class Session
{
public:
struct State;
explicit Session(
Void::IO::Driver& driver,
Void::Async::Executor& executor,
DuplexTransport transport,
IpcLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
std::shared_ptr<BufferQuota> global_quota = {});
~Session() noexcept;
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
Session(Session&&) = delete;
Session& operator=(Session&&) = delete;
[[nodiscard]] Void::Coro::Task<Void::Result::Result<HelloInfo, Void::Result::Error>>
handshake(HelloInfo local_hello = {},
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
start(RequestHandler on_request, OneWayHandler on_one_way = {});
[[nodiscard]] Void::Coro::Task<
std::expected<Void::Binary::FrozenBytes, CallFailure>>
request(Void::Binary::FrozenBytes payload,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_one_way(Void::Binary::FrozenBytes payload);
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_goaway(IpcErrorCode code = IpcErrorCode::closed,
std::string_view reason = "closing");
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
close_and_join(Void::Async::OperationOptions options = {});
[[nodiscard]] SessionStats stats() const noexcept;
[[nodiscard]] HelloInfo negotiated_hello() const;
[[nodiscard]] const PeerCredentials& peer_credentials() const noexcept;
// Test hook to inspect/force request ID near exhaustion without 2^64 calls.
void set_next_request_id_for_test(std::uint64_t next_id) noexcept;
private:
std::shared_ptr<State> state_{};
};
} // namespace Void::IPC
+118
View File
@@ -0,0 +1,118 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IPC/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
namespace Void::IPC
{
class DuplexTransport
{
public:
DuplexTransport() noexcept = default;
DuplexTransport(Void::IO::ByteStream unified_stream,
PeerCredentials creds) noexcept;
DuplexTransport(Void::IO::ByteStream read_stream,
Void::IO::ByteStream write_stream,
PeerCredentials creds) noexcept;
DuplexTransport(const DuplexTransport&) = delete;
DuplexTransport& operator=(const DuplexTransport&) = delete;
DuplexTransport(DuplexTransport&&) noexcept = default;
DuplexTransport& operator=(DuplexTransport&&) noexcept = default;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool is_split() const noexcept { return split_; }
[[nodiscard]] const PeerCredentials& credentials() const noexcept
{
return credentials_;
}
[[nodiscard]] Void::IO::ByteStream& reader_stream() noexcept
{
return read_stream_;
}
[[nodiscard]] Void::IO::ByteStream& writer_stream() noexcept
{
return split_ ? write_stream_ : read_stream_;
}
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
close_and_join(Void::Async::OperationOptions options = {});
private:
friend class LocalListener;
bool split_{false};
Void::IO::ByteStream read_stream_{};
Void::IO::ByteStream write_stream_{};
PeerCredentials credentials_{};
std::shared_ptr<void> listener_slot_{};
};
class LocalListener
{
public:
struct SlotState;
LocalListener() noexcept = default;
~LocalListener() noexcept;
LocalListener(const LocalListener&) = delete;
LocalListener& operator=(const LocalListener&) = delete;
LocalListener(LocalListener&& other) noexcept;
LocalListener& operator=(LocalListener&& other) noexcept;
[[nodiscard]] static Void::Result::Result<LocalListener, Void::Result::Error>
listen(const std::filesystem::path& socket_path,
IpcLimits limits = {},
PeerPolicy policy = {});
[[nodiscard]] Void::Result::Result<std::optional<DuplexTransport>,
Void::Result::Error>
try_accept(Void::IO::Driver& driver);
[[nodiscard]] bool valid() const noexcept { return listen_fd_ >= 0; }
[[nodiscard]] std::size_t active_sessions() const noexcept;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return socket_path_;
}
[[nodiscard]] int fd() const noexcept { return listen_fd_; }
void close() noexcept;
private:
int listen_fd_{-1};
int dir_fd_{-1};
int lock_fd_{-1};
std::filesystem::path socket_path_{};
std::string socket_name_{};
std::uint64_t socket_dev_{0};
std::uint64_t socket_ino_{0};
IpcLimits limits_{};
PeerPolicy policy_{};
std::shared_ptr<SlotState> slot_state_{};
};
[[nodiscard]] Void::Result::Result<DuplexTransport, Void::Result::Error>
connect_local(Void::IO::Driver& driver,
const std::filesystem::path& socket_path,
PeerPolicy policy = {});
[[nodiscard]] Void::Result::Result<DuplexTransport, Void::Result::Error>
adopt_pipe_pair(Void::IO::Driver& driver, int read_fd, int write_fd);
[[nodiscard]] Void::Result::Result<std::pair<DuplexTransport, DuplexTransport>,
Void::Result::Error>
create_socket_pair_transports(Void::IO::Driver& driver);
} // namespace Void::IPC
+181
View File
@@ -0,0 +1,181 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <format>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
namespace Void::IPC
{
inline constexpr std::size_t kFrameHeaderSize = 24;
inline constexpr std::uint16_t kWireVersion = 1;
enum class IpcErrorCode : std::int32_t {
invalid_argument = 1,
corrupt_frame = 2,
unsupported_version = 3,
frame_too_large = 4,
quota_exceeded = 5,
overloaded = 6,
rate_limited = 7,
cancelled = 8,
timed_out = 9,
transport_lost = 10,
closed = 11,
permission_denied = 12,
already_exists = 13,
not_found = 14,
handshake_failed = 15,
id_exhausted = 16,
self_join = 17,
peer_error = 18,
internal = 19,
};
[[nodiscard]] constexpr Void::Result::ErrorKind
classify_ipc_error(IpcErrorCode code) noexcept
{
switch (code) {
case IpcErrorCode::invalid_argument:
return Void::Result::ErrorKind::invalid_argument;
case IpcErrorCode::corrupt_frame:
return Void::Result::ErrorKind::corrupt;
case IpcErrorCode::unsupported_version:
return Void::Result::ErrorKind::unsupported;
case IpcErrorCode::frame_too_large:
case IpcErrorCode::quota_exceeded:
case IpcErrorCode::id_exhausted:
return Void::Result::ErrorKind::exhausted;
case IpcErrorCode::overloaded:
case IpcErrorCode::rate_limited:
return Void::Result::ErrorKind::overloaded;
case IpcErrorCode::cancelled:
case IpcErrorCode::closed:
return Void::Result::ErrorKind::cancelled;
case IpcErrorCode::timed_out:
return Void::Result::ErrorKind::timeout;
case IpcErrorCode::not_found:
return Void::Result::ErrorKind::not_found;
case IpcErrorCode::already_exists:
case IpcErrorCode::self_join:
return Void::Result::ErrorKind::conflict;
case IpcErrorCode::permission_denied:
case IpcErrorCode::transport_lost:
case IpcErrorCode::handshake_failed:
case IpcErrorCode::peer_error:
return Void::Result::ErrorKind::io;
case IpcErrorCode::internal:
return Void::Result::ErrorKind::internal;
}
return Void::Result::ErrorKind::internal;
}
[[nodiscard]] inline Void::Result::Error make_ipc_error(
IpcErrorCode code, std::string_view message, int sys_errno = 0)
{
std::string detail;
std::error_code sys_ec{};
if (sys_errno != 0) {
detail = std::format(
"{} (errno={}: {})", message, sys_errno, std::strerror(sys_errno));
sys_ec = std::error_code{sys_errno, std::generic_category()};
} else {
detail.assign(message);
}
return Void::Result::Error{
classify_ipc_error(code),
std::move(detail),
Void::Result::ErrorCode{Void::Result::kIpcErrorDomain,
static_cast<std::int32_t>(code)},
sys_ec};
}
enum class FrameType : std::uint8_t {
hello = 1,
request = 2,
response = 3,
error = 4,
cancel = 5,
one_way = 6,
goaway = 7,
};
enum class EffectStatus : std::uint8_t {
not_sent = 0,
unknown = 1,
};
struct CallFailure {
Void::Result::Error error{};
EffectStatus effect{EffectStatus::not_sent};
bool may_have_executed{false};
};
struct IpcLimits {
std::size_t max_frame_payload{1024ULL * 1024ULL};
std::size_t max_hello_bytes{4096};
std::size_t max_inflight_requests{64};
std::size_t max_active_handlers{64};
std::size_t max_outbound_frames{128};
std::size_t max_outbound_bytes{4ULL * 1024ULL * 1024ULL};
std::size_t max_recv_buffer_bytes{2ULL * 1024ULL * 1024ULL};
std::size_t max_tombstones{256};
std::size_t max_sessions{128};
std::size_t global_buffer_budget_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_waiters{128};
std::size_t control_lane_max_bytes{8192};
std::size_t control_lane_max_frames{16};
double rate_limit_per_sec{1000.0};
double rate_limit_burst{128.0};
std::chrono::milliseconds handshake_timeout{std::chrono::milliseconds{5000}};
std::chrono::milliseconds progress_timeout{std::chrono::milliseconds{5000}};
std::chrono::milliseconds idle_timeout{std::chrono::milliseconds{60000}};
};
struct PeerCredentials {
bool available{false};
long long pid{-1};
unsigned long uid{0};
unsigned long gid{0};
};
struct PeerPolicy {
bool require_uid_match{true};
bool set_allowed_uid_to_current_user{true};
unsigned long allowed_uid{0};
std::optional<unsigned long> required_gid{};
};
struct HelloInfo {
std::string protocol_id{"void.ipc.v1"};
std::uint32_t protocol_version{1};
std::uint32_t capabilities{0};
std::uint32_t max_frame_payload{1024u * 1024u};
std::uint32_t max_inflight_requests{64u};
std::uint32_t max_active_handlers{64u};
};
struct SessionStats {
std::uint64_t frames_sent{0};
std::uint64_t frames_received{0};
std::uint64_t requests_sent{0};
std::uint64_t requests_received{0};
std::uint64_t late_responses_dropped{0};
std::uint64_t cancels_coalesced{0};
std::size_t active_inflight{0};
std::size_t active_handlers{0};
std::size_t outbound_queued_bytes{0};
std::size_t control_queued_frames{0};
std::uint64_t next_request_id{1};
};
} // namespace Void::IPC
+353
View File
@@ -0,0 +1,353 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Resilience/KeyedRateLimiter.hpp>
#include <Void/Security/Authorization.hpp>
#include <Void/Security/SecureBuffer.hpp>
#include <Void/Security/Security.hpp>
#include <Void/Security/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::SecurityAsync
{
struct AccountRecord {
std::string subject{};
std::string normalized_username{};
std::string password_hash{};
std::vector<std::string> roles{};
std::uint64_t credential_version{1};
std::uint64_t revocation_generation{1};
std::uint64_t policy_generation{1};
bool enabled{true};
};
struct SessionRecord {
std::string session_id{};
std::string token_digest{};
std::string subject{};
std::vector<std::string> roles{};
std::uint64_t credential_version{1};
std::uint64_t revocation_generation{1};
std::uint64_t policy_generation{1};
Void::Time::CivilClock::time_point created_at{};
Void::Time::CivilClock::time_point expires_at{};
bool revoked{false};
};
class AccountSessionPort
{
public:
virtual ~AccountSessionPort() = default;
[[nodiscard]] virtual Void::Result::Result<
std::optional<AccountRecord>>
find_account_by_username(
std::string_view normalized_username) = 0;
[[nodiscard]] virtual Void::Result::Result<
std::optional<AccountRecord>>
find_account_by_subject(std::string_view subject) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
update_password_hash_if_version(
std::string_view subject,
std::uint64_t expected_credential_version,
std::string new_password_hash) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
create_session_if_version(
const SessionRecord& session,
std::uint64_t expected_credential_version,
std::size_t max_total_sessions,
std::size_t max_per_subject,
Void::Time::CivilClock::time_point now) = 0;
[[nodiscard]] virtual Void::Result::Result<
std::optional<SessionRecord>>
find_session_by_token_digest(std::string_view token_digest) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
revoke_session(std::string_view session_id) = 0;
[[nodiscard]] virtual Void::Result::Result<std::size_t>
cleanup_expired_sessions(
Void::Time::CivilClock::time_point now,
std::size_t batch_limit) = 0;
};
class InMemoryAccountSessionStore final : public AccountSessionPort
{
public:
[[nodiscard]] Void::Result::Result<void>
upsert_account(AccountRecord account);
[[nodiscard]] Void::Result::Result<void>
bump_credential_version(std::string_view subject,
std::string new_password_hash = {});
[[nodiscard]] Void::Result::Result<void>
set_account_enabled(std::string_view subject, bool enabled);
[[nodiscard]] Void::Result::Result<void>
bump_revocation_generation(std::string_view subject);
void set_available(bool available) noexcept;
[[nodiscard]] std::size_t session_count() const;
[[nodiscard]] Void::Result::Result<std::optional<AccountRecord>>
find_account_by_username(
std::string_view normalized_username) override;
[[nodiscard]] Void::Result::Result<std::optional<AccountRecord>>
find_account_by_subject(std::string_view subject) override;
[[nodiscard]] Void::Result::Result<void>
update_password_hash_if_version(
std::string_view subject,
std::uint64_t expected_credential_version,
std::string new_password_hash) override;
[[nodiscard]] Void::Result::Result<void> create_session_if_version(
const SessionRecord& session,
std::uint64_t expected_credential_version,
std::size_t max_total_sessions, std::size_t max_per_subject,
Void::Time::CivilClock::time_point now) override;
[[nodiscard]] Void::Result::Result<std::optional<SessionRecord>>
find_session_by_token_digest(
std::string_view token_digest) override;
[[nodiscard]] Void::Result::Result<void>
revoke_session(std::string_view session_id) override;
[[nodiscard]] Void::Result::Result<std::size_t>
cleanup_expired_sessions(Void::Time::CivilClock::time_point now,
std::size_t batch_limit) override;
private:
mutable std::mutex m_mu{};
bool m_available{true};
std::map<std::string, AccountRecord, std::less<>>
m_accounts_by_subject{};
std::map<std::string, std::string, std::less<>>
m_subject_by_username{};
std::map<std::string, SessionRecord, std::less<>>
m_sessions_by_id{};
std::map<std::string, std::string, std::less<>>
m_session_id_by_digest{};
};
struct AuditEvent {
std::string event_type{};
std::string subject{};
std::string internal_reason{};
bool success{false};
Void::Time::CivilClock::time_point timestamp{};
};
class AuditSink
{
public:
virtual ~AuditSink() = default;
[[nodiscard]] virtual Void::Result::Result<void>
record(const AuditEvent& event) = 0;
};
class InMemoryAuditSink final : public AuditSink
{
public:
explicit InMemoryAuditSink(std::size_t max_events = 1024) noexcept
: m_max_events(max_events)
{
}
[[nodiscard]] Void::Result::Result<void>
record(const AuditEvent& event) override;
[[nodiscard]] std::vector<AuditEvent> snapshot() const;
void clear();
private:
std::size_t m_max_events{1024};
mutable std::mutex m_mu{};
std::vector<AuditEvent> m_events{};
};
enum class AuditFailurePolicy : std::uint8_t {
FailClosed = 0,
BestEffort
};
struct PasswordJobBudget {
std::size_t max_memory_bytes{
Void::Security::SecurityLimits::
kDefaultPasswordJobMemoryBudgetBytes};
std::size_t max_concurrent_jobs{
Void::Security::SecurityLimits::
kDefaultMaxConcurrentPasswordJobs};
std::size_t max_waiters{
Void::Security::SecurityLimits::kDefaultMaxWaitingPasswordJobs};
};
struct SessionPolicy {
std::chrono::seconds ttl{
Void::Security::SecurityLimits::kDefaultSessionTtl};
std::size_t max_total_sessions{
Void::Security::SecurityLimits::kDefaultMaxTotalSessions};
std::size_t max_per_subject{
Void::Security::SecurityLimits::kDefaultMaxSessionsPerSubject};
std::chrono::seconds clock_rollback_tolerance{
Void::Security::SecurityLimits::
kDefaultClockRollbackTolerance};
std::size_t expiry_cleanup_batch{
Void::Security::SecurityLimits::kDefaultExpiryCleanupBatch};
};
struct AuthenticatorOptions {
SessionPolicy session{};
PasswordJobBudget password_budget{};
Void::Security::PasswordVerifyBudget verify_budget{};
Void::Security::PasswordHashStrength dummy_hash_strength{
Void::Security::PasswordHashStrength::Moderate};
std::string precomputed_dummy_hash{};
AuditFailurePolicy audit_policy{AuditFailurePolicy::FailClosed};
Void::Resilience::KeyedBucketConfig rate_limit{
.capacity = 20.0,
.refill_per_second = 5.0,
.max_keys = 4096,
.max_key_bytes = 256,
};
std::optional<Void::Time::CivilClock::time_point>
last_known_civil_time{};
Void::Security::LockPolicy secret_lock_policy{
Void::Security::LockPolicy::StandardWiped};
std::function<void()> before_password_verify_hook{};
};
class BearerToken
{
public:
BearerToken() noexcept = default;
BearerToken(BearerToken&&) noexcept = default;
BearerToken& operator=(BearerToken&&) noexcept = default;
BearerToken(const BearerToken&) = delete;
BearerToken& operator=(const BearerToken&) = delete;
[[nodiscard]] static Void::Result::Result<BearerToken>
from_string(std::string_view raw,
Void::Security::LockPolicy policy =
Void::Security::LockPolicy::StandardWiped);
[[nodiscard]] std::string_view expose_secret() const noexcept
{
return m_buf.string_view();
}
[[nodiscard]] bool empty() const noexcept { return m_buf.empty(); }
void clear() noexcept { m_buf.clear(); }
private:
explicit BearerToken(Void::Security::SecureBuffer buf) noexcept
: m_buf(std::move(buf))
{
}
Void::Security::SecureBuffer m_buf{};
friend class Authenticator;
};
struct LoginInput {
std::string username{};
std::string password{};
};
struct SessionGrant {
std::string session_id{};
BearerToken bearer_token{};
Void::Time::CivilClock::time_point expires_at{};
Void::Security::Principal principal{};
};
struct AuthenticatorStats {
std::size_t active_password_jobs{0};
std::size_t waiting_password_jobs{0};
std::size_t reserved_password_memory_bytes{0};
bool closing{false};
};
class Authenticator
{
public:
[[nodiscard]] static Void::Result::Result<
std::unique_ptr<Authenticator>>
create(std::shared_ptr<AccountSessionPort> port,
Void::Async::Executor& executor,
AuthenticatorOptions options = {},
std::shared_ptr<AuditSink> audit_sink = {},
const Void::Time::MonotonicClock& monotonic_clock =
Void::Time::SystemMonotonicClock::instance(),
const Void::Time::CivilClock& civil_clock =
Void::Time::SystemCivilClock::instance());
~Authenticator();
Authenticator(const Authenticator&) = delete;
Authenticator& operator=(const Authenticator&) = delete;
Authenticator(Authenticator&&) = delete;
Authenticator& operator=(Authenticator&&) = delete;
[[nodiscard]] Void::Coro::Task<Void::Result::Result<SessionGrant>>
login(LoginInput input,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Security::Principal>>
authenticate(const BearerToken& token,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void>>
revoke(std::string session_id,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<std::size_t>
cleanup_expired_step();
void reconcile_clock(
Void::Time::CivilClock::time_point new_watermark) noexcept;
void request_stop() noexcept;
[[nodiscard]] Void::Result::Result<void> close_and_join();
[[nodiscard]] AuthenticatorStats stats() const noexcept;
private:
struct State;
explicit Authenticator(std::shared_ptr<State> state) noexcept;
std::shared_ptr<State> m_state;
};
} // namespace Void::SecurityAsync
+170
View File
@@ -0,0 +1,170 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Security/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Security
{
struct Principal {
std::string subject{};
std::vector<std::string> roles{};
std::uint64_t policy_generation{0};
std::map<std::string, std::string, std::less<>> attributes{};
};
struct ResourceAttributes {
std::string resource_type{};
std::string resource_id{};
std::map<std::string, std::string, std::less<>> attributes{};
};
enum class Effect : std::uint8_t { Deny = 0, Allow = 1 };
/// Native typed policy predicate AST with bounded depth (<= 16) and zero
/// script/filesystem/network side effects.
struct Predicate {
enum class Kind : std::uint8_t {
AlwaysTrue = 0,
AlwaysFalse,
HasRole,
SubjectEquals,
ResourceTypeEquals,
ResourceIdEquals,
ResourceAttrEquals,
PrincipalAttrEquals,
ResourceOwnerMatchesSubject,
AllOf,
AnyOf,
Not
};
Kind kind{Kind::AlwaysFalse};
std::string key{};
std::string value{};
std::vector<Predicate> children{};
[[nodiscard]] static Predicate always_true()
{
return Predicate{.kind = Kind::AlwaysTrue};
}
[[nodiscard]] static Predicate always_false()
{
return Predicate{.kind = Kind::AlwaysFalse};
}
[[nodiscard]] static Predicate has_role(std::string role)
{
return Predicate{.kind = Kind::HasRole,
.value = std::move(role)};
}
[[nodiscard]] static Predicate subject_equals(std::string subject)
{
return Predicate{.kind = Kind::SubjectEquals,
.value = std::move(subject)};
}
[[nodiscard]] static Predicate resource_type(std::string type)
{
return Predicate{.kind = Kind::ResourceTypeEquals,
.value = std::move(type)};
}
[[nodiscard]] static Predicate resource_id(std::string id)
{
return Predicate{.kind = Kind::ResourceIdEquals,
.value = std::move(id)};
}
[[nodiscard]] static Predicate resource_attr(std::string k,
std::string v)
{
return Predicate{.kind = Kind::ResourceAttrEquals,
.key = std::move(k),
.value = std::move(v)};
}
[[nodiscard]] static Predicate principal_attr(std::string k,
std::string v)
{
return Predicate{.kind = Kind::PrincipalAttrEquals,
.key = std::move(k),
.value = std::move(v)};
}
[[nodiscard]] static Predicate
owner_is_subject(std::string owner_attr = "owner")
{
return Predicate{.kind = Kind::ResourceOwnerMatchesSubject,
.key = std::move(owner_attr)};
}
[[nodiscard]] static Predicate all_of(std::vector<Predicate> items)
{
return Predicate{.kind = Kind::AllOf,
.children = std::move(items)};
}
[[nodiscard]] static Predicate any_of(std::vector<Predicate> items)
{
return Predicate{.kind = Kind::AnyOf,
.children = std::move(items)};
}
[[nodiscard]] static Predicate negate(Predicate child)
{
Predicate p{.kind = Kind::Not};
p.children.push_back(std::move(child));
return p;
}
};
struct PolicyRule {
std::string id{};
Effect effect{Effect::Deny};
std::string action{};
Predicate condition{Predicate::always_false()};
};
struct Decision {
bool allowed{false};
std::string matched_rule_id{};
std::string reason{};
std::uint64_t policy_generation{0};
};
/// Immutable validated authorization policy snapshot.
/// Enforces default-deny and deny-overrides-allow with bounded rules
/// (<= 4096), roles (<= 64), and predicate nesting depth (<= 16).
class PolicySnapshot
{
public:
[[nodiscard]] static Void::Result::Result<PolicySnapshot>
create(std::uint64_t generation, std::vector<PolicyRule> rules);
[[nodiscard]] std::uint64_t generation() const noexcept
{
return m_generation;
}
[[nodiscard]] std::size_t rule_count() const noexcept
{
return m_rules.size();
}
[[nodiscard]] Decision
authorize(const Principal& principal, std::string_view action,
const ResourceAttributes& resource) const;
private:
PolicySnapshot(std::uint64_t generation,
std::vector<PolicyRule> rules) noexcept
: m_generation(generation), m_rules(std::move(rules))
{
}
std::uint64_t m_generation{0};
std::vector<PolicyRule> m_rules{};
};
} // namespace Void::Security
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Security/SecureBuffer.hpp>
#include <Void/Security/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Security
{
inline constexpr std::uint8_t kEnvelopeVersionV1 = 1;
inline constexpr std::uint8_t kEnvelopeAlgXChaCha20Poly1305Ietf = 1;
inline constexpr std::size_t kEnvelopeKeyBytes = 32;
inline constexpr std::size_t kEnvelopeNonceBytes = 24;
inline constexpr std::size_t kEnvelopeTagBytes = 16;
struct EnvelopeHeader {
std::uint8_t version{kEnvelopeVersionV1};
std::uint8_t algorithm{kEnvelopeAlgXChaCha20Poly1305Ietf};
std::string key_id{};
std::uint32_t plaintext_size{0};
};
/// Parse and validate a versioned VSEC envelope header without decrypting.
/// Never falls back to legacy seal_secret framing.
[[nodiscard]] Void::Result::Result<EnvelopeHeader>
inspect_envelope(std::span<const unsigned char> envelope);
/// Versioned AEAD key ring supporting key rotation: writes use the single
/// active key ID, reads resolve the key ID authenticated in the header, and
/// retirement requires proving no ciphertext still depends on that key ID.
class SecretKeyRing
{
public:
SecretKeyRing() = default;
SecretKeyRing(SecretKeyRing&&) noexcept = default;
SecretKeyRing& operator=(SecretKeyRing&&) noexcept = default;
SecretKeyRing(const SecretKeyRing&) = delete;
SecretKeyRing& operator=(const SecretKeyRing&) = delete;
[[nodiscard]] Void::Result::Result<void>
add_key(std::string key_id,
std::span<const unsigned char> raw_key,
bool make_active = false,
LockPolicy lock_policy = LockPolicy::StandardWiped);
[[nodiscard]] Void::Result::Result<void> generate_and_add_key(
std::string key_id, bool make_active = true,
LockPolicy lock_policy = LockPolicy::StandardWiped);
[[nodiscard]] Void::Result::Result<void>
set_active_key(std::string_view key_id);
/// Retire a non-active key only after the caller supplies an
/// inventory of remaining ciphertext key IDs proving none reference
/// `key_id`.
[[nodiscard]] Void::Result::Result<void>
retire_key(std::string_view key_id,
std::span<const std::string>
remaining_ciphertext_key_ids);
[[nodiscard]] std::optional<std::string>
active_key_id() const;
[[nodiscard]] bool has_key(std::string_view key_id) const;
[[nodiscard]] std::vector<std::string> key_ids() const;
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
seal(std::span<const unsigned char> plaintext,
std::span<const unsigned char> aad = {}) const;
[[nodiscard]] Void::Result::Result<SecureBuffer>
open(std::span<const unsigned char> envelope,
std::span<const unsigned char> aad = {},
LockPolicy out_policy = LockPolicy::StandardWiped) const;
private:
std::map<std::string, SecureBuffer, std::less<>> m_keys{};
std::string m_active_key_id{};
};
} // namespace Void::Security
+84
View File
@@ -0,0 +1,84 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Security/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string_view>
namespace Void::Security
{
enum class LockPolicy : std::uint8_t {
StandardWiped = 0,
LockedOptional,
LockedRequired
};
/// Move-only secret byte buffer wiped with sodium_memzero on release.
/// Supports optional or required libsodium locked allocation without
/// silently downgrading a LockedRequired policy.
class SecureBuffer
{
public:
SecureBuffer() noexcept = default;
~SecureBuffer() noexcept;
SecureBuffer(SecureBuffer&& other) noexcept;
SecureBuffer& operator=(SecureBuffer&& other) noexcept;
SecureBuffer(const SecureBuffer&) = delete;
SecureBuffer& operator=(const SecureBuffer&) = delete;
[[nodiscard]] static Void::Result::Result<SecureBuffer>
allocate(std::size_t size,
LockPolicy policy = LockPolicy::StandardWiped);
[[nodiscard]] static Void::Result::Result<SecureBuffer>
from_bytes(std::span<const unsigned char> data,
LockPolicy policy = LockPolicy::StandardWiped);
[[nodiscard]] static Void::Result::Result<SecureBuffer>
from_string(std::string_view text,
LockPolicy policy = LockPolicy::StandardWiped);
[[nodiscard]] std::span<const unsigned char> view() const noexcept
{
return m_data ? std::span<const unsigned char>{m_data, m_size}
: std::span<const unsigned char>{};
}
[[nodiscard]] std::span<unsigned char> writable() noexcept
{
return m_data ? std::span<unsigned char>{m_data, m_size}
: std::span<unsigned char>{};
}
[[nodiscard]] std::string_view string_view() const noexcept
{
return m_data ? std::string_view{
reinterpret_cast<const char*>(m_data),
m_size}
: std::string_view{};
}
[[nodiscard]] std::size_t size() const noexcept { return m_size; }
[[nodiscard]] bool empty() const noexcept { return m_size == 0; }
[[nodiscard]] bool is_locked() const noexcept { return m_locked; }
void clear() noexcept;
/// Total bytes wiped across SecureBuffer lifetimes (for
/// sanitizer-safe wipe verification in tests).
[[nodiscard]] static std::uint64_t total_wiped_bytes() noexcept;
private:
unsigned char* m_data{nullptr};
std::size_t m_size{0};
bool m_locked{false};
};
} // namespace Void::Security
+23 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Security/Types.hpp>
#include <array>
#include <cstddef>
@@ -23,6 +24,14 @@ namespace Void::Security
inline constexpr std::size_t secret_authentication_bytes = 16;
using SecretKey = std::array<unsigned char, secret_key_bytes>;
/// Wipe a mutable byte buffer with sodium_memzero.
void wipe_bytes(std::span<unsigned char> buffer) noexcept;
/// Constant-time comparison using sodium_memcmp.
[[nodiscard]] bool
constant_time_equal(std::span<const unsigned char> lhs,
std::span<const unsigned char> rhs) noexcept;
/// Generate a URL-safe, unpadded token containing `entropy_bytes` of
/// cryptographically secure randomness.
[[nodiscard]] Void::Result::Result<std::string>
@@ -44,6 +53,18 @@ namespace Void::Security
std::string_view password,
PasswordHashStrength strength = PasswordHashStrength::Moderate);
/// Parse Argon2id cost parameters (`$argon2id$v=19$m=...,t=...,p=...$...`)
/// without executing Argon2id or allocating memory.
[[nodiscard]] Void::Result::Result<Argon2idCost>
parse_argon2id_cost(std::string_view encoded_hash);
/// Verify a password against an encoded Argon2id hash after enforcing input
/// caps and operator-approved memory/iteration/parallelism cost budgets.
[[nodiscard]] Void::Result::Result<bool>
verify_password_budgeted(std::string_view password,
std::string_view encoded_hash,
const PasswordVerifyBudget& budget = {});
/// Verify a password against a libsodium Argon2id encoded hash.
/// Malformed hashes are treated as a non-match.
[[nodiscard]] Void::Result::Result<bool>
@@ -53,8 +74,8 @@ namespace Void::Security
/// Generate a cryptographically random key for local secret encryption.
[[nodiscard]] Void::Result::Result<SecretKey> random_secret_key();
/// Encrypt and authenticate bytes. The returned portable envelope is
/// nonce || ciphertext || authentication tag.
/// Encrypt and authenticate bytes using the legacy local secret format
/// (24-byte nonce || crypto_secretbox_easy combined MAC + ciphertext).
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
seal_secret(std::span<const unsigned char> plaintext,
const SecretKey& key);
+197
View File
@@ -0,0 +1,197 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <optional>
#include <span>
#include <string>
#include <system_error>
#include <utility>
namespace Void::Security
{
struct SecurityLimits {
static constexpr std::size_t kMaxPasswordBytes = 1024;
static constexpr std::size_t kMaxEncodedHashBytes = 1024;
static constexpr std::size_t kMaxTokenBytes = 512;
static constexpr std::size_t kMaxSecretPlaintextBytes =
16ULL * 1024ULL * 1024ULL;
static constexpr std::size_t kMaxKeyIdBytes = 128;
static constexpr std::size_t kMaxAadBytes = 64ULL * 1024ULL;
static constexpr std::size_t kMaxRolesPerPrincipal = 64;
static constexpr std::size_t kMaxPolicyRules = 4096;
static constexpr std::size_t kMaxPredicateDepth = 16;
static constexpr std::size_t kDefaultPasswordJobMemoryBudgetBytes =
512ULL * 1024ULL * 1024ULL;
static constexpr std::size_t kDefaultMaxConcurrentPasswordJobs = 2;
static constexpr std::size_t kDefaultMaxWaitingPasswordJobs = 32;
static constexpr std::size_t kDefaultMaxTotalSessions = 10000;
static constexpr std::size_t kDefaultMaxSessionsPerSubject = 16;
static constexpr std::chrono::seconds kDefaultSessionTtl{3600};
static constexpr std::chrono::seconds
kDefaultClockRollbackTolerance{60};
static constexpr std::size_t kDefaultExpiryCleanupBatch = 256;
};
enum class SecurityErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
input_too_large = 2,
malformed_hash = 3,
cost_budget_exceeded = 4,
authentication_failed = 5,
denied = 6,
rate_limited = 7,
session_expired = 8,
session_revoked = 9,
session_capacity_exceeded = 10,
clock_rollback = 11,
conflict = 12,
key_not_found = 13,
key_in_use = 14,
unsupported_version = 15,
policy_invalid = 16,
audit_failed = 17,
locked_memory_unavailable = 18,
backend_error = 19,
store_unavailable = 20,
cancelled = 21,
timeout = 22,
overloaded = 23,
closed = 24
};
[[nodiscard]] inline Void::Result::Error
make_security_error(SecurityErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case SecurityErrorCode::none:
kind = ErrorKind::internal;
break;
case SecurityErrorCode::invalid_argument:
case SecurityErrorCode::input_too_large:
case SecurityErrorCode::policy_invalid:
kind = ErrorKind::invalid_argument;
break;
case SecurityErrorCode::malformed_hash:
case SecurityErrorCode::authentication_failed:
kind = ErrorKind::corrupt;
break;
case SecurityErrorCode::cost_budget_exceeded:
case SecurityErrorCode::session_capacity_exceeded:
case SecurityErrorCode::locked_memory_unavailable:
kind = ErrorKind::exhausted;
break;
case SecurityErrorCode::denied:
case SecurityErrorCode::session_expired:
case SecurityErrorCode::session_revoked:
case SecurityErrorCode::clock_rollback:
case SecurityErrorCode::conflict:
case SecurityErrorCode::key_in_use:
kind = ErrorKind::conflict;
break;
case SecurityErrorCode::rate_limited:
case SecurityErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case SecurityErrorCode::key_not_found:
kind = ErrorKind::not_found;
break;
case SecurityErrorCode::unsupported_version:
kind = ErrorKind::unsupported;
break;
case SecurityErrorCode::audit_failed:
case SecurityErrorCode::backend_error:
case SecurityErrorCode::store_unavailable:
kind = ErrorKind::internal;
break;
case SecurityErrorCode::cancelled:
case SecurityErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case SecurityErrorCode::timeout:
kind = ErrorKind::timeout;
break;
}
const ErrorCode domain_code{Void::Result::kSecurityErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
struct Argon2idCost {
std::uint32_t version{19};
std::uint64_t memory_kib{0};
std::uint64_t iterations{0};
std::uint32_t parallelism{0};
[[nodiscard]] std::optional<std::uint64_t>
memory_bytes() const noexcept
{
if (memory_kib >
std::numeric_limits<std::uint64_t>::max() / 1024ULL) {
return std::nullopt;
}
return memory_kib * 1024ULL;
}
};
struct PasswordVerifyBudget {
std::uint64_t max_memory_bytes{256ULL * 1024ULL * 1024ULL};
std::uint64_t max_iterations{16};
std::uint32_t max_parallelism{4};
};
enum class FaultOperation : std::uint8_t {
none = 0,
any,
sodium_init,
random_bytes,
locked_alloc,
password_hash,
secret_seal,
secret_open
};
struct FaultConfig {
FaultOperation op{FaultOperation::none};
SecurityErrorCode code{SecurityErrorCode::backend_error};
std::size_t fail_after{0};
};
class ScopedFaultGuard
{
public:
explicit ScopedFaultGuard(FaultConfig config) noexcept;
~ScopedFaultGuard() noexcept;
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
private:
FaultConfig m_previous{};
std::size_t m_previous_hits{0};
};
namespace Detail
{
[[nodiscard]] std::optional<Void::Result::Error>
maybe_inject_fault(FaultOperation op, std::string_view operation);
} // namespace Detail
} // namespace Void::Security
+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
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <memory>
#include <string>
namespace Void::SystemAsync
{
struct ProcessManagerOptions {
std::size_t max_active_children{64};
std::size_t max_pending_spawns{128};
std::chrono::milliseconds default_kill_grace{std::chrono::milliseconds{2000}};
};
class ProcessManager;
class ManagedChild
{
public:
ManagedChild() noexcept = default;
~ManagedChild() noexcept;
ManagedChild(const ManagedChild&) = delete;
ManagedChild& operator=(const ManagedChild&) = delete;
ManagedChild(ManagedChild&&) noexcept;
ManagedChild& operator=(ManagedChild&&) noexcept;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] Void::Process::Child& child() noexcept { return child_; }
[[nodiscard]] const Void::Process::Child& child() const noexcept
{
return child_;
}
void release_slot() noexcept;
private:
friend class ProcessManager;
struct SlotGuard;
Void::Process::Child child_{};
std::shared_ptr<void> slot_token_{};
};
class ProcessManager
{
public:
struct Impl;
explicit ProcessManager(
Void::IO::Driver& driver,
Void::Async::Executor& executor,
ProcessManagerOptions options = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~ProcessManager() noexcept;
ProcessManager(const ProcessManager&) = delete;
ProcessManager& operator=(const ProcessManager&) = delete;
ProcessManager(ProcessManager&&) = delete;
ProcessManager& operator=(ProcessManager&&) = delete;
[[nodiscard]] Void::Result::Result<ManagedChild, Void::Result::Error>
spawn(const Void::Process::SpawnOptions& options);
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
communicate(Void::Process::Child& child,
std::string stdin_data = {},
Void::Process::CaptureLimits limits = {},
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
communicate(ManagedChild& managed,
std::string stdin_data = {},
Void::Process::CaptureLimits limits = {},
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
wait(Void::Process::Child& child,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
wait(ManagedChild& managed,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
close_and_join(Void::Async::OperationOptions options = {});
[[nodiscard]] std::size_t active_children() const noexcept;
[[nodiscard]] bool closed() const noexcept;
private:
std::shared_ptr<Impl> impl_;
};
} // namespace Void::SystemAsync
+116
View File
@@ -0,0 +1,116 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <string>
namespace Void::SystemAsync
{
enum class WatchEventKind {
created,
modified,
deleted,
replaced_inode,
symlink_changed,
permission_denied,
rescan_required,
};
struct WatchEvent {
WatchEventKind kind{WatchEventKind::modified};
std::filesystem::path path{};
bool exists{false};
std::uint64_t dev{0};
std::uint64_t ino{0};
std::uint64_t size{0};
int sys_errno{0};
};
struct WatcherLimits {
std::size_t max_watched_paths{1024};
std::size_t max_queued_events{256};
std::chrono::milliseconds poll_interval{std::chrono::milliseconds{250}};
int debounce_polls{1};
};
struct WatchPathOptions {
std::optional<std::filesystem::path> allowed_root{};
bool allow_symlink{false};
};
using WatchCallback = std::function<void(const WatchEvent&)>;
using ErrorSink = std::function<void(const Void::Result::Error&)>;
class WatcherService;
class WatchSubscription
{
public:
WatchSubscription() noexcept = default;
~WatchSubscription() noexcept;
WatchSubscription(const WatchSubscription&) = delete;
WatchSubscription& operator=(const WatchSubscription&) = delete;
WatchSubscription(WatchSubscription&&) noexcept;
WatchSubscription& operator=(WatchSubscription&&) noexcept;
[[nodiscard]] bool active() const noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
close_and_join();
private:
friend class WatcherService;
struct Token;
std::shared_ptr<Token> token_;
};
class WatcherService
{
public:
struct Impl;
explicit WatcherService(
Void::Async::Executor& executor,
WatcherLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
ErrorSink error_sink = {},
bool start_background_thread = false);
~WatcherService() noexcept;
WatcherService(const WatcherService&) = delete;
WatcherService& operator=(const WatcherService&) = delete;
WatcherService(WatcherService&&) = delete;
WatcherService& operator=(WatcherService&&) = delete;
[[nodiscard]] Void::Result::Result<WatchSubscription, Void::Result::Error>
watch(const std::filesystem::path& path,
WatchCallback callback,
WatchPathOptions options = {});
void poll_once();
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] std::size_t queued_event_count() const noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> shutdown();
private:
std::shared_ptr<Impl> impl_;
};
} // namespace Void::SystemAsync
+105 -84
View File
@@ -1,5 +1,7 @@
#pragma once
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstdint>
#include <optional>
@@ -12,113 +14,132 @@
#include <unistd.h>
#endif
// Generic, app-agnostic process/system resource queries. Used to feed monitors
// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully
// supported; other platforms return nullopt / 0 so callers degrade gracefully.
namespace Void::SystemInfo
{
// ── memory ──────────────────────────────────────────────────────────────
/// Resident set size (physical memory) of the current process, in bytes.
/// nullopt if it cannot be determined on this platform.
[[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
{
/// Resident set size (physical memory) of the current process, in bytes.
/// nullopt if it cannot be determined on this platform.
[[nodiscard]] inline std::optional<std::uint64_t> process_memory_bytes()
{
#if defined(__linux__)
// /proc/self/statm: "size resident shared text lib data dt" in pages.
std::ifstream statm{"/proc/self/statm"};
std::uint64_t total_pages = 0, resident_pages = 0;
if (statm >> total_pages >> resident_pages) {
const long page = ::sysconf(_SC_PAGESIZE);
if (page > 0) {
return resident_pages * static_cast<std::uint64_t>(page);
}
}
return std::nullopt;
std::ifstream statm{"/proc/self/statm"};
std::uint64_t total_pages = 0, resident_pages = 0;
if (statm >> total_pages >> resident_pages) {
const long page = ::sysconf(_SC_PAGESIZE);
if (page > 0) {
return resident_pages * static_cast<std::uint64_t>(page);
}
}
return std::nullopt;
#else
return std::nullopt;
return std::nullopt;
#endif
}
}
struct SystemMemory {
std::uint64_t total = 0; ///< total physical RAM, bytes
std::uint64_t available = 0; ///< approx. RAM available to new work
};
struct SystemMemory {
std::uint64_t total = 0; ///< total physical RAM, bytes
std::uint64_t available = 0; ///< approx. RAM available to new work
};
/// Total and (approximately) available system memory in bytes.
[[nodiscard]] inline std::optional<SystemMemory> system_memory()
{
/// Total and (approximately) available system memory in bytes.
[[nodiscard]] inline std::optional<SystemMemory> system_memory()
{
#if defined(__linux__)
struct ::sysinfo info{};
if (::sysinfo(&info) != 0) {
return std::nullopt;
}
const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1;
SystemMemory m;
m.total = static_cast<std::uint64_t>(info.totalram) * unit;
// freeram excludes reclaimable cache/buffers, so this is conservative.
m.available =
(static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit;
return m;
struct ::sysinfo info{};
if (::sysinfo(&info) != 0) {
return std::nullopt;
}
const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1;
SystemMemory m;
m.total = static_cast<std::uint64_t>(info.totalram) * unit;
m.available =
(static_cast<std::uint64_t>(info.freeram) + info.bufferram) * unit;
return m;
#else
return std::nullopt;
return std::nullopt;
#endif
}
}
// ── CPU ─────────────────────────────────────────────────────────────────
struct CpuSample {
double ratio{0.0};
bool valid{false};
};
/// Samples this process's CPU usage between successive calls. usage()
/// returns the fraction of a single core consumed since the previous
/// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on
/// multi-core workloads). The first call establishes the baseline and
/// returns 0.
class CpuSampler
{
public:
/// Samples this process's CPU usage between successive calls.
/// `sample()` explicitly distinguishes real 0.0 from unavailable sampling.
class CpuSampler
{
public:
explicit CpuSampler(
const Void::Time::MonotonicClock* clock =
&Void::Time::SystemMonotonicClock::instance())
: clock_(clock != nullptr ? clock
: &Void::Time::SystemMonotonicClock::instance())
{
reset();
}
CpuSampler() { reset(); }
void reset()
{
wall_ = std::chrono::steady_clock::now();
void reset()
{
wall_ = clock_->now();
baseline_valid_ = false;
#if defined(__linux__)
struct ::tms t{};
last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1))
? 0
: (t.tms_utime + t.tms_stime);
struct ::tms t{};
if (::times(&t) != static_cast<::clock_t>(-1)) {
last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
baseline_valid_ = true;
}
#endif
}
}
[[nodiscard]] double usage()
{
const auto now = std::chrono::steady_clock::now();
const std::chrono::duration<double> wall = now - wall_;
wall_ = now;
[[nodiscard]] CpuSample sample(
const Void::Time::MonotonicClock* override_clock = nullptr)
{
const Void::Time::MonotonicClock* active =
(override_clock != nullptr) ? override_clock : clock_;
const auto now = active->now();
const std::chrono::duration<double> wall = now - wall_;
wall_ = now;
#if defined(__linux__)
const long hz = ::sysconf(_SC_CLK_TCK);
struct ::tms t{};
if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) ||
wall.count() <= 0.0) {
return 0.0;
}
const std::int64_t ticks = t.tms_utime + t.tms_stime;
const double cpu_seconds =
static_cast<double>(ticks - last_ticks_) /
static_cast<double>(hz);
last_ticks_ = ticks;
return cpu_seconds / wall.count();
const long hz = ::sysconf(_SC_CLK_TCK);
struct ::tms t{};
if (!baseline_valid_ || hz <= 0 ||
::times(&t) == static_cast<::clock_t>(-1) || wall.count() <= 0.0) {
if (::times(&t) != static_cast<::clock_t>(-1)) {
last_ticks_ = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
baseline_valid_ = true;
}
return CpuSample{0.0, false};
}
const std::int64_t ticks = static_cast<std::int64_t>(t.tms_utime) +
static_cast<std::int64_t>(t.tms_stime);
const std::int64_t delta_ticks =
(ticks >= last_ticks_) ? (ticks - last_ticks_) : 0;
last_ticks_ = ticks;
const double cpu_seconds =
static_cast<double>(delta_ticks) / static_cast<double>(hz);
return CpuSample{cpu_seconds / wall.count(), true};
#else
return 0.0;
(void)wall;
return CpuSample{0.0, false};
#endif
}
}
private:
[[nodiscard]] double usage()
{
const auto s = sample();
return s.valid ? s.ratio : 0.0;
}
std::chrono::steady_clock::time_point wall_;
private:
const Void::Time::MonotonicClock* clock_;
Void::Time::MonotonicClock::time_point wall_{};
bool baseline_valid_{false};
#if defined(__linux__)
std::int64_t last_ticks_ = 0;
std::int64_t last_ticks_{0};
#endif
};
};
} // namespace Void::SystemInfo
+531 -124
View File
@@ -1,144 +1,551 @@
#pragma once
#include <Void/Log/Log.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Types.hpp>
#include <array>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <format>
#include <fstream>
#include <ios>
#include <iterator>
#include <functional>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#if defined(__linux__)
#include <sys/random.h>
#endif
#endif
namespace Void::FileSystem
{
/// Read the entire contents of a file as a string.
///
/// Failure modes wrapped in `Result`:
/// - File does not exist
/// - File cannot be opened (permissions, etc.)
/// - I/O error during read
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file(const std::filesystem::path& path)
{
std::ifstream f{path, std::ios::binary};
if (!f.is_open()) {
Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string());
return Void::Result::fail(std::format(
"FileSystem::read_file: cannot open '{}'", path.string()));
}
std::string content{std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>()};
if (f.bad()) {
Void::Log::warn("FileSystem", "read_file: I/O error reading '{}'",
path.string());
return Void::Result::fail(
std::format("FileSystem::read_file: I/O error reading '{}'",
path.string()));
}
Void::Log::debug("FileSystem", "read_file: '{}' ({} bytes)", path.string(),
content.size());
return Void::Result::ok(std::move(content));
}
/// Write `content` to `path`, overwriting any existing file.
///
/// This is NOT crash-safe — a process killed mid-write may leave a
/// truncated file. Use `atomic_write` when you need durability.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
write_file(const std::filesystem::path& path, std::string_view content)
{
std::ofstream f{path, std::ios::binary | std::ios::trunc};
if (!f.is_open()) {
Void::Log::warn("FileSystem", "write_file: cannot open '{}'", path.string());
return Void::Result::fail(std::format(
"FileSystem::write_file: cannot open '{}'", path.string()));
}
f.write(content.data(), static_cast<std::streamsize>(content.size()));
f.flush();
if (!f.good()) {
Void::Log::warn("FileSystem", "write_file: I/O error writing '{}'",
path.string());
return Void::Result::fail(
std::format("FileSystem::write_file: I/O error writing '{}'",
path.string()));
}
return {};
}
struct ReadFileOptions {
std::size_t max_bytes{16ULL * 1024ULL * 1024ULL};
};
/// Crash-safe write: stage `content` in a sibling `.tmp` file, then
/// atomically rename onto `path`. The rename is atomic on POSIX
/// within the same filesystem; std::filesystem::rename uses the
/// platform-appropriate primitive (`ReplaceFileW` on Windows).
///
/// Note: this does NOT fsync the staged file before rename. A
/// process or kernel crash between write and rename may leave the
/// `.tmp` file behind, but the original `path` is never corrupted.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_write(const std::filesystem::path& path,
std::string_view content)
{
auto staging = path;
staging += ".tmp";
if (auto r = write_file(staging, content); !r) {
return r;
}
std::error_code ec;
std::filesystem::rename(staging, path, ec);
if (ec) {
std::error_code ignore;
std::filesystem::remove(staging, ignore);
Void::Log::warn("FileSystem", "atomic_write: rename failed for '{}': {}",
path.string(), ec.message());
return Void::Result::fail(std::format(
"FileSystem::atomic_write: rename failed for '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "atomic_write: '{}' committed ({} bytes)",
path.string(), content.size());
return {};
}
enum class ReplaceDurability {
atomic_visibility,
durable_sync,
};
/// Create `path` as a directory, including any missing parents.
/// Succeeds (no-op) if `path` already exists as a directory.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
ensure_directory(const std::filesystem::path& path)
{
std::error_code ec;
if (std::filesystem::is_directory(path, ec)) {
return {};
}
std::filesystem::create_directories(path, ec);
if (ec) {
Void::Log::warn("FileSystem", "ensure_directory: cannot create '{}': {}",
path.string(), ec.message());
return Void::Result::fail(std::format(
"FileSystem::ensure_directory: cannot create '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string());
return {};
}
enum class ReplacePhase {
validation,
create_stage,
write_stage,
sync_stage,
rename,
sync_parent,
};
/// Remove a file or directory (recursively for directories).
/// Succeeds (no-op) if the path doesn't exist.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
remove_path(const std::filesystem::path& path)
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
if (ec) {
Void::Log::warn("FileSystem", "remove_path: cannot remove '{}': {}",
path.string(), ec.message());
return Void::Result::fail(
std::format("FileSystem::remove_path: cannot remove '{}': {}",
path.string(), ec.message()));
}
return {};
}
struct ReplaceFailure {
Void::Result::Error error{};
ReplacePhase phase{ReplacePhase::validation};
bool visible_on_disk{false};
bool durability_unknown{false};
};
/// Optional test hook: return a POSIX errno to inject a failure at `phase`.
using ReplaceFaultHook = std::function<std::optional<int>(ReplacePhase phase)>;
struct ReplaceOptions {
ReplaceDurability durability{ReplaceDurability::durable_sync};
unsigned mode{0644};
ReplaceFaultHook fault_hook{};
};
namespace detail
{
[[nodiscard]] inline std::uint64_t next_temp_entropy() noexcept
{
static std::atomic<std::uint64_t> counter{0};
std::uint64_t rnd = 0;
#if defined(__linux__)
if (::getrandom(&rnd, sizeof(rnd), 0) == static_cast<ssize_t>(sizeof(rnd))) {
return rnd ^ (counter.fetch_add(1, std::memory_order_relaxed) << 12);
}
#endif
const auto now = static_cast<std::uint64_t>(
std::chrono::steady_clock::now().time_since_epoch().count());
return now ^ (counter.fetch_add(1, std::memory_order_relaxed) *
0x9e3779b97f4a7c15ULL);
}
#ifndef _WIN32
[[nodiscard]] inline int fsync_eintr(int fd) noexcept
{
for (;;) {
if (::fsync(fd) == 0) {
return 0;
}
if (errno == EINTR) {
continue;
}
return errno;
}
}
#endif
} // namespace detail
/// Read up to `options.max_bytes` from `path` cleanly with typed errors.
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file_bounded(const std::filesystem::path& path,
ReadFileOptions options = {})
{
#ifndef _WIN32
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::read_file: cannot open '{}'", path.string()),
err)};
}
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
const auto sz = static_cast<std::uint64_t>(st.st_size);
if (sz > options.max_bytes) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})",
path.string(),
sz,
options.max_bytes))};
}
}
std::string content;
std::array<char, 8192> buf{};
for (;;) {
const ssize_t n = ::read(fd, buf.data(), buf.size());
if (n > 0) {
const auto un = static_cast<std::size_t>(n);
if (un > options.max_bytes - content.size()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format("FileSystem::read_file: '{}' exceeded limit ({})",
path.string(),
options.max_bytes))};
}
content.append(buf.data(), un);
} else if (n == 0) {
break;
} else {
if (errno == EINTR) {
continue;
}
const int err = errno;
Void::Log::warn("FileSystem",
"read_file: I/O error reading '{}'",
path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::read_file: I/O error reading '{}'",
path.string()),
err)};
}
}
Void::Log::debug("FileSystem",
"read_file: '{}' ({} bytes)",
path.string(),
content.size());
return content;
#else
(void)path;
(void)options;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::read_file: unsupported platform")};
#endif
}
/// Read the entire contents of a file as a string (bounded at 16 MiB default).
[[nodiscard]] inline Void::Result::Result<std::string, Void::Result::Error>
read_file(const std::filesystem::path& path)
{
return read_file_bounded(path, ReadFileOptions{});
}
/// Write `content` to `path`, overwriting any existing file (not crash-safe).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
write_file(const std::filesystem::path& path, std::string_view content)
{
#ifndef _WIN32
const int fd =
::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) {
const int err = errno;
Void::Log::warn("FileSystem",
"write_file: cannot open '{}'",
path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::write_file: cannot open '{}'", path.string()),
err)};
}
Void::System::OwnedFd guard{fd};
std::size_t off = 0;
while (off < content.size()) {
const ssize_t n =
::write(fd, content.data() + off, content.size() - off);
if (n < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
Void::Log::warn("FileSystem",
"write_file: I/O error writing '{}'",
path.string());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::write_file: I/O error writing '{}'",
path.string()),
err)};
}
off += static_cast<std::size_t>(n);
}
return guard.close();
#else
(void)path;
(void)content;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::write_file: unsupported platform")};
#endif
}
/// Atomically stage and replace `path`, distinguishing atomic visibility vs
/// durable commit (`fsync` stage -> `renameat` -> `fsync` parent dir).
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
const std::filesystem::path& path,
std::span<const std::byte> bytes,
ReplaceOptions options = {})
{
#ifndef _WIN32
auto check_fault = [&](ReplacePhase phase,
bool visible,
bool unknown) -> std::optional<ReplaceFailure> {
if (options.fault_hook) {
if (const auto injected = options.fault_hook(phase)) {
return ReplaceFailure{
Void::System::make_system_error(
unknown
? Void::System::SystemErrorCode::durability_unknown
: Void::System::map_errno_to_system_code(*injected),
std::format("FileSystem::replace_file: injected fault for '{}'",
path.string()),
*injected),
phase,
visible,
unknown};
}
}
return std::nullopt;
};
if (auto f = check_fault(ReplacePhase::validation, false, false)) {
return std::unexpected{std::move(*f)};
}
if (path.empty() || !path.has_filename()) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::replace_file: empty path or missing filename"),
ReplacePhase::validation,
false,
false}};
}
const std::filesystem::path parent =
path.parent_path().empty() ? std::filesystem::path{"."}
: path.parent_path();
const std::string target_name = path.filename().string();
if (target_name == "." || target_name == "..") {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::replace_file: invalid target filename"),
ReplacePhase::validation,
false,
false}};
}
const int raw_dir_fd = ::open(
parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir_fd < 0) {
const int err = errno;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::replace_file: cannot open parent '{}'",
parent.string()),
err),
ReplacePhase::validation,
false,
false}};
}
Void::System::OwnedFd dir_fd{raw_dir_fd};
if (auto f = check_fault(ReplacePhase::create_stage, false, false)) {
return std::unexpected{std::move(*f)};
}
std::string tmp_name;
Void::System::OwnedFd tmp_fd;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_tmp_{:016x}", target_name, detail::next_temp_entropy());
const int fd = ::openat(dir_fd.get(),
tmp_name.c_str(),
O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW |
O_CLOEXEC,
static_cast<mode_t>(options.mode));
if (fd >= 0) {
tmp_fd.reset(fd);
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"FileSystem::replace_file: cannot create temp in '{}'",
parent.string()),
last_err),
ReplacePhase::create_stage,
false,
false}};
}
}
if (!tmp_fd.valid()) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::replace_file: exhausted temp names",
last_err),
ReplacePhase::create_stage,
false,
false}};
}
bool cleanup_temp = true;
struct TempCleanup {
int dir_fd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~TempCleanup() noexcept
{
if (active != nullptr && *active && dir_fd >= 0 && name != nullptr) {
(void)::unlinkat(dir_fd, name->c_str(), 0);
}
}
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_temp};
if (auto f = check_fault(ReplacePhase::write_stage, false, false)) {
return std::unexpected{std::move(*f)};
}
std::size_t off = 0;
while (off < bytes.size()) {
const ssize_t n =
::write(tmp_fd.get(), bytes.data() + off, bytes.size() - off);
if (n < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::replace_file: write failed for '{}'",
path.string()),
err),
ReplacePhase::write_stage,
false,
false}};
}
off += static_cast<std::size_t>(n);
}
if (options.durability == ReplaceDurability::durable_sync) {
if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) {
return std::unexpected{std::move(*f)};
}
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::sync_failed,
std::format(
"FileSystem::replace_file: stage fsync failed for '{}'",
path.string()),
err),
ReplacePhase::sync_stage,
false,
false}};
}
}
if (auto closed = tmp_fd.close(); !closed.has_value()) {
return std::unexpected{ReplaceFailure{
std::move(closed.error()),
ReplacePhase::write_stage,
false,
false}};
}
if (auto f = check_fault(ReplacePhase::rename, false, false)) {
return std::unexpected{std::move(*f)};
}
if (::renameat(
dir_fd.get(), tmp_name.c_str(), dir_fd.get(), target_name.c_str()) !=
0) {
const int err = errno;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::replace_file: rename failed for '{}'",
path.string()),
err),
ReplacePhase::rename,
false,
false}};
}
// Rename succeeded: target is now visible on disk; never unlink target!
cleanup_temp = false;
if (options.durability == ReplaceDurability::durable_sync) {
if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) {
return std::unexpected{std::move(*f)};
}
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::replace_file: parent dir fsync failed after rename for '{}'",
path.string()),
err),
ReplacePhase::sync_parent,
true,
true}};
}
}
Void::Log::debug("FileSystem",
"replace_file: '{}' committed ({} bytes)",
path.string(),
bytes.size());
return {};
#else
(void)path;
(void)bytes;
(void)options;
return std::unexpected{ReplaceFailure{
Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::replace_file: unsupported platform"),
ReplacePhase::validation,
false,
false}};
#endif
}
[[nodiscard]] inline std::expected<void, ReplaceFailure> replace_file(
const std::filesystem::path& path,
std::string_view content,
ReplaceOptions options = {})
{
const auto* ptr = reinterpret_cast<const std::byte*>(content.data());
return replace_file(path, std::span<const std::byte>{ptr, content.size()}, std::move(options));
}
/// Crash-safe write: stages content in a unique temp file and atomically
/// renames onto `path`. Delegates to `replace_file(..., atomic_visibility)` to
/// preserve 1.x atomic replacement behavior safely across concurrent writers.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_write(const std::filesystem::path& path, std::string_view content)
{
auto res = replace_file(
path,
content,
ReplaceOptions{.durability = ReplaceDurability::atomic_visibility});
if (!res.has_value()) {
Void::Log::warn("FileSystem",
"atomic_write: failed for '{}': {}",
path.string(),
res.error().error.message());
return std::unexpected{std::move(res.error().error)};
}
return {};
}
/// Create `path` as a directory, including any missing parents.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
ensure_directory(const std::filesystem::path& path)
{
std::error_code ec;
if (std::filesystem::is_directory(path, ec)) {
return {};
}
std::filesystem::create_directories(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"ensure_directory: cannot create '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::ensure_directory: cannot create '{}': {}",
path.string(),
ec.message()))};
}
Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string());
return {};
}
/// Remove a file or directory (recursively for directories).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
remove_path(const std::filesystem::path& path)
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"remove_path: cannot remove '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::remove_path: cannot remove '{}': {}",
path.string(),
ec.message()))};
}
return {};
}
} // namespace Void::FileSystem
+182 -51
View File
@@ -2,72 +2,203 @@
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <functional>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Process
{
/// Captured output from a completed subprocess.
struct Output {
int exit_code{0};
std::string out; ///< captured stdout
std::string err; ///< captured stderr
};
inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL;
inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL;
/// Live line callbacks for run_streaming(). Each fires (on the calling
/// thread, as output arrives) with one line of output, newline stripped.
/// Either may be left empty. The full output is still accumulated into the
/// returned Output.
struct StreamCallbacks {
std::function<void(std::string_view line)> on_stdout;
std::function<void(std::string_view line)> on_stderr;
};
/// Captured output from a completed subprocess.
struct Output {
int exit_code{0};
std::string out; ///< captured stdout
std::string err; ///< captured stderr
};
/// Run an executable synchronously, capturing stdout and stderr separately.
///
/// @param executable Path to the binary (searched via PATH when relative).
/// @param args Additional arguments passed after argv[0].
/// @param stdin_data Data written to the process's stdin before reading.
/// @param timeout Wall-clock limit; zero means no limit. On expiry the
/// process receives SIGTERM and the call returns.
///
/// Returns an error only when process creation itself fails (pipe or fork
/// failure). A process that exits non-zero still yields a successful Result
/// with the appropriate exit_code. A process whose executable is not found
/// exits with code 127 (POSIX convention).
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Live line callbacks for run_streaming() and communicate_blocking().
struct StreamCallbacks {
std::function<void(std::string_view line)> on_stdout;
std::function<void(std::string_view line)> on_stderr;
};
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr
/// arrive, for progress reporting on long-running or streaming processes.
/// The complete output is still captured into the returned Output.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
enum class OverflowPolicy {
fail_and_terminate,
drain_and_truncate,
};
/// Run a command through /bin/sh -c "command".
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
enum class EnvMode {
inherit,
allowlist,
explicit_only,
};
/// Replace the current process image while preserving its PID and inherited
/// environment. Returns only when the platform does not support re-exec or
/// exec fails.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments);
struct EnvironmentPolicy {
EnvMode mode{EnvMode::inherit};
std::vector<std::string> allowlist{};
std::vector<std::pair<std::string, std::string>> set_vars{};
std::vector<std::string> unset_keys{};
std::vector<std::string> redacted_keys{};
};
struct CaptureLimits {
std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes};
std::size_t max_stderr_bytes{kDefaultMaxStderrBytes};
std::size_t max_line_bytes{kDefaultMaxLineBytes};
std::size_t max_stdin_bytes{kDefaultMaxStdinBytes};
OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate};
};
struct SpawnOptions {
std::filesystem::path executable{};
std::vector<std::string> arguments{};
std::optional<std::filesystem::path> working_directory{};
EnvironmentPolicy environment{};
bool stdin_pipe{true};
bool stdout_pipe{true};
bool stderr_pipe{true};
bool search_path{true};
bool new_process_group{true};
std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}};
};
struct ExitStatus {
bool exited{false};
int code{-1};
int signal{0};
int raw_status{0};
};
struct CommunicateResult {
ExitStatus status{};
std::string out{};
std::string err{};
bool stdout_truncated{false};
bool stderr_truncated{false};
bool timed_out{false};
bool cancelled{false};
bool overflowed{false};
};
class Child
{
public:
Child() noexcept = default;
Child(long long pid,
long long pgid,
bool owns_process_group,
Void::System::OwnedFd stdin_fd,
Void::System::OwnedFd stdout_fd,
Void::System::OwnedFd stderr_fd,
std::chrono::milliseconds kill_grace) noexcept;
~Child() noexcept;
Child(const Child&) = delete;
Child& operator=(const Child&) = delete;
Child(Child&& other) noexcept;
Child& operator=(Child&& other) noexcept;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
[[nodiscard]] int stdin_fd() const noexcept;
[[nodiscard]] int stdout_fd() const noexcept;
[[nodiscard]] int stderr_fd() const noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept;
[[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept;
void close_stdin() noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
send_signal(int sig) noexcept;
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1});
[[nodiscard]] Void::Result::Result<std::optional<ExitStatus>, Void::Result::Error>
try_wait();
[[nodiscard]] Void::Result::Result<ExitStatus, Void::Result::Error>
wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1});
private:
long long pid_{-1};
long long pgid_{-1};
bool owns_group_{false};
bool reaped_{true};
ExitStatus cached_status_{};
Void::System::OwnedFd stdin_{};
Void::System::OwnedFd stdout_{};
Void::System::OwnedFd stderr_{};
std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}};
void reset_and_reap() noexcept;
};
[[nodiscard]] Void::Result::Result<Child, Void::Result::Error>
spawn(const SpawnOptions& options);
[[nodiscard]] Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data = {},
CaptureLimits limits = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0},
std::stop_token stop = {},
const StreamCallbacks* callbacks = nullptr);
/// Run an executable synchronously, capturing stdout and stderr separately.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run(const std::filesystem::path& executable,
std::vector<std::string> args = {},
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive.
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
run_streaming(
const std::filesystem::path& executable,
std::vector<std::string> args,
const StreamCallbacks& callbacks,
std::string_view stdin_data = {},
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Run a command through /bin/sh -c "command".
[[nodiscard]] Void::Result::Result<Output, Void::Result::Error>
shell(std::string_view command,
std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Replace the current process image while preserving its PID and inherited
/// environment.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments);
/// Replace the current process image with explicit open-descriptor cleanup policy.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
reexec(const std::filesystem::path& executable,
const std::vector<std::string>& arguments,
bool close_extra_fds);
} // namespace Void::Process
+133 -81
View File
@@ -1,9 +1,13 @@
#pragma once
#include <Void/Log/Log.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <format>
#include <system_error>
@@ -12,113 +16,161 @@
namespace Void::FileSystem
{
struct ListDirectoryOptions {
std::size_t max_entries{65536};
};
/// Return true if path exists (file, directory, or symlink).
[[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept
{
std::error_code ec;
return std::filesystem::exists(path, ec);
std::error_code ec;
return std::filesystem::exists(path, ec);
}
/// Return the size of a regular file in bytes.
[[nodiscard]] inline Void::Result::Result<std::uintmax_t, Void::Result::Error>
file_size(const std::filesystem::path& path)
file_size(const std::filesystem::path& path)
{
std::error_code ec;
auto sz = std::filesystem::file_size(path, ec);
if (ec) {
Void::Log::warn("FileSystem", "file_size: cannot stat '{}': {}", path.string(),
ec.message());
return Void::Result::fail(
std::format("FileSystem::file_size: cannot stat '{}': {}",
path.string(), ec.message()));
}
return Void::Result::ok(sz);
std::error_code ec;
auto sz = std::filesystem::file_size(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"file_size: cannot stat '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::file_size: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(sz);
}
/// Return the last-write time of a path.
[[nodiscard]] inline Void::Result::
Result<std::filesystem::file_time_type, Void::Result::Error>
last_modified(const std::filesystem::path& path)
Result<std::filesystem::file_time_type, Void::Result::Error>
last_modified(const std::filesystem::path& path)
{
std::error_code ec;
auto t = std::filesystem::last_write_time(path, ec);
if (ec) {
Void::Log::warn("FileSystem", "last_modified: cannot stat '{}': {}", path.string(),
ec.message());
return Void::Result::fail(
std::format("FileSystem::last_modified: cannot stat '{}': {}",
path.string(), ec.message()));
}
return Void::Result::ok(t);
std::error_code ec;
auto t = std::filesystem::last_write_time(path, ec);
if (ec) {
Void::Log::warn("FileSystem",
"last_modified: cannot stat '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::last_modified: cannot stat '{}': {}",
path.string(),
ec.message()))};
}
return Void::Result::ok(t);
}
/// List all entries in a directory (non-recursive, filesystem order).
/// List entries in a directory up to `options.max_entries`.
[[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path)
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory_bounded(const std::filesystem::path& path,
ListDirectoryOptions options = {})
{
std::error_code ec;
std::vector<std::filesystem::path> entries;
for (const auto& entry :
std::filesystem::directory_iterator{path, ec}) {
if (ec) {
break;
}
entries.push_back(entry.path());
}
if (ec) {
Void::Log::warn("FileSystem", "list_directory: cannot iterate '{}': {}",
path.string(), ec.message());
return Void::Result::fail(
std::format("FileSystem::list_directory: cannot iterate '{}': {}",
path.string(), ec.message()));
}
Void::Log::debug("FileSystem", "list_directory: '{}' ({} entries)",
path.string(), entries.size());
return Void::Result::ok(std::move(entries));
std::error_code ec;
std::vector<std::filesystem::path> entries;
for (const auto& entry : std::filesystem::directory_iterator{path, ec}) {
if (ec) {
break;
}
if (entries.size() >= options.max_entries) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format(
"FileSystem::list_directory: '{}' exceeded max_entries ({})",
path.string(),
options.max_entries))};
}
entries.push_back(entry.path());
}
if (ec) {
Void::Log::warn("FileSystem",
"list_directory: cannot iterate '{}': {}",
path.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::list_directory: cannot iterate '{}': {}",
path.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"list_directory: '{}' ({} entries)",
path.string(),
entries.size());
return Void::Result::ok(std::move(entries));
}
/// List all entries in a directory (bounded at 65,536 default).
[[nodiscard]] inline Void::Result::
Result<std::vector<std::filesystem::path>, Void::Result::Error>
list_directory(const std::filesystem::path& path)
{
return list_directory_bounded(path, ListDirectoryOptions{});
}
/// Copy a single file. Set overwrite=true to allow replacing an existing dst.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
bool overwrite = false)
copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
bool overwrite = false)
{
std::error_code ec;
auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing
: std::filesystem::copy_options::none;
std::filesystem::copy_file(src, dst, opts, ec);
if (ec) {
Void::Log::warn("FileSystem", "copy_file: '{}' -> '{}': {}", src.string(),
dst.string(), ec.message());
return Void::Result::fail(
std::format("FileSystem::copy_file: '{}' -> '{}': {}",
src.string(), dst.string(), ec.message()));
}
Void::Log::debug("FileSystem", "copy_file: '{}' -> '{}'", src.string(),
dst.string());
return {};
std::error_code ec;
auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing
: std::filesystem::copy_options::none;
std::filesystem::copy_file(src, dst, opts, ec);
if (ec) {
Void::Log::warn("FileSystem",
"copy_file: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::copy_file: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_file: '{}' -> '{}'",
src.string(),
dst.string());
return {};
}
/// Recursively copy a directory tree from src to dst.
/// dst must not already exist; its parent must be accessible.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
copy_dir(const std::filesystem::path& src,
const std::filesystem::path& dst)
copy_dir(const std::filesystem::path& src, const std::filesystem::path& dst)
{
std::error_code ec;
std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive,
ec);
if (ec) {
Void::Log::warn("FileSystem", "copy_dir: '{}' -> '{}': {}", src.string(),
dst.string(), ec.message());
return Void::Result::fail(
std::format("FileSystem::copy_dir: '{}' -> '{}': {}",
src.string(), dst.string(), ec.message()));
}
Void::Log::debug("FileSystem", "copy_dir: '{}' -> '{}'", src.string(),
dst.string());
return {};
std::error_code ec;
std::filesystem::copy(
src, dst, std::filesystem::copy_options::recursive, ec);
if (ec) {
Void::Log::warn("FileSystem",
"copy_dir: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("FileSystem::copy_dir: '{}' -> '{}': {}",
src.string(),
dst.string(),
ec.message()))};
}
Void::Log::debug("FileSystem",
"copy_dir: '{}' -> '{}'",
src.string(),
dst.string());
return {};
}
} // namespace Void::FileSystem
+224 -99
View File
@@ -1,126 +1,251 @@
#pragma once
#include <Void/System/Path.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <format>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>
#ifndef _WIN32
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
/// RAII scoped directory under `std::filesystem::temp_directory_path()`.
///
/// The directory is created with a unique name on construction and
/// recursively removed on destruction. Useful in tests that need a
/// scratch area without manual cleanup.
///
/// Construction throws `std::system_error` if the directory cannot
/// be created. Use `TempDir::open(prefix)` for a non-throwing
/// `Result`-returning factory.
class TempDir
{
public:
explicit TempDir(std::string_view prefix = "void_test_")
: m_path(make_unique_dir(prefix))
{
}
/// RAII scoped directory created with private `0700` permissions and removed
/// safely without following symlinks or deleting replaced directories.
class TempDir
{
public:
explicit TempDir(std::string_view prefix = "void_test_")
{
auto created = create_unique_dir(
std::filesystem::temp_directory_path(), prefix);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempDir() noexcept
{
if (!m_path.empty()) {
Void::Log::debug("FileSystem", "TempDir: removed '{}'", m_path.string());
std::error_code ignore;
std::filesystem::remove_all(m_path, ignore);
}
}
~TempDir() noexcept { remove_if_owned(); }
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
TempDir(TempDir&& other) noexcept
: m_path(std::exchange(other.m_path, {}))
{
}
TempDir(TempDir&& other) noexcept
: m_path(std::exchange(other.m_path, {})),
m_dev(std::exchange(other.m_dev, 0)),
m_ino(std::exchange(other.m_ino, 0))
{
}
TempDir& operator=(TempDir&& other) noexcept
{
if (this != &other) {
if (!m_path.empty()) {
std::error_code ignore;
std::filesystem::remove_all(m_path, ignore);
}
m_path = std::exchange(other.m_path, {});
}
return *this;
}
TempDir& operator=(TempDir&& other) noexcept
{
if (this != &other) {
remove_if_owned();
m_path = std::exchange(other.m_path, {});
m_dev = std::exchange(other.m_dev, 0);
m_ino = std::exchange(other.m_ino, 0);
}
return *this;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
/// Build a path inside the temp dir.
/// Example: `auto log_path = tmp / "test.log";`
[[nodiscard]] std::filesystem::path
operator/(std::string_view relative) const
{
return m_path / relative;
}
[[nodiscard]] std::filesystem::path
operator/(std::string_view relative) const
{
return m_path / relative;
}
/// Non-throwing factory.
[[nodiscard]] static Void::Result::Result<TempDir,
Void::Result::Error>
open(std::string_view prefix = "void_test_")
{
try {
return Void::Result::ok(TempDir{prefix});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
open(std::string_view prefix = "void_test_")
{
return open_in(std::filesystem::temp_directory_path(), prefix);
}
private:
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_test_")
{
return create_unique_dir(directory, prefix);
}
std::filesystem::path m_path;
private:
struct InternalEmpty {};
explicit TempDir(InternalEmpty) noexcept {}
static std::filesystem::path
make_unique_dir(std::string_view prefix)
{
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path();
for (int attempt = 0; attempt < 16; ++attempt) {
const auto seed =
static_cast<std::uint64_t>(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()) ^
(counter.fetch_add(1, std::memory_order_relaxed)
<< 16) ^
static_cast<std::uint64_t>(std::hash<std::thread::id>{}(
std::this_thread::get_id()));
auto candidate =
base / std::format("{}{:016x}", prefix, seed);
std::error_code ec;
if (std::filesystem::create_directory(candidate, ec)) {
Void::Log::debug("FileSystem", "TempDir: created '{}'",
candidate.string());
return candidate;
}
}
throw std::system_error(
std::make_error_code(std::errc::file_exists),
"TempDir: failed to create unique directory after 16 "
"attempts");
}
};
std::filesystem::path m_path;
std::uint64_t m_dev = 0;
std::uint64_t m_ino = 0;
#ifndef _WIN32
static void clear_dir_contents_nofollow(int dir_fd) noexcept
{
const int dup_fd = ::dup(dir_fd);
if (dup_fd < 0) {
return;
}
DIR* dir = ::fdopendir(dup_fd);
if (dir == nullptr) {
(void)::close(dup_fd);
return;
}
std::vector<std::string> subdirs;
std::vector<std::string> files;
while (const struct dirent* ent = ::readdir(dir)) {
const std::string_view name{ent->d_name};
if (name == "." || name == "..") {
continue;
}
struct stat st {};
if (::fstatat(dir_fd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0) {
continue;
}
if (S_ISDIR(st.st_mode)) {
subdirs.emplace_back(name);
} else {
files.emplace_back(name);
}
}
(void)::closedir(dir);
for (const auto& f : files) {
(void)::unlinkat(dir_fd, f.c_str(), 0);
}
for (const auto& d : subdirs) {
const int sub_fd = ::openat(
dir_fd,
d.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (sub_fd >= 0) {
clear_dir_contents_nofollow(sub_fd);
(void)::close(sub_fd);
(void)::unlinkat(dir_fd, d.c_str(), AT_REMOVEDIR);
}
}
}
#endif
void remove_if_owned() noexcept
{
if (m_path.empty()) {
return;
}
#ifndef _WIN32
struct stat st {};
if (::lstat(m_path.c_str(), &st) != 0 || S_ISLNK(st.st_mode) ||
!S_ISDIR(st.st_mode)) {
return;
}
if (static_cast<std::uint64_t>(st.st_dev) != m_dev ||
static_cast<std::uint64_t>(st.st_ino) != m_ino ||
st.st_uid != ::geteuid()) {
return;
}
const int dir_fd = ::open(
m_path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (dir_fd < 0) {
return;
}
struct stat fd_st {};
if (::fstat(dir_fd, &fd_st) == 0 &&
static_cast<std::uint64_t>(fd_st.st_dev) == m_dev &&
static_cast<std::uint64_t>(fd_st.st_ino) == m_ino) {
clear_dir_contents_nofollow(dir_fd);
}
(void)::close(dir_fd);
(void)::rmdir(m_path.c_str());
Void::Log::debug(
"FileSystem", "TempDir: removed '{}'", m_path.string());
#endif
}
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
create_unique_dir(const std::filesystem::path& base,
std::string_view prefix)
{
#ifndef _WIN32
if (prefix.find('/') != std::string_view::npos ||
prefix.find('\0') != std::string_view::npos) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempDir: prefix must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate = base / std::format("{}{:016x}", prefix, seed);
if (::mkdir(candidate.c_str(), 0700) == 0) {
const int fd = ::open(
candidate.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0) {
const int err = errno;
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: open failed after mkdir",
err)};
}
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::rmdir(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempDir: fstat failed",
err)};
}
TempDir out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempDir: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"TempDir: failed creating '{}'", candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempDir: failed to create unique directory after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempDir: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem
+163 -105
View File
@@ -2,135 +2,193 @@
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <format>
#include <fstream>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
#ifndef _WIN32
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
/// RAII scoped *file* under `std::filesystem::temp_directory_path()`.
///
/// A uniquely-named empty file is created on construction and removed on
/// destruction, unless `keep()` was called. Move-only. Useful for staging
/// downloads, copying a shared library to a fresh inode, etc.
///
/// Construction throws `std::system_error` if the file cannot be created;
/// use `TempFile::open(prefix, ext)` for a non-throwing factory.
class TempFile
{
public:
explicit TempFile(std::string_view prefix = "void_",
std::string_view extension = "")
: m_path(make_unique_file(prefix, extension))
{
}
/// RAII scoped regular file created atomically (`O_CREAT|O_EXCL|O_NOFOLLOW`, `0600`).
class TempFile
{
public:
explicit TempFile(std::string_view prefix = "void_",
std::string_view extension = "")
{
auto created = create_unique_file(
std::filesystem::temp_directory_path(), prefix, extension);
if (!created.has_value()) {
throw std::system_error(
std::make_error_code(std::errc::file_exists),
created.error().message());
}
*this = std::move(*created);
}
~TempFile() noexcept
{
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
Void::Log::debug("FileSystem", "TempFile: removed '{}'",
m_path.string());
}
}
~TempFile() noexcept { remove_if_owned(); }
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
TempFile(TempFile&& other) noexcept
: m_path(std::exchange(other.m_path, {})),
m_keep(std::exchange(other.m_keep, true))
{
}
TempFile(TempFile&& other) noexcept
: m_path(std::exchange(other.m_path, {})),
m_keep(std::exchange(other.m_keep, true)),
m_dev(std::exchange(other.m_dev, 0)),
m_ino(std::exchange(other.m_ino, 0))
{
}
TempFile& operator=(TempFile&& other) noexcept
{
if (this != &other) {
if (!m_path.empty() && !m_keep) {
std::error_code ignore;
std::filesystem::remove(m_path, ignore);
}
m_path = std::exchange(other.m_path, {});
m_keep = std::exchange(other.m_keep, true);
}
return *this;
}
TempFile& operator=(TempFile&& other) noexcept
{
if (this != &other) {
remove_if_owned();
m_path = std::exchange(other.m_path, {});
m_keep = std::exchange(other.m_keep, true);
m_dev = std::exchange(other.m_dev, 0);
m_ino = std::exchange(other.m_ino, 0);
}
return *this;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
/// Persist the file beyond this object's lifetime (no removal on
/// destruction). Returns the path for convenience.
std::filesystem::path keep() noexcept
{
m_keep = true;
return m_path;
}
std::filesystem::path keep() noexcept
{
m_keep = true;
return m_path;
}
/// Non-throwing factory.
[[nodiscard]] static Void::Result::Result<TempFile,
Void::Result::Error>
open(std::string_view prefix = "void_",
std::string_view extension = "")
{
try {
return Void::Result::ok(TempFile{prefix, extension});
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
}
}
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
open(std::string_view prefix = "void_",
std::string_view extension = "")
{
return open_in(
std::filesystem::temp_directory_path(), prefix, extension);
}
private:
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
open_in(const std::filesystem::path& directory,
std::string_view prefix = "void_",
std::string_view extension = "")
{
return create_unique_file(directory, prefix, extension);
}
std::filesystem::path m_path;
bool m_keep = false;
private:
struct InternalEmpty {};
explicit TempFile(InternalEmpty) noexcept {}
static std::filesystem::path
make_unique_file(std::string_view prefix,
std::string_view extension)
{
static std::atomic<std::uint64_t> counter{0};
const auto base = std::filesystem::temp_directory_path();
for (int attempt = 0; attempt < 16; ++attempt) {
const auto seed =
static_cast<std::uint64_t>(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()) ^
(counter.fetch_add(1, std::memory_order_relaxed) << 16) ^
static_cast<std::uint64_t>(
std::hash<std::thread::id>{}(
std::this_thread::get_id()));
auto candidate =
base / std::format("{}{:016x}{}", prefix, seed, extension);
std::error_code ec;
if (!std::filesystem::exists(candidate, ec)) {
std::ofstream f(candidate);
if (f) {
Void::Log::debug("FileSystem",
"TempFile: created '{}'",
candidate.string());
return candidate;
}
}
}
throw std::system_error(
std::make_error_code(std::errc::file_exists),
"TempFile: failed to create unique file after 16 attempts");
}
};
std::filesystem::path m_path;
bool m_keep = true;
std::uint64_t m_dev = 0;
std::uint64_t m_ino = 0;
void remove_if_owned() noexcept
{
if (m_path.empty() || m_keep) {
return;
}
#ifndef _WIN32
struct stat st {};
if (::lstat(m_path.c_str(), &st) == 0 && !S_ISLNK(st.st_mode) &&
S_ISREG(st.st_mode) &&
static_cast<std::uint64_t>(st.st_dev) == m_dev &&
static_cast<std::uint64_t>(st.st_ino) == m_ino) {
(void)::unlink(m_path.c_str());
Void::Log::debug(
"FileSystem", "TempFile: removed '{}'", m_path.string());
}
#endif
}
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
create_unique_file(const std::filesystem::path& base,
std::string_view prefix,
std::string_view extension)
{
#ifndef _WIN32
if (prefix.find('/') != std::string_view::npos ||
prefix.find('\0') != std::string_view::npos ||
extension.find('/') != std::string_view::npos ||
extension.find('\0') != std::string_view::npos) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"TempFile: prefix/extension must not contain '/' or NUL")};
}
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
const auto seed = detail::next_temp_entropy();
auto candidate =
base / std::format("{}{:016x}{}", prefix, seed, extension);
const int fd = ::open(candidate.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
0600);
if (fd >= 0) {
Void::System::OwnedFd guard{fd};
struct stat st {};
if (::fstat(fd, &st) != 0) {
const int err = errno;
guard.reset();
(void)::unlink(candidate.c_str());
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"TempFile: fstat failed",
err)};
}
TempFile out{InternalEmpty{}};
out.m_path = std::move(candidate);
out.m_keep = false;
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
Void::Log::debug(
"FileSystem", "TempFile: created '{}'", out.m_path.string());
return out;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format("TempFile: failed creating '{}'",
candidate.string()),
last_err)};
}
}
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"TempFile: failed to create unique file after 32 attempts",
last_err)};
#else
(void)base;
(void)prefix;
(void)extension;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"TempFile: unsupported platform")};
#endif
}
};
} // namespace Void::FileSystem
+207
View File
@@ -0,0 +1,207 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <expected>
#include <format>
#include <string>
#include <string_view>
#include <utility>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::System
{
enum class SystemErrorCode : std::int32_t {
invalid_argument = 1,
not_found = 2,
permission_denied = 3,
already_exists = 4,
spawn_failed = 5,
exec_failed = 6,
timed_out = 7,
cancelled = 8,
output_limit = 9,
line_limit = 10,
io_error = 11,
sync_failed = 12,
durability_unknown = 13,
limit_exceeded = 14,
busy = 15,
self_join = 16,
unsupported = 17,
unavailable = 18,
internal = 19,
};
[[nodiscard]] constexpr Void::Result::ErrorKind
classify_system_error(SystemErrorCode code) noexcept
{
switch (code) {
case SystemErrorCode::invalid_argument:
return Void::Result::ErrorKind::invalid_argument;
case SystemErrorCode::not_found:
return Void::Result::ErrorKind::not_found;
case SystemErrorCode::already_exists:
case SystemErrorCode::busy:
case SystemErrorCode::self_join:
return Void::Result::ErrorKind::conflict;
case SystemErrorCode::timed_out:
return Void::Result::ErrorKind::timeout;
case SystemErrorCode::cancelled:
return Void::Result::ErrorKind::cancelled;
case SystemErrorCode::output_limit:
case SystemErrorCode::line_limit:
case SystemErrorCode::limit_exceeded:
return Void::Result::ErrorKind::exhausted;
case SystemErrorCode::unsupported:
return Void::Result::ErrorKind::unsupported;
case SystemErrorCode::unavailable:
return Void::Result::ErrorKind::overloaded;
case SystemErrorCode::permission_denied:
case SystemErrorCode::spawn_failed:
case SystemErrorCode::exec_failed:
case SystemErrorCode::io_error:
case SystemErrorCode::sync_failed:
case SystemErrorCode::durability_unknown:
return Void::Result::ErrorKind::io;
case SystemErrorCode::internal:
return Void::Result::ErrorKind::internal;
}
return Void::Result::ErrorKind::internal;
}
[[nodiscard]] inline SystemErrorCode
map_errno_to_system_code(int sys_errno) noexcept
{
switch (sys_errno) {
case ENOENT:
return SystemErrorCode::not_found;
case EACCES:
case EPERM:
case EROFS:
return SystemErrorCode::permission_denied;
case EEXIST:
return SystemErrorCode::already_exists;
case ETIMEDOUT:
return SystemErrorCode::timed_out;
case ECANCELED:
return SystemErrorCode::cancelled;
case EBUSY:
return SystemErrorCode::busy;
case EINVAL:
case ENAMETOOLONG:
case EISDIR:
case ENOTDIR:
return SystemErrorCode::invalid_argument;
case ENOSYS:
case EOPNOTSUPP:
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
case ENOTSUP:
#endif
return SystemErrorCode::unsupported;
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
return SystemErrorCode::unavailable;
default:
return SystemErrorCode::io_error;
}
}
[[nodiscard]] inline Void::Result::Error make_system_error(
SystemErrorCode code, std::string_view message, int sys_errno = 0)
{
std::string detail;
if (sys_errno != 0) {
detail = std::format("{} (errno={}: {})",
message,
sys_errno,
std::strerror(sys_errno));
} else {
detail.assign(message);
}
std::error_code sys_ec{};
if (sys_errno != 0) {
sys_ec = std::error_code{sys_errno, std::generic_category()};
}
return Void::Result::Error{
classify_system_error(code),
std::move(detail),
Void::Result::ErrorCode{Void::Result::kSystemErrorDomain,
static_cast<std::int32_t>(code)},
sys_ec};
}
class OwnedFd
{
public:
OwnedFd() noexcept = default;
explicit OwnedFd(int fd) noexcept : fd_(fd) {}
~OwnedFd() noexcept { reset(); }
OwnedFd(const OwnedFd&) = delete;
OwnedFd& operator=(const OwnedFd&) = delete;
OwnedFd(OwnedFd&& other) noexcept
: fd_(std::exchange(other.fd_, -1))
{
}
OwnedFd& operator=(OwnedFd&& other) noexcept
{
if (this != &other) {
reset();
fd_ = std::exchange(other.fd_, -1);
}
return *this;
}
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
[[nodiscard]] explicit operator bool() const noexcept { return valid(); }
[[nodiscard]] int get() const noexcept { return fd_; }
[[nodiscard]] int release() noexcept { return std::exchange(fd_, -1); }
void reset(int new_fd = -1) noexcept
{
const int old = std::exchange(fd_, new_fd);
#ifndef _WIN32
if (old >= 0) {
(void)::close(old);
}
#else
(void)old;
#endif
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> close() noexcept
{
const int old = std::exchange(fd_, -1);
if (old < 0) {
return {};
}
#ifndef _WIN32
if (::close(old) != 0) {
const int err = errno;
return std::unexpected{make_system_error(
map_errno_to_system_code(err), "OwnedFd::close failed", err)};
}
#endif
return {};
}
private:
int fd_{-1};
};
} // namespace Void::System
+107
View File
@@ -4,6 +4,7 @@
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <Void/Update/Types.hpp>
#include <array>
#include <chrono>
@@ -68,6 +69,8 @@ namespace Void::Update
std::chrono::system_clock::time_point now{
std::chrono::system_clock::now()};
bool requireUnexpired{true};
SchemaParsePolicy parsePolicy{SchemaParsePolicy::LegacyGeneralJson};
std::size_t maxJsonDepth{64};
};
struct VerifiedFeed {
@@ -193,4 +196,108 @@ namespace Void::Update
/// Select the greatest compatible version, independent of feed order.
[[nodiscard]] std::optional<Release>
selectRelease(const Feed& feed, const SelectionRequest& request);
/// Non-forgeable signature-verified release selection retaining the exact
/// verified envelope bytes, signer key ID, policy decision, and selected
/// release/component metadata. Can only be constructed by verified factory
/// functions.
class VerifiedSelection
{
public:
VerifiedSelection(const VerifiedSelection&) = default;
VerifiedSelection(VerifiedSelection&&) noexcept = default;
VerifiedSelection& operator=(const VerifiedSelection&) = default;
VerifiedSelection& operator=(VerifiedSelection&&) noexcept = default;
[[nodiscard]] const std::string&
signed_envelope_bytes() const noexcept
{
return m_signed_envelope;
}
[[nodiscard]] const std::string&
signed_payload_bytes() const noexcept
{
return m_signed_payload;
}
[[nodiscard]] const std::string& signer_key_id() const noexcept
{
return m_signer_key_id;
}
[[nodiscard]] const std::string& feed_id() const noexcept
{
return m_feed_id;
}
[[nodiscard]] std::uint64_t sequence() const noexcept
{
return m_sequence;
}
[[nodiscard]] std::chrono::system_clock::time_point
expires_at() const noexcept
{
return m_expires_at;
}
[[nodiscard]] SchemaParsePolicy parse_policy() const noexcept
{
return m_parse_policy;
}
[[nodiscard]] const ReleaseIdentity& release() const noexcept
{
return m_release;
}
[[nodiscard]] const std::map<std::string, ComponentRelease>&
component_releases() const noexcept
{
return m_components;
}
private:
VerifiedSelection() = default;
std::string m_signed_envelope{};
std::string m_signed_payload{};
std::string m_signer_key_id{};
std::string m_feed_id{};
std::uint64_t m_sequence{0};
std::chrono::system_clock::time_point m_expires_at{};
SchemaParsePolicy m_parse_policy{
SchemaParsePolicy::LegacyGeneralJson};
ReleaseIdentity m_release{};
std::map<std::string, ComponentRelease> m_components{};
friend Void::Result::Result<VerifiedSelection>
verify_and_select_release(std::string_view envelopeJson,
const Keyring& keys,
const SelectionRequest& request,
const VerificationPolicy& policy);
friend Void::Result::Result<VerifiedSelection>
verify_and_select_component_set(
std::string_view catalogEnvelopeJson,
const std::map<std::string, std::string>&
releaseEnvelopeJsons,
const Keyring& keys, std::string_view primaryComponentId,
const VerificationPolicy& policy);
};
/// Verify an aggregate feed envelope (verify-before-parse), validate
/// policy, and produce a non-forgeable VerifiedSelection for the best
/// compatible release.
[[nodiscard]] Void::Result::Result<VerifiedSelection>
verify_and_select_release(std::string_view envelopeJson,
const Keyring& keys,
const SelectionRequest& request,
const VerificationPolicy& policy = {});
/// Verify a signed component catalog envelope and signed per-component
/// release envelopes, validate dependency closure and transaction limits
/// (<= 32 components, <= 256 dependency edges), and return a non-forgeable
/// VerifiedSelection.
[[nodiscard]] Void::Result::Result<VerifiedSelection>
verify_and_select_component_set(
std::string_view catalogEnvelopeJson,
const std::map<std::string, std::string>& releaseEnvelopeJsons,
const Keyring& keys, std::string_view primaryComponentId,
const VerificationPolicy& policy = {});
} // namespace Void::Update
+228
View File
@@ -0,0 +1,228 @@
#pragma once
#include <Void/Archive/Archive.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Update/Feed.hpp>
#include <Void/Update/Types.hpp>
#include <Void/Update/VersionStore.hpp>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Update
{
/// Durable high-water sequence floor per (feed_id, channel) persisted via
/// atomic file replacement + directory sync. Monotonic across restarts, key
/// rotations, and civil-clock rollbacks; corrupt floor files fail with
/// RecoveryRequired instead of resetting to zero.
class ReplayFloorStore
{
public:
explicit ReplayFloorStore(std::filesystem::path file_path);
[[nodiscard]] Void::Result::Result<void> load();
[[nodiscard]] std::optional<std::uint64_t>
floor(std::string_view feed_id,
std::string_view channel) const;
/// Validate `sequence >= stored_floor` (or strictly `>` when
/// `require_strictly_greater` is true) and durably persist the new
/// high-water mark before returning.
[[nodiscard]] Void::Result::Result<void>
advance(std::string_view feed_id, std::string_view channel,
std::uint64_t sequence,
bool require_strictly_greater = false);
private:
std::filesystem::path m_path{};
mutable std::mutex m_mu{};
std::map<std::string, std::uint64_t, std::less<>> m_floors{};
bool m_loaded{false};
};
/// Explicit trust-root store supporting application bootstrap,
/// authenticated old-trust key rotation, operator-approved rotation, and
/// key revocation without rewriting historical signed bytes.
class TrustStore
{
public:
[[nodiscard]] static std::string
rotation_statement(std::string_view new_key_id,
const Ed25519PublicKey& new_public_key);
[[nodiscard]] Void::Result::Result<void> bootstrap(Keyring keys);
/// Rotate in `new_key_id` using an Ed25519 signature produced by an
/// active trusted key (`authorizing_key_id`) over
/// `rotation_statement(new_key_id, new_public_key)`.
[[nodiscard]] Void::Result::Result<void>
rotate_key_authenticated(
std::string new_key_id,
const Ed25519PublicKey& new_public_key,
std::span<const std::byte> signature,
std::string_view authorizing_key_id);
[[nodiscard]] Void::Result::Result<void>
rotate_key_operator(std::string new_key_id,
const Ed25519PublicKey& new_public_key);
[[nodiscard]] Void::Result::Result<void>
revoke_key(std::string_view key_id);
[[nodiscard]] Keyring snapshot() const;
[[nodiscard]] bool is_revoked(std::string_view key_id) const;
private:
mutable std::mutex m_mu{};
Keyring m_active{};
std::set<std::string, std::less<>> m_revoked{};
};
struct DownloadRequest {
std::string url{};
std::string expected_sha256{};
std::uint64_t expected_size{0};
std::uint64_t max_bytes{0};
std::optional<std::string> resume_validator{};
std::uint64_t resume_offset{0};
std::stop_token stop{};
};
struct DownloadMetadata {
std::string validator{};
bool resumed{false};
};
/// Abstract bounded artifact download transport. Concrete Net/HTTP
/// transports implement this interface without coupling Update to Net.
class ArtifactTransport
{
public:
virtual ~ArtifactTransport() = default;
[[nodiscard]] virtual Void::Result::Result<DownloadMetadata>
download(
const DownloadRequest& request,
const std::function<
Void::Result::Result<void>(std::span<const std::byte>)>&
on_chunk) = 0;
};
/// Offline local-file transport for deterministic update workflow and
/// installed-consumer testing.
class LocalFileArtifactTransport final : public ArtifactTransport
{
public:
void map_url(std::string url, std::filesystem::path file_path,
std::string validator = "v1");
void set_fail_next(bool fail) noexcept;
void set_truncate_bytes(std::optional<std::size_t> bytes) noexcept;
[[nodiscard]] Void::Result::Result<DownloadMetadata> download(
const DownloadRequest& request,
const std::function<
Void::Result::Result<void>(std::span<const std::byte>)>&
on_chunk) override;
private:
struct Entry {
std::filesystem::path path{};
std::string validator{};
};
mutable std::mutex m_mu{};
std::map<std::string, Entry, std::less<>> m_entries{};
bool m_fail_next{false};
std::optional<std::size_t> m_truncate_bytes{};
};
struct LifecycleHooks {
/// Required when ActivationMode::ExternalLifecycle is selected.
std::function<Void::Result::Result<void>(
const Semver::Version&, const std::filesystem::path&)>
activate_external{};
/// Cooperative health probe executed outside coordinator locks.
/// Defaults to immediately healthy if unset.
std::function<Void::Result::Result<bool>(
const Semver::Version&, const std::filesystem::path&)>
health_probe{};
/// Invoked before rollback on readiness failure to stop/join the
/// candidate cleanly.
std::function<void(const Semver::Version&)> stop_candidate{};
/// Returns currently pinned live generations (e.g. loaded plugins)
/// that pruning must not delete.
std::function<std::vector<Semver::Version>()> live_pinned_versions{};
/// Owning progress event snapshot invoked outside coordinator locks.
std::function<void(const InstallReceipt&)> on_progress{};
/// Optional post-commit cleanup hook (also usable to inject cleanup
/// failures in tests to verify CleanupPending without rollback).
std::function<Void::Result::Result<void>()>
post_commit_cleanup_hook{};
};
/// Serialized per-store installation orchestrator combining verified
/// selections, monotonic replay floors, exact-digest streaming downloads,
/// Archive atomic staging, VersionStore single-commit activation,
/// checksummed operation journaling, and pin-aware bounded pruning.
class InstallCoordinator
{
public:
InstallCoordinator(VersionStore& store,
ReplayFloorStore& floor_store,
std::shared_ptr<ArtifactTransport> transport,
LifecycleHooks hooks = {});
InstallCoordinator(const InstallCoordinator&) = delete;
InstallCoordinator& operator=(const InstallCoordinator&) = delete;
[[nodiscard]] Void::Result::Result<InstallReceipt>
install(const VerifiedSelection& selection,
const InstallOptions& options = {});
/// Idempotent recovery pass inspecting both the checksummed
/// operation journal and VersionStore's durable activation/health
/// evidence. Corrupt or unknown journal records halt with
/// RecoveryRequired without discarding evidence.
[[nodiscard]] Void::Result::Result<InstallReceipt> reconcile();
/// Retry post-commit cleanup/pruning after a CleanupPending
/// outcome. Never rolls back a committed version.
[[nodiscard]] Void::Result::Result<InstallReceipt>
retry_cleanup(const InstallOptions& options = {});
void shutdown() noexcept;
[[nodiscard]] bool is_shutdown() const noexcept;
[[nodiscard]] std::filesystem::path
operation_journal_path() const;
private:
VersionStore& m_store;
ReplayFloorStore& m_floor_store;
std::shared_ptr<ArtifactTransport> m_transport;
LifecycleHooks m_hooks{};
mutable std::mutex m_state_mu{};
bool m_active{false};
bool m_shutdown{false};
};
} // namespace Void::Update
+209
View File
@@ -0,0 +1,209 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Text/Semver.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <stop_token>
#include <string>
#include <system_error>
#include <utility>
namespace Void::Update
{
enum class UpdateErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
signature_failed = 2,
untrusted_key = 3,
replay_rejected = 4,
expired = 5,
schema_error = 6,
mirror_mismatch = 7,
digest_mismatch = 8,
size_mismatch = 9,
limit_exceeded = 10,
transport_error = 11,
staging_error = 12,
activation_failed = 13,
health_check_failed = 14,
recovery_required = 15,
cleanup_pending = 16,
unknown_outcome = 17,
conflict = 18,
cancelled = 19,
timeout = 20,
closed = 21,
io_error = 22
};
[[nodiscard]] inline Void::Result::Error
make_update_error(UpdateErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case UpdateErrorCode::none:
kind = ErrorKind::internal;
break;
case UpdateErrorCode::invalid_argument:
case UpdateErrorCode::schema_error:
kind = ErrorKind::invalid_argument;
break;
case UpdateErrorCode::signature_failed:
case UpdateErrorCode::untrusted_key:
case UpdateErrorCode::mirror_mismatch:
case UpdateErrorCode::digest_mismatch:
case UpdateErrorCode::size_mismatch:
case UpdateErrorCode::recovery_required:
kind = ErrorKind::corrupt;
break;
case UpdateErrorCode::replay_rejected:
case UpdateErrorCode::expired:
case UpdateErrorCode::conflict:
case UpdateErrorCode::cleanup_pending:
kind = ErrorKind::conflict;
break;
case UpdateErrorCode::limit_exceeded:
kind = ErrorKind::exhausted;
break;
case UpdateErrorCode::transport_error:
case UpdateErrorCode::staging_error:
case UpdateErrorCode::io_error:
kind = ErrorKind::io;
break;
case UpdateErrorCode::activation_failed:
case UpdateErrorCode::health_check_failed:
case UpdateErrorCode::unknown_outcome:
kind = ErrorKind::internal;
break;
case UpdateErrorCode::cancelled:
case UpdateErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case UpdateErrorCode::timeout:
kind = ErrorKind::timeout;
break;
}
const ErrorCode domain_code{Void::Result::kUpdateErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
/// Explicit JSON parsing policy for signed payloads (C-07).
/// LegacyGeneralJson preserves existing accepted documents;
/// StrictJsonProfile additionally enforces Void::Json::Strict rules
/// (no duplicate keys, integer-only strict numbers, bounded nesting depth).
enum class SchemaParsePolicy : std::uint8_t {
LegacyGeneralJson = 0,
StrictJsonProfile = 1
};
enum class InstallState : std::uint8_t {
Verified = 0,
Downloading,
Staged,
Published,
Activated,
HealthyCommitted,
CleanupPending,
RolledBack,
RecoveryRequired
};
enum class ActivationMode : std::uint8_t {
InternalVersionStore = 0,
ExternalLifecycle = 1
};
struct UpdateLimits {
static constexpr std::size_t kDefaultMaxActiveInstalls = 1;
static constexpr std::size_t kDefaultMaxQueuedSelections = 8;
static constexpr std::size_t kDefaultMaxConcurrentDownloads = 2;
static constexpr std::uint64_t kDefaultMaxArtifactBytes =
512ULL * 1024 * 1024;
static constexpr std::uint64_t kDefaultStagingQuotaBytes =
2ULL * 1024 * 1024 * 1024;
static constexpr std::size_t kDefaultMaxComponentsPerTransaction =
32;
static constexpr std::size_t kDefaultMaxDependencyEdges = 256;
static constexpr std::chrono::milliseconds kDefaultInstallDeadline{
std::chrono::minutes{10}};
static constexpr std::chrono::milliseconds kDefaultReadinessTimeout{
std::chrono::seconds{30}};
static constexpr std::chrono::milliseconds
kDefaultHealthProbeInterval{std::chrono::seconds{1}};
static constexpr std::size_t kDefaultConsecutiveHealthyRequired = 3;
static constexpr std::size_t kDefaultRetainedPreviousVersions = 2;
static constexpr std::size_t kDefaultPruneBatchLimit = 16;
};
struct ReleaseIdentity {
std::string component{};
std::string artifact_id{};
std::string channel{};
Semver::Version version{};
std::uint64_t sequence{0};
std::string sha256{};
std::uint64_t size{0};
std::string url{};
std::string package_type{};
};
struct InstallReceipt {
std::string install_id{};
InstallState state{InstallState::Verified};
ReleaseIdentity release{};
std::string signer_key_id{};
std::string diagnostic{};
bool cleanup_retryable{false};
};
struct InstallOptions {
ActivationMode activation_mode{
ActivationMode::InternalVersionStore};
std::size_t max_active_installs{
UpdateLimits::kDefaultMaxActiveInstalls};
std::size_t max_queued_selections{
UpdateLimits::kDefaultMaxQueuedSelections};
std::size_t max_concurrent_downloads{
UpdateLimits::kDefaultMaxConcurrentDownloads};
std::uint64_t max_artifact_bytes{
UpdateLimits::kDefaultMaxArtifactBytes};
std::uint64_t staging_quota_bytes{
UpdateLimits::kDefaultStagingQuotaBytes};
std::size_t max_components{
UpdateLimits::kDefaultMaxComponentsPerTransaction};
std::size_t max_dependency_edges{
UpdateLimits::kDefaultMaxDependencyEdges};
std::chrono::milliseconds install_deadline{
UpdateLimits::kDefaultInstallDeadline};
std::chrono::milliseconds readiness_timeout{
UpdateLimits::kDefaultReadinessTimeout};
std::chrono::milliseconds health_probe_interval{
UpdateLimits::kDefaultHealthProbeInterval};
std::size_t consecutive_healthy_required{
UpdateLimits::kDefaultConsecutiveHealthyRequired};
std::size_t retained_previous_versions{
UpdateLimits::kDefaultRetainedPreviousVersions};
std::size_t prune_batch_limit{
UpdateLimits::kDefaultPruneBatchLimit};
bool allow_resumable_download{false};
std::optional<std::filesystem::path> isolated_archive_worker{};
std::stop_token stop{};
const Void::Time::MonotonicClock* monotonic_clock{nullptr};
const Void::Time::CivilClock* civil_clock{nullptr};
};
} // namespace Void::Update
+2
View File
@@ -1,4 +1,6 @@
#pragma once
#include <Void/Update/Feed.hpp>
#include <Void/Update/Install.hpp>
#include <Void/Update/Types.hpp>
#include <Void/Update/VersionStore.hpp>
+16
View File
@@ -8,10 +8,16 @@
#include <cstdint>
#include <filesystem>
#include <optional>
#include <span>
#include <vector>
namespace Void::Update
{
struct PruneReport {
std::vector<Semver::Version> removed{};
std::vector<Semver::Version> skipped_due_to_pins{};
bool batch_limit_reached{false};
};
struct PendingActivation {
std::optional<Semver::Version> previousVersion;
Semver::Version candidateVersion;
@@ -86,6 +92,16 @@ namespace Void::Update
Void::Result::Result<std::vector<Semver::Version>>
prune(std::size_t retainedPreviousVersions);
/// Pin-aware bounded pruning pass. Never deletes the active
/// version, pending activation candidate/previous, top
/// `retainedPreviousVersions` healthy versions, or any version in
/// `pinnedVersions`. Reports pin-blocked candidates and honors
/// `batchLimit` (default 16 publications per pass).
[[nodiscard]] Void::Result::Result<PruneReport>
pruneWithPins(std::size_t retainedPreviousVersions,
std::span<const Semver::Version> pinnedVersions,
std::size_t batchLimit = 16);
[[nodiscard]] Void::Result::Result<std::optional<Semver::Version>>
currentVersion() const;
[[nodiscard]] Void::Result::Result<std::optional<PendingActivation>>
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,4 +1,4 @@
void_add_module(Archive
INTERNAL_DEPS Functional
INTERNAL_DEPS Functional Time System
EXTERNAL_DEPS LibArchive::LibArchive
)
+658 -85
View File
@@ -1,48 +1,226 @@
#include <Void/Crypto/Crypto.hpp>
#include <array>
#include <cstdint>
#include <cstring>
#include <format>
#include <fstream>
#include <limits>
#include <utility>
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
namespace Void::Crypto
{
namespace
{
[[nodiscard]] const EVP_MD*
algorithm_impl(HashAlgorithm algorithm) noexcept
thread_local FaultConfig g_fault_config{};
thread_local std::size_t g_fault_hits{0};
[[nodiscard]] std::optional<Void::Result::Error>
maybe_inject_fault(FaultOperation op, std::string_view operation)
{
if (g_fault_config.op == FaultOperation::none) {
return std::nullopt;
}
if (g_fault_config.op != FaultOperation::any &&
g_fault_config.op != op) {
return std::nullopt;
}
if (g_fault_hits < g_fault_config.fail_after) {
++g_fault_hits;
return std::nullopt;
}
++g_fault_hits;
return make_crypto_error(
g_fault_config.code,
std::format("{}: injected crypto backend fault", operation));
}
[[nodiscard]] const char*
algorithm_name(HashAlgorithm algorithm) noexcept
{
switch (algorithm) {
case HashAlgorithm::Sha1:
return EVP_sha1();
return "SHA1";
case HashAlgorithm::Sha256:
return EVP_sha256();
return "SHA256";
case HashAlgorithm::Sha512:
return EVP_sha512();
return "SHA512";
}
return nullptr;
}
[[nodiscard]] std::string openssl_error(std::string_view operation)
[[nodiscard]] const char*
propq_or_null(const ProviderOptions& provider) noexcept
{
const unsigned long code = ERR_get_error();
if (code == 0) {
return std::string{operation};
return provider.property_query.empty()
? nullptr
: provider.property_query.c_str();
}
[[nodiscard]] Void::Result::Error
make_openssl_error(CryptoErrorCode code, std::string_view operation)
{
const unsigned long err_code = ERR_get_error();
ERR_clear_error();
if (err_code == 0) {
return make_crypto_error(code, std::string{operation});
}
std::array<char, 256> buffer{};
ERR_error_string_n(code, buffer.data(), buffer.size());
return std::format("{}: {}", operation, buffer.data());
ERR_error_string_n(err_code, buffer.data(), buffer.size());
return make_crypto_error(
code, std::format("{}: {}", operation, buffer.data()));
}
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>;
using EvpMdCtxPtr =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
using EvpPkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using EvpMacPtr = std::unique_ptr<EVP_MAC, decltype(&EVP_MAC_free)>;
using EvpMacCtxPtr =
std::unique_ptr<EVP_MAC_CTX, decltype(&EVP_MAC_CTX_free)>;
using EvpKdfPtr = std::unique_ptr<EVP_KDF, decltype(&EVP_KDF_free)>;
using EvpKdfCtxPtr =
std::unique_ptr<EVP_KDF_CTX, decltype(&EVP_KDF_CTX_free)>;
[[nodiscard]] const unsigned char*
non_null_bytes(std::span<const std::byte> span) noexcept
{
static constexpr unsigned char kEmptyByte = 0;
return span.empty()
? &kEmptyByte
: reinterpret_cast<const unsigned char*>(span.data());
}
[[nodiscard]] Void::Result::Result<bool>
verify_ed25519_impl(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> public_key,
const ProviderOptions& provider)
{
if (signature.size() != Ed25519SignatureSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_signature_size,
std::format("Crypto::verifyEd25519: signature must be {} "
"bytes",
Ed25519SignatureSize))};
}
if (public_key.size() != Ed25519PublicKeySize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
std::format("Crypto::verifyEd25519: public key must be {} "
"bytes",
Ed25519PublicKeySize))};
}
if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::verifyEd25519: message exceeds {} "
"byte one-shot limit",
CryptoLimits::kMaxOneShotMessageBytes))};
}
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_verify,
"Crypto::verifyEd25519");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
const char* propq = propq_or_null(provider);
EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex(
nullptr, "ED25519", propq,
non_null_bytes(public_key), public_key.size()),
&EVP_PKEY_free};
if (!key) {
const auto code =
provider.property_query.empty()
? CryptoErrorCode::backend_error
: CryptoErrorCode::provider_error;
return std::unexpected{make_openssl_error(
code, "Crypto::verifyEd25519: invalid public key or "
"unavailable provider")};
}
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::verifyEd25519: EVP_MD_CTX_new failed")};
}
if (EVP_DigestVerifyInit_ex(context.get(), nullptr, nullptr,
nullptr, propq, key.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::verifyEd25519: initialization failed")};
}
const int result = EVP_DigestVerify(
context.get(), non_null_bytes(signature), signature.size(),
non_null_bytes(message), message.size());
if (result < 0) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::verifyEd25519 failed")};
}
ERR_clear_error();
return result == 1;
}
} // namespace
void secure_wipe(std::span<std::byte> buffer) noexcept
{
if (!buffer.empty()) {
OPENSSL_cleanse(buffer.data(), buffer.size());
}
}
bool constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
if (lhs.empty()) {
return true;
}
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
}
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
: m_previous(g_fault_config), m_previous_hits(g_fault_hits)
{
g_fault_config = config;
g_fault_hits = 0;
}
ScopedFaultGuard::~ScopedFaultGuard() noexcept
{
g_fault_config = m_previous;
g_fault_hits = m_previous_hits;
}
struct Hasher::Impl {
EVP_MD_CTX* context{nullptr};
const EVP_MD* algorithm{nullptr};
bool finalized{false};
~Impl() { EVP_MD_CTX_free(context); }
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
EvpMdPtr algorithm{nullptr, &EVP_MD_free};
HasherState state{HasherState::Ready};
};
Hasher::Hasher(std::unique_ptr<Impl> impl) noexcept
@@ -53,36 +231,85 @@ namespace Void::Crypto
Hasher::Hasher(Hasher&&) noexcept = default;
Hasher& Hasher::operator=(Hasher&&) noexcept = default;
HasherState Hasher::state() const noexcept
{
return m_impl ? m_impl->state : HasherState::MovedFrom;
}
Void::Result::Result<Hasher> Hasher::create(HashAlgorithm algorithm)
{
return create(algorithm, ProviderOptions{});
}
Void::Result::Result<Hasher>
Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider)
{
const char* md_name = algorithm_name(algorithm);
if (md_name == nullptr) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported algorithm")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_create,
"Crypto::Hasher::create");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
auto impl = std::make_unique<Impl>();
impl->algorithm = algorithm_impl(algorithm);
if (impl->algorithm == nullptr) {
return Void::Result::fail("Crypto::Hasher: unsupported algorithm");
impl->algorithm = EvpMdPtr{
EVP_MD_fetch(nullptr, md_name, propq_or_null(provider)),
&EVP_MD_free};
if (!impl->algorithm) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: EVP_MD_fetch failed")};
}
impl->context = EVP_MD_CTX_new();
if (impl->context == nullptr) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: EVP_MD_CTX_new failed"));
impl->context = EvpMdCtxPtr{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!impl->context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: EVP_MD_CTX_new failed")};
}
if (EVP_DigestInit_ex(impl->context, impl->algorithm, nullptr) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: digest initialization failed"));
if (EVP_DigestInit_ex2(impl->context.get(), impl->algorithm.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: digest initialization failed")};
}
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
}
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::update: hasher is finalized or moved-from");
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::update: hasher is moved-from")};
}
if (m_impl->state == HasherState::Finalized ||
m_impl->state == HasherState::Failed) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::update: hasher is finalized or failed")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_update,
"Crypto::Hasher::update");
fault.has_value()) {
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
if (!data.empty() &&
EVP_DigestUpdate(m_impl->context, data.data(), data.size()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::update failed"));
EVP_DigestUpdate(m_impl->context.get(), data.data(),
data.size()) != 1) {
m_impl->state = HasherState::Failed;
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::update failed")};
}
m_impl->state = HasherState::Updating;
return {};
}
@@ -93,24 +320,41 @@ namespace Void::Crypto
Void::Result::Result<Digest> Hasher::finalize()
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::finalize: hasher is finalized or moved-from");
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::finalize: hasher is moved-from")};
}
const int digest_size = EVP_MD_get_size(m_impl->algorithm);
if (m_impl->state == HasherState::Finalized ||
m_impl->state == HasherState::Failed) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::finalize: hasher is finalized or failed")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_finalize,
"Crypto::Hasher::finalize");
fault.has_value()) {
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
if (digest_size <= 0) {
return Void::Result::fail(
"Crypto::Hasher::finalize: invalid digest size");
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid digest size")};
}
Digest digest(static_cast<std::size_t>(digest_size));
unsigned int written = 0;
if (EVP_DigestFinal_ex(m_impl->context,
if (EVP_DigestFinal_ex(m_impl->context.get(),
reinterpret_cast<unsigned char*>(digest.data()),
&written) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::finalize failed"));
m_impl->state = HasherState::Failed;
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize failed")};
}
m_impl->finalized = true;
m_impl->state = HasherState::Finalized;
digest.resize(written);
return digest;
}
@@ -118,7 +362,13 @@ namespace Void::Crypto
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
-> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm);
return hash(algorithm, data, ProviderOptions{});
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data,
const ProviderOptions& provider) -> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
@@ -137,17 +387,26 @@ namespace Void::Crypto
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hashFile(algorithm, path, ProviderOptions{});
}
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{
std::ifstream input{path, std::ios::binary};
if (!input.is_open()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: cannot open '{}'", path.string()));
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: cannot open '{}'",
path.string()))};
}
auto hasher = Hasher::create(algorithm);
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
std::array<char, 64 * 1024> buffer{};
std::array<char, CryptoLimits::kStreamChunkBytes> buffer{};
while (input) {
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
@@ -160,9 +419,11 @@ namespace Void::Crypto
}
}
}
if (input.bad()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: I/O error reading '{}'", path.string()));
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: I/O error reading '{}'",
path.string()))};
}
return hasher->finalize();
}
@@ -204,54 +465,366 @@ namespace Void::Crypto
return hashFile(HashAlgorithm::Sha512, path);
}
struct Ed25519PrivateKey::Impl {
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
};
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
Ed25519PrivateKey::~Ed25519PrivateKey() = default;
Ed25519PrivateKey::Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept =
default;
Ed25519PrivateKey&
Ed25519PrivateKey::operator=(Ed25519PrivateKey&&) noexcept = default;
bool Ed25519PrivateKey::valid() const noexcept
{
return m_impl != nullptr && m_impl->pkey != nullptr;
}
Void::Result::Result<Ed25519PrivateKey>
Ed25519PrivateKey::generate(const ProviderOptions& provider)
{
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_keygen,
"Crypto::Ed25519PrivateKey::generate");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpPkeyPtr key{
EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"),
&EVP_PKEY_free};
if (!key) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Ed25519PrivateKey::generate failed")};
}
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
}
Void::Result::Result<Ed25519PrivateKey>
Ed25519PrivateKey::from_raw_seed(std::span<const std::byte> seed,
const ProviderOptions& provider)
{
if (seed.size() != Ed25519SeedSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
std::format("Crypto::Ed25519PrivateKey::from_raw_seed: seed "
"must be {} bytes",
Ed25519SeedSize))};
}
if (auto fault = maybe_inject_fault(
FaultOperation::ed25519_import,
"Crypto::Ed25519PrivateKey::from_raw_seed");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex(
nullptr, "ED25519", propq_or_null(provider),
non_null_bytes(seed), seed.size()),
&EVP_PKEY_free};
if (!key) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Ed25519PrivateKey::from_raw_seed failed")};
}
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
}
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
{
if (!valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
"key")};
}
Ed25519PublicKey pub;
std::size_t len = pub.bytes.size();
if (EVP_PKEY_get_raw_public_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(pub.bytes.data()),
&len) != 1 ||
len != Ed25519PublicKeySize) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Ed25519PrivateKey::public_key failed")};
}
return pub;
}
Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const
{
if (!valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Ed25519PrivateKey::export_raw_seed: invalid or "
"moved-from key")};
}
std::array<std::byte, Ed25519SeedSize> raw{};
std::size_t len = raw.size();
if (EVP_PKEY_get_raw_private_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(raw.data()), &len) != 1 ||
len != Ed25519SeedSize) {
secure_wipe(raw);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Ed25519PrivateKey::export_raw_seed failed")};
}
auto result = Ed25519Seed::from_bytes(raw);
secure_wipe(raw);
return result;
}
Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> message,
const Ed25519PrivateKey& private_key,
const ProviderOptions& provider)
{
if (!private_key.valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::sign_ed25519: private key is invalid or moved-from")};
}
if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::sign_ed25519: message exceeds {} byte "
"one-shot limit",
CryptoLimits::kMaxOneShotMessageBytes))};
}
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_sign,
"Crypto::sign_ed25519");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::sign_ed25519: EVP_MD_CTX_new failed")};
}
if (EVP_DigestSignInit_ex(context.get(), nullptr, nullptr, nullptr,
propq_or_null(provider),
private_key.m_impl->pkey.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::sign_ed25519: initialization failed")};
}
Ed25519Signature signature;
std::size_t sig_len = signature.bytes.size();
if (EVP_DigestSign(
context.get(),
reinterpret_cast<unsigned char*>(signature.bytes.data()),
&sig_len, non_null_bytes(message), message.size()) != 1 ||
sig_len != Ed25519SignatureSize) {
secure_wipe(signature.bytes);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::sign_ed25519 failed")};
}
return signature;
}
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte>
signature,
std::span<const std::byte>
publicKey)
{
if (signature.size() != Ed25519SignatureSize) {
return Void::Result::fail(
std::format("Crypto::verifyEd25519: signature must be {} bytes",
Ed25519SignatureSize));
return verify_ed25519_impl(message, signature, publicKey,
ProviderOptions{});
}
Void::Result::Result<bool>
verify_ed25519(std::span<const std::byte> message,
const Ed25519Signature& signature,
const Ed25519PublicKey& public_key,
const ProviderOptions& provider)
{
return verify_ed25519_impl(message, signature.view(), public_key.view(),
provider);
}
Void::Result::Result<void>
hmac_sha256_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider)
{
if (output.size() != HmacSha256Size) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
std::format("Crypto::hmac_sha256_into: output must be {} bytes",
HmacSha256Size))};
}
if (publicKey.size() != Ed25519PublicKeySize) {
return Void::Result::fail(std::format(
"Crypto::verifyEd25519: public key must be {} bytes",
Ed25519PublicKeySize));
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hmac_sha256_into: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hmac,
"Crypto::hmac_sha256_into");
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
}
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
Key key{EVP_PKEY_new_raw_public_key(
EVP_PKEY_ED25519, nullptr,
reinterpret_cast<const unsigned char*>(publicKey.data()),
publicKey.size()),
&EVP_PKEY_free};
if (!key) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: invalid public key"));
ERR_clear_error();
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
&EVP_MAC_free};
if (!mac) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_fetch failed")};
}
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: EVP_MD_CTX_new failed"));
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
if (!ctx) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")};
}
if (EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr,
key.get()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: initialization failed"));
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_end(),
};
if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key),
secret_key.size(), params.data()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_init failed")};
}
const int result = EVP_DigestVerify(
context.get(),
reinterpret_cast<const unsigned char*>(signature.data()),
signature.size(),
reinterpret_cast<const unsigned char*>(message.data()),
message.size());
if (result < 0) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519 failed"));
if (!message.empty() &&
EVP_MAC_update(ctx.get(), non_null_bytes(message),
message.size()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_update failed")};
}
return result == 1;
std::size_t out_len = 0;
if (EVP_MAC_final(ctx.get(),
reinterpret_cast<unsigned char*>(output.data()),
&out_len, output.size()) != 1 ||
out_len != HmacSha256Size) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_final failed")};
}
return {};
}
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider)
{
Digest out(HmacSha256Size);
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
!res.has_value()) {
secure_wipe(out);
return std::unexpected{std::move(res.error())};
}
return out;
}
Void::Result::Result<void>
hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output,
const ProviderOptions& provider)
{
if (secret_output.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"Crypto::hkdf_sha256: output buffer must be non-empty")};
}
if (secret_output.size() > CryptoLimits::kMaxHkdfOutputBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::output_too_large,
std::format("Crypto::hkdf_sha256: output size exceeds {} byte "
"cap",
CryptoLimits::kMaxHkdfOutputBytes))};
}
if (spans_overlap(secret_input, secret_output) ||
spans_overlap(salt, secret_output) ||
spans_overlap(context, secret_output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hkdf_sha256: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hkdf,
"Crypto::hkdf_sha256");
fault.has_value()) {
secure_wipe(secret_output);
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)),
&EVP_KDF_free};
if (!kdf) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hkdf_sha256: EVP_KDF_fetch failed")};
}
EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free};
if (!ctx) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: EVP_KDF_CTX_new failed")};
}
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 5> params = {
OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_KEY,
const_cast<unsigned char*>(non_null_bytes(secret_input)),
secret_input.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_SALT,
const_cast<unsigned char*>(non_null_bytes(salt)), salt.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_INFO,
const_cast<unsigned char*>(non_null_bytes(context)),
context.size()),
OSSL_PARAM_construct_end(),
};
if (EVP_KDF_derive(
ctx.get(),
reinterpret_cast<unsigned char*>(secret_output.data()),
secret_output.size(), params.data()) != 1) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: EVP_KDF_derive failed")};
}
return {};
}
} // namespace Void::Crypto
+2
View File
@@ -1,4 +1,6 @@
void_add_module(Crypto
INTERNAL_DEPS Functional
EXTERNAL_DEPS OpenSSL::Crypto
EXCLUDE_HEADERS
Void/Crypto/AsyncHash.hpp
)
+522
View File
@@ -0,0 +1,522 @@
#include <Void/Crypto/AsyncHash.hpp>
#include <algorithm>
#include <condition_variable>
#include <deque>
#include <format>
#include <fstream>
#include <functional>
#include <mutex>
#include <stop_token>
#include <thread>
#include <vector>
namespace Void::CryptoAsync
{
namespace
{
[[nodiscard]] Void::Result::Error
map_io_error(const Void::Result::Error& err)
{
if (err.kind() == Void::Result::ErrorKind::cancelled) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::cancelled, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::timeout) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::exhausted) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::resource_exhausted,
err.message(), err.system_code());
}
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::io_error, err.message(),
err.system_code());
}
} // namespace
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
hash_stream(Void::Crypto::HashAlgorithm algorithm,
Void::IO::Driver& driver, Void::IO::ByteStream& stream,
Void::Async::OperationOptions options,
StreamHashOptions hash_options)
{
using namespace Void::Crypto;
if (hash_options.chunk_bytes == 0 ||
hash_options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::hash_stream: chunk_bytes must be in [1, 64 KiB]")};
}
if (!stream.valid()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::hash_stream: stream is invalid or closed")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: operation stopped before start")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired before start")};
}
auto hasher = Hasher::create(algorithm, hash_options.provider);
if (!hasher.has_value()) {
co_return std::unexpected{std::move(hasher.error())};
}
auto lease = driver.allocate_buffer(hash_options.chunk_bytes);
if (!lease.has_value()) {
co_return std::unexpected{map_io_error(lease.error())};
}
for (;;) {
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped between chunks")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired between chunks")};
}
auto transfer = co_await stream.read_some_owned(*lease, options);
if (!transfer.has_value()) {
co_return std::unexpected{map_io_error(transfer.error())};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped during stream read")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired after read")};
}
if (transfer->bytes > 0) {
if (auto upd = hasher->update(lease->readable());
!upd.has_value()) {
co_return std::unexpected{std::move(upd.error())};
}
}
if (transfer->eof) {
break;
}
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped before finalize")};
}
co_return hasher->finalize();
}
struct AsyncFileHasher::State : std::enable_shared_from_this<State> {
struct Job {
Job(Void::Crypto::HashAlgorithm alg,
std::filesystem::path p,
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
o)
: algorithm(alg), path(std::move(p)), op(std::move(o))
{
}
Void::Crypto::HashAlgorithm algorithm;
std::filesystem::path path;
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
op;
std::optional<std::stop_callback<std::function<void()>>>
cancel_cb{};
};
State(Void::Async::Executor& exec, FileHasherOptions opts,
const Void::Time::MonotonicClock& clk)
: executor(exec), options(std::move(opts)), clock(clk)
{
}
void start_workers_locked()
{
if (workers_started || options.max_concurrent == 0) {
return;
}
workers_started = true;
const std::size_t count =
std::max<std::size_t>(1, options.max_concurrent);
workers.reserve(count);
auto self = shared_from_this();
for (std::size_t i = 0; i < count; ++i) {
workers.emplace_back([self] { self->worker_loop(); });
}
}
void worker_loop()
{
for (;;) {
std::shared_ptr<Job> job;
{
std::unique_lock lk{mu};
cv.wait(lk, [this] {
if (closing) {
return true;
}
if (queue.empty()) {
return false;
}
if (active < options.max_concurrent &&
reserved_bytes + options.chunk_bytes <=
options.buffer_budget_bytes) {
return true;
}
return std::any_of(
queue.begin(), queue.end(),
[this](const auto& j) {
return j->op->stop_requested() ||
j->op->is_deadline_expired(clock);
});
});
// Purge any already-cancelled or expired jobs in queue.
std::vector<std::pair<std::shared_ptr<Job>,
Void::Result::Error>>
dropped_jobs;
for (auto it = queue.begin(); it != queue.end();) {
auto& item = *it;
if (closing || item->op->stop_requested()) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
closing
? Void::Crypto::CryptoErrorCode::closed
: Void::Crypto::CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: job cancelled while queued"));
it = queue.erase(it);
} else if (item->op->is_deadline_expired(clock)) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired while queued"));
it = queue.erase(it);
} else {
++it;
}
}
if (!dropped_jobs.empty()) {
lk.unlock();
for (auto& [dropped, err] : dropped_jobs) {
dropped->cancel_cb.reset();
const auto kind =
(err.kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
auto ticket = dropped->op->try_commit_error(
std::move(err), kind);
if (ticket.has_value()) {
ticket->dispatch();
}
dropped->op->release_backend_ref_and_dispatch();
}
lk.lock();
}
if (closing && queue.empty()) {
return;
}
if (queue.empty() || active >= options.max_concurrent ||
reserved_bytes + options.chunk_bytes >
options.buffer_budget_bytes) {
continue;
}
job = std::move(queue.front());
queue.pop_front();
++active;
reserved_bytes += options.chunk_bytes;
in_flight.push_back(job->op);
}
job->cancel_cb.reset();
auto result = run_job(*job);
{
std::lock_guard lk{mu};
--active;
reserved_bytes -= options.chunk_bytes;
++completed;
std::erase_if(in_flight, [&](const auto& weak_op) {
auto sp = weak_op.lock();
return !sp || sp == job->op;
});
}
cv.notify_all();
std::optional<Void::Async::ResumeTicket> ticket;
if (result.has_value()) {
ticket = job->op->try_commit_value(std::move(*result));
} else {
const auto kind =
(result.error().kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
ticket = job->op->try_commit_error(
std::move(result.error()), kind);
}
if (ticket.has_value()) {
ticket->dispatch();
}
job->op->release_backend_ref_and_dispatch();
}
}
[[nodiscard]] Void::Result::Result<Void::Crypto::Digest>
run_job(const Job& job) const
{
using namespace Void::Crypto;
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: cancelled before open")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before open")};
}
std::ifstream input{job.path, std::ios::binary};
if (!input.is_open()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: cannot open '{}'",
job.path.string()))};
}
auto hasher = Hasher::create(job.algorithm, options.provider);
if (!hasher.has_value()) {
return std::unexpected{std::move(hasher.error())};
}
std::vector<char> buffer(options.chunk_bytes);
while (input) {
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped during file read")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired during read")};
}
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0) {
const auto bytes = std::as_bytes(std::span{
buffer.data(), static_cast<std::size_t>(count)});
if (auto upd = hasher->update(bytes);
!upd.has_value()) {
return std::unexpected{std::move(upd.error())};
}
}
}
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: I/O error reading '{}'",
job.path.string()))};
}
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before finalize")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before finalize")};
}
return hasher->finalize();
}
Void::Async::Executor& executor;
FileHasherOptions options;
const Void::Time::MonotonicClock& clock;
mutable std::mutex mu{};
std::condition_variable cv{};
std::deque<std::shared_ptr<Job>> queue{};
std::vector<std::weak_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>>
in_flight{};
std::vector<std::thread> workers{};
bool workers_started{false};
bool closing{false};
bool joined{false};
std::size_t active{0};
std::size_t reserved_bytes{0};
std::uint64_t completed{0};
std::uint64_t rejected{0};
};
AsyncFileHasher::AsyncFileHasher(Void::Async::Executor& executor,
FileHasherOptions options,
const Void::Time::MonotonicClock& clock)
: m_state(std::make_shared<State>(executor, std::move(options), clock))
{
}
AsyncFileHasher::~AsyncFileHasher() { (void)close_and_join(); }
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
AsyncFileHasher::hash_file(Void::Crypto::HashAlgorithm algorithm,
std::filesystem::path path,
Void::Async::OperationOptions options)
{
using namespace Void::Crypto;
auto state = m_state;
if (state->options.max_concurrent == 0 ||
state->options.chunk_bytes == 0 ||
state->options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::AsyncFileHasher: invalid options")};
}
if (state->options.chunk_bytes > state->options.buffer_budget_bytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::resource_exhausted,
"CryptoAsync::AsyncFileHasher: chunk_bytes exceeds buffer budget")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before admission")};
}
if (Void::Async::is_deadline_expired(options, state->clock)) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before admission")};
}
auto op = Void::Async::OperationState<Digest>::create(
options, &state->executor, Void::Async::StopBehavior::notify_only);
auto job = std::make_shared<State::Job>(algorithm, std::move(path), op);
{
std::lock_guard lk{state->mu};
if (state->closing) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::AsyncFileHasher: service is closing")};
}
const std::size_t max_effective_concurrent = std::min(
state->options.max_concurrent,
state->options.buffer_budget_bytes / state->options.chunk_bytes);
const std::size_t capacity =
max_effective_concurrent + state->options.max_waiting;
if (state->active + state->queue.size() >= capacity) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::overloaded,
"CryptoAsync::AsyncFileHasher: wait queue is full")};
}
op->acquire_backend_ref();
state->start_workers_locked();
if (options.stop.stop_possible()) {
std::weak_ptr<State> weak_state = state;
job->cancel_cb.emplace(options.stop, [weak_state]() {
if (auto s = weak_state.lock()) {
s->cv.notify_all();
}
});
}
state->queue.push_back(std::move(job));
}
state->cv.notify_one();
co_return co_await op->awaitable(&state->executor);
}
void AsyncFileHasher::request_stop() noexcept
{
std::vector<
std::shared_ptr<Void::Async::OperationState<Void::Crypto::Digest>>>
ops;
{
std::lock_guard lk{m_state->mu};
m_state->closing = true;
for (const auto& j : m_state->queue) {
ops.push_back(j->op);
}
for (const auto& weak_op : m_state->in_flight) {
if (auto sp = weak_op.lock()) {
ops.push_back(std::move(sp));
}
}
}
for (auto& op : ops) {
op->request_stop();
}
m_state->cv.notify_all();
}
Void::Result::Result<void> AsyncFileHasher::close_and_join()
{
request_stop();
std::vector<std::thread> threads;
{
std::lock_guard lk{m_state->mu};
if (m_state->joined) {
return {};
}
m_state->joined = true;
threads.swap(m_state->workers);
}
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
return {};
}
FileHasherStats AsyncFileHasher::stats() const noexcept
{
std::lock_guard lk{m_state->mu};
return FileHasherStats{
.active = m_state->active,
.waiting = m_state->queue.size(),
.reserved_buffer_bytes = m_state->reserved_bytes,
.completed = m_state->completed,
.rejected = m_state->rejected,
.closing = m_state->closing,
};
}
} // namespace Void::CryptoAsync
+6
View File
@@ -0,0 +1,6 @@
void_add_module(CryptoAsync
INTERNAL_DEPS Crypto IO Async Time Functional
EXTERNAL_DEPS Threads::Threads
EXTRA_HEADERS
Void/Crypto/AsyncHash.hpp
)
+55
View File
@@ -14,6 +14,7 @@
#ifdef __linux__
#include <fcntl.h>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/socket.h>
@@ -30,6 +31,55 @@ namespace
return std::error_code{err, std::generic_category()};
}
#ifdef __linux__
[[nodiscard]] ssize_t write_pipe_nosigpipe(
int fd, const void* buf, std::size_t len, int& out_errno) noexcept
{
sigset_t pending{};
::sigemptyset(&pending);
::sigpending(&pending);
const bool was_pending = (::sigismember(&pending, SIGPIPE) == 1);
sigset_t block{};
::sigemptyset(&block);
::sigaddset(&block, SIGPIPE);
sigset_t old_mask{};
const int mask_rc = ::pthread_sigmask(SIG_BLOCK, &block, &old_mask);
const bool was_blocked =
(mask_rc == 0) && (::sigismember(&old_mask, SIGPIPE) == 1);
ssize_t n = -1;
out_errno = 0;
for (;;) {
n = ::write(fd, buf, len);
if (n < 0) {
out_errno = errno;
if (out_errno == EINTR) {
continue;
}
}
break;
}
if (n < 0 && out_errno == EPIPE && !was_pending && !was_blocked) {
const struct timespec zero_wait{0, 0};
for (;;) {
if (::sigtimedwait(&block, nullptr, &zero_wait) >= 0) {
break;
}
if (errno != EINTR) {
break;
}
}
}
if (mask_rc == 0 && !was_blocked) {
(void)::pthread_sigmask(SIG_SETMASK, &old_mask, nullptr);
}
return n;
}
#endif
void dispatch_tickets(std::vector<Async::ResumeTicket>& tickets)
{
for (auto& t : tickets) {
@@ -1503,6 +1553,10 @@ private:
continue;
}
if (saved_errno == ENOTSOCK) {
#ifdef __linux__
n = write_pipe_nosigpipe(
fd, op->write_ptr, to_write, saved_errno);
#else
n = ::write(fd, op->write_ptr, to_write);
if (n < 0) {
saved_errno = errno;
@@ -1510,6 +1564,7 @@ private:
continue;
}
}
#endif
}
}
break;
+602
View File
@@ -0,0 +1,602 @@
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/IPC/Codec.hpp>
#include <algorithm>
#include <array>
#include <bit>
#include <cstring>
#include <expected>
#include <format>
#include <limits>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
namespace Void::IPC
{
namespace
{
constexpr std::array<std::byte, 4> kMagicBytes{
std::byte{'V'}, std::byte{'D'}, std::byte{'I'}, std::byte{'P'}};
[[nodiscard]] bool is_valid_frame_type(std::uint8_t raw) noexcept
{
return raw >= static_cast<std::uint8_t>(FrameType::hello) &&
raw <= static_cast<std::uint8_t>(FrameType::goaway);
}
[[nodiscard]] bool is_valid_error_code(std::int32_t raw) noexcept
{
return raw >= static_cast<std::int32_t>(IpcErrorCode::invalid_argument) &&
raw <= static_cast<std::int32_t>(IpcErrorCode::internal);
}
} // namespace
QuotaPermit::~QuotaPermit() noexcept { reset(); }
QuotaPermit::QuotaPermit(QuotaPermit&& other) noexcept
: quota_(std::move(other.quota_)),
bytes_(std::exchange(other.bytes_, 0))
{
}
QuotaPermit& QuotaPermit::operator=(QuotaPermit&& other) noexcept
{
if (this != &other) {
reset();
quota_ = std::move(other.quota_);
bytes_ = std::exchange(other.bytes_, 0);
}
return *this;
}
void QuotaPermit::reset() noexcept
{
const std::size_t rel = std::exchange(bytes_, 0);
if (rel > 0) {
if (auto q = quota_.lock()) {
q->release(rel);
}
}
quota_.reset();
}
BufferQuota::BufferQuota(std::size_t capacity_bytes) : capacity_(capacity_bytes)
{
}
std::shared_ptr<BufferQuota> BufferQuota::create(std::size_t capacity_bytes)
{
return std::make_shared<BufferQuota>(capacity_bytes);
}
Void::Result::Result<QuotaPermit, Void::Result::Error>
BufferQuota::reserve(std::size_t bytes)
{
std::lock_guard lk{mu_};
if (bytes > capacity_ || used_ > capacity_ - bytes) {
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded,
std::format(
"IPC buffer quota exceeded (requested {}, used {}/{})",
bytes,
used_,
capacity_))};
}
used_ += bytes;
QuotaPermit permit;
permit.quota_ = weak_from_this();
permit.bytes_ = bytes;
return permit;
}
void BufferQuota::release(std::size_t bytes) noexcept
{
std::lock_guard lk{mu_};
used_ = (used_ >= bytes) ? (used_ - bytes) : 0;
}
std::size_t BufferQuota::used() const noexcept
{
std::lock_guard lk{mu_};
return used_;
}
Void::Result::Result<void, Void::Result::Error>
validate_frame_header(const FrameHeader& header, const IpcLimits& limits)
{
if (header.version != kWireVersion) {
return std::unexpected{make_ipc_error(
IpcErrorCode::unsupported_version,
std::format("Unsupported IPC wire version {}", header.version))};
}
if (header.flags != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format("Unsupported non-zero IPC flags {:#x}", header.flags))};
}
if (!is_valid_frame_type(static_cast<std::uint8_t>(header.type))) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format(
"Unknown IPC frame type {}",
static_cast<unsigned>(header.type)))};
}
if (header.stream_id != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format(
"IPC V1 requires stream_id == 0 (got {})", header.stream_id))};
}
if (header.payload_len > limits.max_frame_payload) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
std::format(
"IPC frame payload_len {} exceeds max_frame_payload {}",
header.payload_len,
limits.max_frame_payload))};
}
if (header.type == FrameType::hello &&
header.payload_len > limits.max_hello_bytes) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
std::format(
"IPC hello payload_len {} exceeds max_hello_bytes {}",
header.payload_len,
limits.max_hello_bytes))};
}
switch (header.type) {
case FrameType::request:
case FrameType::response:
case FrameType::cancel:
if (header.request_id == 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
"IPC request/response/cancel frame requires nonzero request_id")};
}
break;
case FrameType::hello:
case FrameType::one_way:
case FrameType::goaway:
if (header.request_id != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
"IPC hello/one_way/goaway frame requires request_id == 0")};
}
break;
case FrameType::error:
break;
}
return {};
}
Void::Result::Result<void, Void::Result::Error> encode_frame_header(
const FrameHeader& header, std::span<std::byte, kFrameHeaderSize> out)
{
Void::Binary::Writer w{out};
if (auto r = w.writeBytes(kMagicBytes); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint16_t>(header.version); !r) {
return std::unexpected{std::move(r.error())};
}
const std::uint16_t flags_type =
static_cast<std::uint16_t>((static_cast<std::uint16_t>(header.flags) << 8) |
static_cast<std::uint8_t>(header.type));
if (auto r = w.writeBig<std::uint16_t>(flags_type); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint32_t>(header.payload_len); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint32_t>(header.stream_id); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = w.writeBig<std::uint64_t>(header.request_id); !r) {
return std::unexpected{std::move(r.error())};
}
return {};
}
Void::Result::Result<FrameHeader, Void::Result::Error>
decode_frame_header(std::span<const std::byte, kFrameHeaderSize> in)
{
Void::Binary::Reader r{in};
auto magic = r.readBytes(4);
if (!magic || !std::equal(magic->begin(), magic->end(), kMagicBytes.begin())) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Invalid IPC wire magic (expected VDIP)")};
}
auto ver = r.read<std::uint16_t>(std::endian::big);
auto flags_type = r.read<std::uint16_t>(std::endian::big);
auto plen = r.read<std::uint32_t>(std::endian::big);
auto sid = r.read<std::uint32_t>(std::endian::big);
auto rid = r.read<std::uint64_t>(std::endian::big);
if (!ver || !flags_type || !plen || !sid || !rid) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Truncated IPC frame header")};
}
const auto raw_flags = static_cast<std::uint8_t>((*flags_type >> 8) & 0xffu);
const auto raw_type = static_cast<std::uint8_t>(*flags_type & 0xffu);
if (!is_valid_frame_type(raw_type)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
std::format("Invalid IPC frame type byte {}", raw_type))};
}
FrameHeader hdr;
hdr.version = *ver;
hdr.flags = raw_flags;
hdr.type = static_cast<FrameType>(raw_type);
hdr.payload_len = *plen;
hdr.stream_id = *sid;
hdr.request_id = *rid;
return hdr;
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error> encode_frame(
const FrameHeader& header,
std::span<const std::byte> payload,
const IpcLimits& limits,
std::pmr::memory_resource* mr)
{
if (payload.size() > std::numeric_limits<std::uint32_t>::max()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
"IPC payload exceeds uint32_t length field")};
}
FrameHeader effective = header;
effective.payload_len = static_cast<std::uint32_t>(payload.size());
if (auto v = validate_frame_header(effective, limits); !v) {
return std::unexpected{std::move(v.error())};
}
std::array<std::byte, kFrameHeaderSize> hdr_bytes{};
if (auto e = encode_frame_header(effective, hdr_bytes); !e) {
return std::unexpected{std::move(e.error())};
}
Void::Binary::ByteBuffer buf{kFrameHeaderSize + payload.size(), mr};
if (auto r = buf.reserve(kFrameHeaderSize + payload.size()); !r) {
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded, r.error().message())};
}
if (auto r = buf.append(hdr_bytes); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.append(payload); !r) {
return std::unexpected{std::move(r.error())};
}
return buf.freeze();
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_hello(const HelloInfo& info, std::pmr::memory_resource* mr)
{
if (info.protocol_id.empty() || info.protocol_id.size() > 256) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"HelloInfo protocol_id must be 1..256 bytes")};
}
const std::size_t total = 4 + info.protocol_id.size() + 20;
Void::Binary::ByteBuffer buf{total, mr};
if (auto r = buf.reserve(total); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(info.protocol_id.size()));
!r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeString(info.protocol_id); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.protocol_version); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.capabilities); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.max_frame_payload); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.max_inflight_requests); !r) {
return std::unexpected{std::move(r.error())};
}
if (auto r = buf.writeBig<std::uint32_t>(info.max_active_handlers); !r) {
return std::unexpected{std::move(r.error())};
}
return buf.freeze();
}
Void::Result::Result<HelloInfo, Void::Result::Error> decode_hello(
std::span<const std::byte> payload, std::size_t max_bytes)
{
if (payload.size() > max_bytes) {
return std::unexpected{make_ipc_error(
IpcErrorCode::frame_too_large,
"Hello payload exceeds max_hello_bytes")};
}
Void::Binary::Reader r{payload};
auto pid_len = r.read<std::uint32_t>(std::endian::big);
if (!pid_len || *pid_len == 0 || *pid_len > 256) {
return std::unexpected{make_ipc_error(
IpcErrorCode::handshake_failed, "Invalid hello protocol_id length")};
}
auto pid_bytes = r.readBytes(*pid_len);
auto pver = r.read<std::uint32_t>(std::endian::big);
auto caps = r.read<std::uint32_t>(std::endian::big);
auto max_frame = r.read<std::uint32_t>(std::endian::big);
auto max_inf = r.read<std::uint32_t>(std::endian::big);
auto max_hdl = r.read<std::uint32_t>(std::endian::big);
if (!pid_bytes || !pver || !caps || !max_frame || !max_inf || !max_hdl ||
!r.empty()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::handshake_failed, "Malformed IPC hello payload")};
}
if (*max_frame == 0 || *max_inf == 0 || *max_hdl == 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::handshake_failed,
"Hello limits must be strictly positive")};
}
HelloInfo out;
out.protocol_id.assign(
reinterpret_cast<const char*>(pid_bytes->data()), pid_bytes->size());
out.protocol_version = *pver;
out.capabilities = *caps;
out.max_frame_payload = *max_frame;
out.max_inflight_requests = *max_inf;
out.max_active_handlers = *max_hdl;
return out;
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_error_payload(IpcErrorCode code,
std::string_view message,
std::pmr::memory_resource* mr)
{
const std::string_view bounded =
message.substr(0, std::min<std::size_t>(message.size(), 512));
const std::size_t total = 8 + bounded.size();
Void::Binary::ByteBuffer buf{total, mr};
if (auto r = buf.reserve(total); !r) {
return std::unexpected{std::move(r.error())};
}
(void)buf.writeBig<std::int32_t>(static_cast<std::int32_t>(code));
(void)buf.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(bounded.size()));
(void)buf.writeString(bounded);
return buf.freeze();
}
Void::Result::Result<std::pair<IpcErrorCode, std::string>, Void::Result::Error>
decode_error_payload(std::span<const std::byte> payload)
{
Void::Binary::Reader r{payload};
auto raw_code = r.read<std::int32_t>(std::endian::big);
auto mlen = r.read<std::uint32_t>(std::endian::big);
if (!raw_code || !mlen || *mlen > r.remaining()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Malformed IPC error payload")};
}
auto msg_bytes = r.readBytes(*mlen);
if (!msg_bytes || !r.empty()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Truncated IPC error payload")};
}
const auto code = is_valid_error_code(*raw_code)
? static_cast<IpcErrorCode>(*raw_code)
: IpcErrorCode::peer_error;
std::string msg{reinterpret_cast<const char*>(msg_bytes->data()),
msg_bytes->size()};
return std::pair<IpcErrorCode, std::string>{code, std::move(msg)};
}
Void::Result::Result<Void::Binary::FrozenBytes, Void::Result::Error>
encode_goaway_payload(IpcErrorCode code,
std::uint64_t last_request_id,
std::string_view reason,
std::pmr::memory_resource* mr)
{
const std::string_view bounded =
reason.substr(0, std::min<std::size_t>(reason.size(), 512));
const std::size_t total = 16 + bounded.size();
Void::Binary::ByteBuffer buf{total, mr};
if (auto r = buf.reserve(total); !r) {
return std::unexpected{std::move(r.error())};
}
(void)buf.writeBig<std::int32_t>(static_cast<std::int32_t>(code));
(void)buf.writeBig<std::uint64_t>(last_request_id);
(void)buf.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(bounded.size()));
(void)buf.writeString(bounded);
return buf.freeze();
}
Void::Result::Result<
std::tuple<IpcErrorCode, std::uint64_t, std::string>,
Void::Result::Error>
decode_goaway_payload(std::span<const std::byte> payload)
{
Void::Binary::Reader r{payload};
auto raw_code = r.read<std::int32_t>(std::endian::big);
auto last_id = r.read<std::uint64_t>(std::endian::big);
auto rlen = r.read<std::uint32_t>(std::endian::big);
if (!raw_code || !last_id || !rlen || *rlen > r.remaining()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Malformed IPC goaway payload")};
}
auto msg_bytes = r.readBytes(*rlen);
if (!msg_bytes || !r.empty()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame, "Truncated IPC goaway payload")};
}
const auto code = is_valid_error_code(*raw_code)
? static_cast<IpcErrorCode>(*raw_code)
: IpcErrorCode::closed;
std::string reason{reinterpret_cast<const char*>(msg_bytes->data()),
msg_bytes->size()};
return std::tuple<IpcErrorCode, std::uint64_t, std::string>{
code, *last_id, std::move(reason)};
}
FrameDecoder::FrameDecoder(IpcLimits limits,
std::shared_ptr<BufferQuota> global_quota,
std::shared_ptr<BufferQuota> session_quota,
std::pmr::memory_resource* mr)
: limits_(limits),
global_quota_(std::move(global_quota)),
session_quota_(std::move(session_quota)),
mr_(mr ? mr : std::pmr::get_default_resource())
{
}
void FrameDecoder::reset_frame_state() noexcept
{
header_len_ = 0;
has_header_ = false;
current_header_ = FrameHeader{};
current_global_permit_.reset();
current_session_permit_.reset();
payload_buf_.reset();
payload_written_ = 0;
state_ = State::reading_header;
}
Void::Result::Result<std::vector<DecodedFrame>, Void::Result::Error>
FrameDecoder::feed(std::span<const std::byte> chunk)
{
if (state_ == State::failed) {
return std::unexpected{make_ipc_error(
IpcErrorCode::corrupt_frame,
"FrameDecoder is poisoned after prior frame error")};
}
std::vector<DecodedFrame> frames;
std::size_t off = 0;
while (off < chunk.size()) {
if (state_ == State::reading_header) {
const std::size_t need = kFrameHeaderSize - header_len_;
const std::size_t take = std::min(need, chunk.size() - off);
std::memcpy(header_buf_.data() + header_len_,
chunk.data() + off,
take);
header_len_ += take;
off += take;
if (header_len_ < kFrameHeaderSize) {
break;
}
auto hdr_res = decode_frame_header(header_buf_);
if (!hdr_res.has_value()) {
state_ = State::failed;
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(hdr_res.error())};
}
if (auto v = validate_frame_header(*hdr_res, limits_); !v.has_value()) {
state_ = State::failed;
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(v.error())};
}
const std::size_t quota_cost = frame_quota_cost(hdr_res->payload_len);
if (quota_cost > limits_.max_recv_buffer_bytes) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded,
"IPC frame exceeds max_recv_buffer_bytes")};
}
// Reserve global + per-session permits BEFORE allocating payload buffer!
QuotaPermit g_perm;
QuotaPermit s_perm;
if (global_quota_) {
auto gr = global_quota_->reserve(quota_cost);
if (!gr.has_value()) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(gr.error())};
}
g_perm = std::move(*gr);
}
if (session_quota_) {
auto sr = session_quota_->reserve(quota_cost);
if (!sr.has_value()) {
g_perm.reset();
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(sr.error())};
}
s_perm = std::move(*sr);
}
current_header_ = *hdr_res;
current_global_permit_ = std::move(g_perm);
current_session_permit_ = std::move(s_perm);
has_header_ = true;
if (current_header_.payload_len == 0) {
DecodedFrame df;
df.header = current_header_;
df.global_permit = std::move(current_global_permit_);
df.session_permit = std::move(current_session_permit_);
frames.push_back(std::move(df));
reset_frame_state();
continue;
}
payload_buf_.emplace(current_header_.payload_len, mr_);
if (auto rr = payload_buf_->reserve(current_header_.payload_len);
!rr.has_value()) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{make_ipc_error(
IpcErrorCode::quota_exceeded, rr.error().message())};
}
payload_written_ = 0;
state_ = State::reading_payload;
}
if (state_ == State::reading_payload) {
const std::size_t rem_payload =
current_header_.payload_len - payload_written_;
const std::size_t take = std::min(rem_payload, chunk.size() - off);
if (auto ar = payload_buf_->append(chunk.subspan(off, take));
!ar.has_value()) {
reset_frame_state();
state_ = State::failed;
return std::unexpected{std::move(ar.error())};
}
payload_written_ += take;
off += take;
if (payload_written_ == current_header_.payload_len) {
DecodedFrame df;
df.header = current_header_;
df.payload = payload_buf_->freeze();
df.global_permit = std::move(current_global_permit_);
df.session_permit = std::move(current_session_permit_);
frames.push_back(std::move(df));
reset_frame_state();
}
}
}
return frames;
}
} // namespace Void::IPC
+1550
View File
File diff suppressed because it is too large. Load diff
+673
View File
@@ -0,0 +1,673 @@
#include <Void/IPC/Transport.hpp>
#include <fcntl.h>
#include <poll.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
#include <atomic>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <expected>
#include <filesystem>
#include <format>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace Void::IPC
{
namespace
{
[[nodiscard]] IpcErrorCode map_errno_to_ipc(int err) noexcept
{
switch (err) {
case ENOENT:
return IpcErrorCode::not_found;
case EACCES:
case EPERM:
case ELOOP:
return IpcErrorCode::permission_denied;
case EEXIST:
return IpcErrorCode::already_exists;
case EINVAL:
case ENAMETOOLONG:
case ENOTDIR:
case EISDIR:
return IpcErrorCode::invalid_argument;
case ETIMEDOUT:
return IpcErrorCode::timed_out;
case ECONNREFUSED:
case ECONNRESET:
case EPIPE:
case ENOTCONN:
return IpcErrorCode::transport_lost;
case EAGAIN:
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
return IpcErrorCode::overloaded;
default:
return IpcErrorCode::transport_lost;
}
}
[[nodiscard]] Void::Result::Result<PeerCredentials, Void::Result::Error>
query_peer_credentials(int fd)
{
struct ucred cred{};
socklen_t len = sizeof(cred);
if (::getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to query SO_PEERCRED", err)};
}
PeerCredentials out;
out.available = true;
out.pid = static_cast<long long>(cred.pid);
out.uid = static_cast<unsigned long>(cred.uid);
out.gid = static_cast<unsigned long>(cred.gid);
return out;
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
check_peer_policy(const PeerCredentials& creds, const PeerPolicy& policy)
{
if (!creds.available) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Peer credentials unavailable for SO_PEERCRED check")};
}
if (policy.require_uid_match) {
const unsigned long expected_uid =
policy.set_allowed_uid_to_current_user
? static_cast<unsigned long>(::geteuid())
: policy.allowed_uid;
if (creds.uid != expected_uid) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
std::format("Peer UID {} denied (expected {})",
creds.uid,
expected_uid))};
}
}
if (policy.required_gid.has_value() && creds.gid != *policy.required_gid) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
std::format("Peer GID {} denied (expected {})",
creds.gid,
*policy.required_gid))};
}
return {};
}
[[nodiscard]] Void::Result::Result<sockaddr_un, Void::Result::Error>
build_sockaddr(const std::filesystem::path& socket_path,
socklen_t& out_len)
{
const std::string& raw = socket_path.native();
if (raw.empty() || raw.find('\0') != std::string::npos) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"IPC socket path must be non-empty without NUL bytes")};
}
sockaddr_un addr{};
if (raw.size() >= sizeof(addr.sun_path)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
std::format("IPC socket path length {} >= sun_path limit ({})",
raw.size(),
sizeof(addr.sun_path)))};
}
addr.sun_family = AF_UNIX;
std::memcpy(addr.sun_path, raw.data(), raw.size());
addr.sun_path[raw.size()] = '\0';
out_len = static_cast<socklen_t>(
offsetof(sockaddr_un, sun_path) + raw.size() + 1);
return addr;
}
[[nodiscard]] bool probe_socket_alive(const sockaddr_un& addr,
socklen_t addr_len,
int& out_errno) noexcept
{
const int probe =
::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (probe < 0) {
out_errno = errno;
return false;
}
const int rc =
::connect(probe, reinterpret_cast<const sockaddr*>(&addr), addr_len);
out_errno = (rc == 0) ? 0 : errno;
(void)::close(probe);
return rc == 0 || out_errno == EINPROGRESS || out_errno == EAGAIN;
}
} // namespace
struct LocalListener::SlotState {
std::size_t max_sessions{128};
mutable std::mutex mu{};
std::size_t active{0};
};
namespace
{
struct ListenerSlotGuard {
std::weak_ptr<LocalListener::SlotState> state;
~ListenerSlotGuard() noexcept
{
if (auto p = state.lock()) {
std::lock_guard lk{p->mu};
if (p->active > 0) {
--p->active;
}
}
}
};
} // namespace
DuplexTransport::DuplexTransport(Void::IO::ByteStream unified_stream,
PeerCredentials creds) noexcept
: split_(false),
read_stream_(std::move(unified_stream)),
credentials_(creds)
{
}
DuplexTransport::DuplexTransport(Void::IO::ByteStream read_stream,
Void::IO::ByteStream write_stream,
PeerCredentials creds) noexcept
: split_(true),
read_stream_(std::move(read_stream)),
write_stream_(std::move(write_stream)),
credentials_(creds)
{
}
bool DuplexTransport::valid() const noexcept
{
return split_ ? (read_stream_.valid() && write_stream_.valid())
: read_stream_.valid();
}
Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
DuplexTransport::close_and_join(Void::Async::OperationOptions options)
{
if (!split_) {
if (read_stream_.valid()) {
auto r = co_await read_stream_.close_and_join(options);
listener_slot_.reset();
co_return r;
}
listener_slot_.reset();
co_return {};
}
Void::Result::Result<void, Void::Result::Error> first_err;
if (write_stream_.valid()) {
auto w = co_await write_stream_.close_and_join(options);
if (!w.has_value()) {
first_err = std::move(w);
}
}
if (read_stream_.valid()) {
auto r = co_await read_stream_.close_and_join(options);
if (!r.has_value() && first_err.has_value()) {
first_err = std::move(r);
}
}
listener_slot_.reset();
co_return first_err;
}
LocalListener::~LocalListener() noexcept { close(); }
LocalListener::LocalListener(LocalListener&& other) noexcept
: listen_fd_(std::exchange(other.listen_fd_, -1)),
dir_fd_(std::exchange(other.dir_fd_, -1)),
lock_fd_(std::exchange(other.lock_fd_, -1)),
socket_path_(std::move(other.socket_path_)),
socket_name_(std::move(other.socket_name_)),
socket_dev_(std::exchange(other.socket_dev_, 0)),
socket_ino_(std::exchange(other.socket_ino_, 0)),
limits_(other.limits_),
policy_(other.policy_),
slot_state_(std::move(other.slot_state_))
{
}
LocalListener& LocalListener::operator=(LocalListener&& other) noexcept
{
if (this != &other) {
close();
listen_fd_ = std::exchange(other.listen_fd_, -1);
dir_fd_ = std::exchange(other.dir_fd_, -1);
lock_fd_ = std::exchange(other.lock_fd_, -1);
socket_path_ = std::move(other.socket_path_);
socket_name_ = std::move(other.socket_name_);
socket_dev_ = std::exchange(other.socket_dev_, 0);
socket_ino_ = std::exchange(other.socket_ino_, 0);
limits_ = other.limits_;
policy_ = other.policy_;
slot_state_ = std::move(other.slot_state_);
}
return *this;
}
void LocalListener::close() noexcept
{
if (listen_fd_ >= 0) {
(void)::close(listen_fd_);
listen_fd_ = -1;
}
if (dir_fd_ >= 0 && !socket_name_.empty() && socket_ino_ != 0) {
struct stat st {};
if (::fstatat(dir_fd_,
socket_name_.c_str(),
&st,
AT_SYMLINK_NOFOLLOW) == 0 &&
S_ISSOCK(st.st_mode) &&
static_cast<std::uint64_t>(st.st_dev) == socket_dev_ &&
static_cast<std::uint64_t>(st.st_ino) == socket_ino_) {
(void)::unlinkat(dir_fd_, socket_name_.c_str(), 0);
}
}
if (dir_fd_ >= 0 && !socket_name_.empty() && lock_fd_ >= 0) {
const std::string lock_name = socket_name_ + ".lock";
(void)::unlinkat(dir_fd_, lock_name.c_str(), 0);
}
if (lock_fd_ >= 0) {
(void)::close(lock_fd_);
lock_fd_ = -1;
}
if (dir_fd_ >= 0) {
(void)::close(dir_fd_);
dir_fd_ = -1;
}
socket_name_.clear();
socket_dev_ = 0;
socket_ino_ = 0;
}
std::size_t LocalListener::active_sessions() const noexcept
{
if (!slot_state_) {
return 0;
}
std::lock_guard lk{slot_state_->mu};
return slot_state_->active;
}
Void::Result::Result<LocalListener, Void::Result::Error> LocalListener::listen(
const std::filesystem::path& socket_path,
IpcLimits limits,
PeerPolicy policy)
{
if (limits.max_sessions == 0 || limits.max_frame_payload == 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"IpcLimits max_sessions and max_frame_payload must be non-zero")};
}
socklen_t addr_len = 0;
auto addr_res = build_sockaddr(socket_path, addr_len);
if (!addr_res.has_value()) {
return std::unexpected{std::move(addr_res.error())};
}
const std::string fname = socket_path.filename().string();
if (fname.empty() || fname == "." || fname == "..") {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"LocalListener socket path must have a valid filename")};
}
const std::filesystem::path parent =
socket_path.parent_path().empty() ? std::filesystem::path{"."}
: socket_path.parent_path();
const int raw_dir_fd = ::open(
parent.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (raw_dir_fd < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Cannot safely open IPC socket parent dir '{}'",
parent.string()),
err)};
}
LocalListener listener;
listener.dir_fd_ = raw_dir_fd;
listener.socket_path_ = socket_path;
listener.socket_name_ = fname;
listener.limits_ = limits;
listener.policy_ = policy;
struct stat dir_st {};
if (::fstat(listener.dir_fd_, &dir_st) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to stat IPC socket parent dir", err)};
}
if (dir_st.st_uid != ::geteuid() || (dir_st.st_mode & 0077) != 0) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
std::format(
"IPC socket parent dir '{}' must be owned by current user with 0700 permissions",
parent.string()))};
}
const std::string lock_name = fname + ".lock";
listener.lock_fd_ = ::openat(listener.dir_fd_,
lock_name.c_str(),
O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC,
0600);
if (listener.lock_fd_ < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
"Failed to open IPC startup lock file",
err)};
}
if (::flock(listener.lock_fd_, LOCK_EX | LOCK_NB) != 0) {
const int err = errno;
(void)::close(listener.lock_fd_);
listener.lock_fd_ = -1;
return std::unexpected{make_ipc_error(
IpcErrorCode::already_exists,
"Another listener holds the startup lock for this socket",
err)};
}
struct stat existing_st {};
if (::fstatat(listener.dir_fd_,
fname.c_str(),
&existing_st,
AT_SYMLINK_NOFOLLOW) == 0) {
if (!S_ISSOCK(existing_st.st_mode) ||
existing_st.st_uid != ::geteuid()) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Refusing to remove non-socket, symlink, or foreign path at IPC endpoint")};
}
int probe_err = 0;
if (probe_socket_alive(*addr_res, addr_len, probe_err)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::already_exists,
"IPC socket endpoint is already active")};
}
if (probe_err != ECONNREFUSED) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Failed to confirm stale state before unlinking existing socket",
probe_err)};
}
if (::unlinkat(listener.dir_fd_, fname.c_str(), 0) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to remove stale IPC socket", err)};
}
} else if (errno != ENOENT) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to inspect IPC socket path", err)};
}
listener.listen_fd_ =
::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (listener.listen_fd_ < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to create AF_UNIX socket", err)};
}
if (::bind(listener.listen_fd_,
reinterpret_cast<const sockaddr*>(&*addr_res),
addr_len) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Failed to bind AF_UNIX socket '{}'",
socket_path.string()),
err)};
}
struct stat bound_st {};
if (::fstatat(listener.dir_fd_,
fname.c_str(),
&bound_st,
AT_SYMLINK_NOFOLLOW) != 0 ||
!S_ISSOCK(bound_st.st_mode)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"Bound IPC endpoint missing or replaced unexpectedly")};
}
listener.socket_dev_ = static_cast<std::uint64_t>(bound_st.st_dev);
listener.socket_ino_ = static_cast<std::uint64_t>(bound_st.st_ino);
if (::chmod(socket_path.c_str(), 0600) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to set 0600 mode on IPC socket", err)};
}
if (::listen(listener.listen_fd_, 128) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to listen on AF_UNIX socket", err)};
}
listener.slot_state_ = std::make_shared<SlotState>();
listener.slot_state_->max_sessions = limits.max_sessions;
return listener;
}
Void::Result::Result<std::optional<DuplexTransport>, Void::Result::Error>
LocalListener::try_accept(Void::IO::Driver& driver)
{
if (listen_fd_ < 0 || !slot_state_) {
return std::unexpected{make_ipc_error(
IpcErrorCode::closed, "LocalListener is closed")};
}
for (;;) {
const int client_fd =
::accept4(listen_fd_, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (client_fd < 0) {
const int err = errno;
if (err == EINTR) {
continue;
}
if (err == EAGAIN || err == EWOULDBLOCK) {
return std::optional<DuplexTransport>{std::nullopt};
}
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "accept4 failed on IPC listener", err)};
}
std::shared_ptr<ListenerSlotGuard> slot_guard;
{
std::lock_guard lk{slot_state_->mu};
if (slot_state_->active >= slot_state_->max_sessions) {
(void)::close(client_fd);
return std::unexpected{make_ipc_error(
IpcErrorCode::overloaded,
std::format("LocalListener max_sessions ({}) reached",
slot_state_->max_sessions))};
}
++slot_state_->active;
slot_guard = std::make_shared<ListenerSlotGuard>(slot_state_);
}
auto creds = query_peer_credentials(client_fd);
if (!creds.has_value()) {
(void)::close(client_fd);
return std::unexpected{std::move(creds.error())};
}
if (auto auth = check_peer_policy(*creds, policy_); !auth.has_value()) {
(void)::close(client_fd);
return std::unexpected{std::move(auth.error())};
}
auto stream = driver.adopt_fd(client_fd);
if (!stream.has_value()) {
(void)::close(client_fd);
return std::unexpected{std::move(stream.error())};
}
DuplexTransport transport{std::move(*stream), *creds};
transport.listener_slot_ = std::move(slot_guard);
return std::optional<DuplexTransport>{std::move(transport)};
}
}
Void::Result::Result<DuplexTransport, Void::Result::Error> connect_local(
Void::IO::Driver& driver,
const std::filesystem::path& socket_path,
PeerPolicy policy)
{
socklen_t addr_len = 0;
auto addr_res = build_sockaddr(socket_path, addr_len);
if (!addr_res.has_value()) {
return std::unexpected{std::move(addr_res.error())};
}
struct stat st {};
if (::lstat(socket_path.c_str(), &st) != 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Cannot stat IPC socket '{}'", socket_path.string()),
err)};
}
if (S_ISLNK(st.st_mode) || !S_ISSOCK(st.st_mode)) {
return std::unexpected{make_ipc_error(
IpcErrorCode::permission_denied,
"IPC connect target must be a real AF_UNIX socket, not a symlink")};
}
const int fd =
::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0) {
const int err = errno;
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err), "Failed to create AF_UNIX client socket", err)};
}
for (;;) {
if (::connect(fd, reinterpret_cast<const sockaddr*>(&*addr_res), addr_len) ==
0) {
break;
}
const int err = errno;
if (err == EINTR) {
continue;
}
if (err == EINPROGRESS) {
struct pollfd pfd{fd, POLLOUT, 0};
const int prc = ::poll(&pfd, 1, 5000);
if (prc <= 0) {
(void)::close(fd);
return std::unexpected{make_ipc_error(
IpcErrorCode::timed_out,
"Timed out connecting to AF_UNIX socket")};
}
int so_err = 0;
socklen_t slen = sizeof(so_err);
if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 ||
so_err != 0) {
(void)::close(fd);
return std::unexpected{make_ipc_error(
map_errno_to_ipc(so_err != 0 ? so_err : errno),
"AF_UNIX connect failed",
so_err != 0 ? so_err : errno)};
}
break;
}
(void)::close(fd);
return std::unexpected{make_ipc_error(
map_errno_to_ipc(err),
std::format("Failed connecting to '{}'", socket_path.string()),
err)};
}
auto creds = query_peer_credentials(fd);
if (!creds.has_value()) {
(void)::close(fd);
return std::unexpected{std::move(creds.error())};
}
if (auto auth = check_peer_policy(*creds, policy); !auth.has_value()) {
(void)::close(fd);
return std::unexpected{std::move(auth.error())};
}
auto stream = driver.adopt_fd(fd);
if (!stream.has_value()) {
(void)::close(fd);
return std::unexpected{std::move(stream.error())};
}
return DuplexTransport{std::move(*stream), *creds};
}
Void::Result::Result<DuplexTransport, Void::Result::Error>
adopt_pipe_pair(Void::IO::Driver& driver, int read_fd, int write_fd)
{
if (read_fd < 0 || write_fd < 0 || read_fd == write_fd) {
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"adopt_pipe_pair requires distinct valid read_fd and write_fd")};
}
if (::fcntl(read_fd, F_GETFD) == -1 || ::fcntl(write_fd, F_GETFD) == -1) {
const int err = errno;
return std::unexpected{make_ipc_error(
IpcErrorCode::invalid_argument,
"adopt_pipe_pair received closed or invalid descriptor",
err)};
}
auto rstream = driver.adopt_fd(read_fd);
if (!rstream.has_value()) {
return std::unexpected{std::move(rstream.error())};
}
auto wstream = driver.adopt_fd(write_fd);
if (!wstream.has_value()) {
// read_fd already owned by rstream (EpollDriver closes on destroy).
return std::unexpected{std::move(wstream.error())};
}
return DuplexTransport{std::move(*rstream),
std::move(*wstream),
PeerCredentials{.available = false}};
}
Void::Result::Result<std::pair<DuplexTransport, DuplexTransport>,
Void::Result::Error>
create_socket_pair_transports(Void::IO::Driver& driver)
{
auto pair = driver.create_socket_pair();
if (!pair.has_value()) {
return std::unexpected{std::move(pair.error())};
}
PeerCredentials self_creds;
self_creds.available = true;
self_creds.pid = static_cast<long long>(::getpid());
self_creds.uid = static_cast<unsigned long>(::geteuid());
self_creds.gid = static_cast<unsigned long>(::getegid());
return std::pair<DuplexTransport, DuplexTransport>{
DuplexTransport{std::move(pair->first), self_creds},
DuplexTransport{std::move(pair->second), self_creds}};
}
} // namespace Void::IPC
+3
View File
@@ -0,0 +1,3 @@
void_add_module(IPC
INTERNAL_DEPS Core Functional Memory Time Binary Async IO Resilience
)
+203
View File
@@ -0,0 +1,203 @@
#include <Void/Security/Authorization.hpp>
#include <algorithm>
namespace Void::Security
{
namespace
{
[[nodiscard]] Void::Result::Result<void>
validate_predicate(const Predicate& pred, std::size_t depth)
{
if (depth > SecurityLimits::kMaxPredicateDepth) {
return std::unexpected{make_security_error(
SecurityErrorCode::policy_invalid,
"Security::PolicySnapshot: predicate nesting exceeds max "
"depth 16")};
}
switch (pred.kind) {
case Predicate::Kind::AlwaysTrue:
case Predicate::Kind::AlwaysFalse:
case Predicate::Kind::HasRole:
case Predicate::Kind::SubjectEquals:
case Predicate::Kind::ResourceTypeEquals:
case Predicate::Kind::ResourceIdEquals:
case Predicate::Kind::ResourceAttrEquals:
case Predicate::Kind::PrincipalAttrEquals:
case Predicate::Kind::ResourceOwnerMatchesSubject:
return {};
case Predicate::Kind::AllOf:
case Predicate::Kind::AnyOf:
for (const auto& child : pred.children) {
if (auto res = validate_predicate(child, depth + 1U);
!res.has_value()) {
return res;
}
}
return {};
case Predicate::Kind::Not:
if (pred.children.size() != 1U) {
return std::unexpected{make_security_error(
SecurityErrorCode::policy_invalid,
"Security::PolicySnapshot: Not predicate requires "
"exactly 1 child")};
}
return validate_predicate(pred.children.front(),
depth + 1U);
}
return std::unexpected{make_security_error(
SecurityErrorCode::policy_invalid,
"Security::PolicySnapshot: unknown predicate kind")};
}
[[nodiscard]] bool eval_predicate(const Predicate& pred,
const Principal& principal,
const ResourceAttributes& resource,
std::size_t depth)
{
if (depth > SecurityLimits::kMaxPredicateDepth) {
return false;
}
switch (pred.kind) {
case Predicate::Kind::AlwaysTrue:
return true;
case Predicate::Kind::AlwaysFalse:
return false;
case Predicate::Kind::HasRole:
return std::find(principal.roles.begin(),
principal.roles.end(),
pred.value) != principal.roles.end();
case Predicate::Kind::SubjectEquals:
return !principal.subject.empty() &&
principal.subject == pred.value;
case Predicate::Kind::ResourceTypeEquals:
return resource.resource_type == pred.value;
case Predicate::Kind::ResourceIdEquals:
return resource.resource_id == pred.value;
case Predicate::Kind::ResourceAttrEquals:
{
auto it = resource.attributes.find(pred.key);
return it != resource.attributes.end() &&
it->second == pred.value;
}
case Predicate::Kind::PrincipalAttrEquals:
{
auto it = principal.attributes.find(pred.key);
return it != principal.attributes.end() &&
it->second == pred.value;
}
case Predicate::Kind::ResourceOwnerMatchesSubject:
{
if (principal.subject.empty()) {
return false;
}
const std::string_view attr_key =
pred.key.empty() ? std::string_view{"owner"}
: std::string_view{pred.key};
auto it = resource.attributes.find(attr_key);
return it != resource.attributes.end() &&
it->second == principal.subject;
}
case Predicate::Kind::AllOf:
if (pred.children.empty()) {
return false;
}
for (const auto& child : pred.children) {
if (!eval_predicate(child, principal, resource,
depth + 1U)) {
return false;
}
}
return true;
case Predicate::Kind::AnyOf:
for (const auto& child : pred.children) {
if (eval_predicate(child, principal, resource,
depth + 1U)) {
return true;
}
}
return false;
case Predicate::Kind::Not:
if (pred.children.size() != 1U) {
return false;
}
return !eval_predicate(pred.children.front(), principal,
resource, depth + 1U);
}
return false;
}
} // namespace
Void::Result::Result<PolicySnapshot>
PolicySnapshot::create(std::uint64_t generation,
std::vector<PolicyRule> rules)
{
if (rules.size() > SecurityLimits::kMaxPolicyRules) {
return std::unexpected{make_security_error(
SecurityErrorCode::policy_invalid,
"Security::PolicySnapshot: rule count exceeds 4096 cap")};
}
for (const auto& rule : rules) {
if (rule.action.empty()) {
return std::unexpected{make_security_error(
SecurityErrorCode::policy_invalid,
"Security::PolicySnapshot: rule action must be non-empty")};
}
if (auto res = validate_predicate(rule.condition, 1U);
!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
}
return PolicySnapshot{generation, std::move(rules)};
}
Decision PolicySnapshot::authorize(const Principal& principal,
std::string_view action,
const ResourceAttributes& resource) const
{
if (action.empty()) {
return Decision{.allowed = false,
.reason = "empty action denied",
.policy_generation = m_generation};
}
if (principal.roles.size() > SecurityLimits::kMaxRolesPerPrincipal) {
return Decision{.allowed = false,
.reason = "principal exceeds 64-role cap",
.policy_generation = m_generation};
}
std::string allow_rule_id;
bool matched_allow = false;
for (const auto& rule : m_rules) {
if (rule.action != "*" && rule.action != action) {
continue;
}
if (!eval_predicate(rule.condition, principal, resource, 1U)) {
continue;
}
if (rule.effect == Effect::Deny) {
return Decision{.allowed = false,
.matched_rule_id = rule.id,
.reason = "explicit deny",
.policy_generation = m_generation};
}
if (!matched_allow) {
matched_allow = true;
allow_rule_id = rule.id;
}
}
if (matched_allow) {
return Decision{.allowed = true,
.matched_rule_id = std::move(allow_rule_id),
.reason = "explicit allow",
.policy_generation = m_generation};
}
return Decision{.allowed = false,
.reason = "default deny",
.policy_generation = m_generation};
}
} // namespace Void::Security
+433
View File
@@ -0,0 +1,433 @@
#include <Void/Security/Envelope.hpp>
#include <sodium.h>
#include <algorithm>
#include <array>
#include <cstring>
#include <vector>
namespace Void::Security
{
namespace
{
constexpr std::array<unsigned char, 4> kMagic{'V', 'S', 'E', 'C'};
constexpr std::size_t kFixedPrefixBytes = 4 + 1 + 1 + 2 + 4; // 12
[[nodiscard]] Void::Result::Result<void> ensure_sodium_env()
{
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::sodium_init, "Security::Envelope");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
static const bool ok = sodium_init() >= 0;
if (!ok) {
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::Envelope: libsodium initialization failed")};
}
return {};
}
void append_u16_be(std::vector<unsigned char>& out, std::uint16_t v)
{
out.push_back(static_cast<unsigned char>((v >> 8U) & 0xFFU));
out.push_back(static_cast<unsigned char>(v & 0xFFU));
}
void append_u32_be(std::vector<unsigned char>& out, std::uint32_t v)
{
out.push_back(static_cast<unsigned char>((v >> 24U) & 0xFFU));
out.push_back(static_cast<unsigned char>((v >> 16U) & 0xFFU));
out.push_back(static_cast<unsigned char>((v >> 8U) & 0xFFU));
out.push_back(static_cast<unsigned char>(v & 0xFFU));
}
void append_u64_be(std::vector<unsigned char>& out, std::uint64_t v)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<unsigned char>((v >> shift) & 0xFFU));
}
}
[[nodiscard]] std::uint16_t read_u16_be(const unsigned char* p) noexcept
{
return static_cast<std::uint16_t>(
(static_cast<std::uint16_t>(p[0]) << 8U) |
static_cast<std::uint16_t>(p[1]));
}
[[nodiscard]] std::uint32_t read_u32_be(const unsigned char* p) noexcept
{
return (static_cast<std::uint32_t>(p[0]) << 24U) |
(static_cast<std::uint32_t>(p[1]) << 16U) |
(static_cast<std::uint32_t>(p[2]) << 8U) |
static_cast<std::uint32_t>(p[3]);
}
[[nodiscard]] bool valid_key_id(std::string_view key_id) noexcept
{
if (key_id.empty() || key_id.size() > SecurityLimits::kMaxKeyIdBytes) {
return false;
}
for (const unsigned char ch : key_id) {
if (ch < 0x20U || ch == 0x7FU) {
return false;
}
}
return true;
}
[[nodiscard]] std::vector<unsigned char>
build_aead_aad(std::span<const unsigned char> header_and_nonce,
std::span<const unsigned char> caller_aad)
{
std::vector<unsigned char> combined;
combined.reserve(header_and_nonce.size() + 8 + caller_aad.size());
combined.insert(combined.end(), header_and_nonce.begin(),
header_and_nonce.end());
append_u64_be(combined, static_cast<std::uint64_t>(caller_aad.size()));
combined.insert(combined.end(), caller_aad.begin(),
caller_aad.end());
return combined;
}
} // namespace
Void::Result::Result<EnvelopeHeader>
inspect_envelope(std::span<const unsigned char> envelope)
{
if (envelope.size() <
kFixedPrefixBytes + kEnvelopeNonceBytes + kEnvelopeTagBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::unsupported_version,
"Security::inspect_envelope: truncated or non-VSEC envelope")};
}
if (!std::equal(kMagic.begin(), kMagic.end(), envelope.begin())) {
return std::unexpected{make_security_error(
SecurityErrorCode::unsupported_version,
"Security::inspect_envelope: invalid magic (legacy fallback "
"disabled)")};
}
const std::uint8_t version = envelope[4];
const std::uint8_t algorithm = envelope[5];
if (version != kEnvelopeVersionV1) {
return std::unexpected{make_security_error(
SecurityErrorCode::unsupported_version,
"Security::inspect_envelope: unsupported envelope version")};
}
if (algorithm != kEnvelopeAlgXChaCha20Poly1305Ietf) {
return std::unexpected{make_security_error(
SecurityErrorCode::unsupported_version,
"Security::inspect_envelope: unsupported envelope algorithm")};
}
const std::uint16_t key_id_len = read_u16_be(envelope.data() + 6);
const std::uint32_t plaintext_size = read_u32_be(envelope.data() + 8);
if (key_id_len == 0 || key_id_len > SecurityLimits::kMaxKeyIdBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::authentication_failed,
"Security::inspect_envelope: invalid key_id length")};
}
if (plaintext_size > SecurityLimits::kMaxSecretPlaintextBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::inspect_envelope: declared plaintext exceeds 16 MiB "
"cap")};
}
const std::size_t expected_size =
kFixedPrefixBytes + static_cast<std::size_t>(key_id_len) +
kEnvelopeNonceBytes + static_cast<std::size_t>(plaintext_size) +
kEnvelopeTagBytes;
if (envelope.size() != expected_size) {
return std::unexpected{make_security_error(
SecurityErrorCode::authentication_failed,
"Security::inspect_envelope: envelope length mismatch")};
}
std::string key_id(
reinterpret_cast<const char*>(envelope.data() + kFixedPrefixBytes),
key_id_len);
if (!valid_key_id(key_id)) {
return std::unexpected{make_security_error(
SecurityErrorCode::authentication_failed,
"Security::inspect_envelope: invalid characters in key_id")};
}
return EnvelopeHeader{
.version = version,
.algorithm = algorithm,
.key_id = std::move(key_id),
.plaintext_size = plaintext_size,
};
}
Void::Result::Result<void>
SecretKeyRing::add_key(std::string key_id,
std::span<const unsigned char> raw_key,
bool make_active, LockPolicy lock_policy)
{
if (!valid_key_id(key_id)) {
return std::unexpected{make_security_error(
SecurityErrorCode::invalid_argument,
"Security::SecretKeyRing::add_key: invalid key_id")};
}
if (raw_key.size() != kEnvelopeKeyBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::invalid_argument,
"Security::SecretKeyRing::add_key: key must be 32 bytes")};
}
if (m_keys.contains(key_id)) {
return std::unexpected{make_security_error(
SecurityErrorCode::conflict,
"Security::SecretKeyRing::add_key: duplicate key_id")};
}
auto stored = SecureBuffer::from_bytes(raw_key, lock_policy);
if (!stored.has_value()) {
return std::unexpected{std::move(stored.error())};
}
const std::string id_copy = key_id;
m_keys.emplace(std::move(key_id), std::move(*stored));
if (make_active || m_active_key_id.empty()) {
m_active_key_id = id_copy;
}
return {};
}
Void::Result::Result<void>
SecretKeyRing::generate_and_add_key(std::string key_id,
bool make_active,
LockPolicy lock_policy)
{
if (auto init = ensure_sodium_env(); !init.has_value()) {
return std::unexpected{std::move(init.error())};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::random_bytes,
"Security::SecretKeyRing::generate_and_add_key");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
auto key_buf = SecureBuffer::allocate(kEnvelopeKeyBytes, lock_policy);
if (!key_buf.has_value()) {
return std::unexpected{std::move(key_buf.error())};
}
static_assert(kEnvelopeKeyBytes ==
crypto_aead_xchacha20poly1305_ietf_KEYBYTES);
crypto_aead_xchacha20poly1305_ietf_keygen(key_buf->writable().data());
return add_key(std::move(key_id), key_buf->view(), make_active,
lock_policy);
}
Void::Result::Result<void>
SecretKeyRing::set_active_key(std::string_view key_id)
{
auto it = m_keys.find(key_id);
if (it == m_keys.end()) {
return std::unexpected{make_security_error(
SecurityErrorCode::key_not_found,
"Security::SecretKeyRing::set_active_key: unknown key_id")};
}
m_active_key_id = it->first;
return {};
}
Void::Result::Result<void> SecretKeyRing::retire_key(
std::string_view key_id,
std::span<const std::string> remaining_ciphertext_key_ids)
{
auto it = m_keys.find(key_id);
if (it == m_keys.end()) {
return std::unexpected{make_security_error(
SecurityErrorCode::key_not_found,
"Security::SecretKeyRing::retire_key: unknown key_id")};
}
if (it->first == m_active_key_id) {
return std::unexpected{make_security_error(
SecurityErrorCode::key_in_use,
"Security::SecretKeyRing::retire_key: cannot retire active "
"key")};
}
for (const auto& referenced : remaining_ciphertext_key_ids) {
if (referenced == key_id) {
return std::unexpected{make_security_error(
SecurityErrorCode::key_in_use,
"Security::SecretKeyRing::retire_key: ciphertext inventory "
"still references key_id")};
}
}
m_keys.erase(it);
return {};
}
std::optional<std::string> SecretKeyRing::active_key_id() const
{
if (m_active_key_id.empty()) {
return std::nullopt;
}
return m_active_key_id;
}
bool SecretKeyRing::has_key(std::string_view key_id) const
{
return m_keys.find(key_id) != m_keys.end();
}
std::vector<std::string> SecretKeyRing::key_ids() const
{
std::vector<std::string> ids;
ids.reserve(m_keys.size());
for (const auto& [id, _] : m_keys) {
ids.push_back(id);
}
return ids;
}
Void::Result::Result<std::vector<unsigned char>>
SecretKeyRing::seal(std::span<const unsigned char> plaintext,
std::span<const unsigned char> aad) const
{
if (auto init = ensure_sodium_env(); !init.has_value()) {
return std::unexpected{std::move(init.error())};
}
if (m_active_key_id.empty()) {
return std::unexpected{make_security_error(
SecurityErrorCode::key_not_found,
"Security::SecretKeyRing::seal: no active key configured")};
}
if (plaintext.size() > SecurityLimits::kMaxSecretPlaintextBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::SecretKeyRing::seal: plaintext exceeds 16 MiB cap")};
}
if (aad.size() > SecurityLimits::kMaxAadBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::SecretKeyRing::seal: AAD exceeds 64 KiB cap")};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::secret_seal, "Security::SecretKeyRing::seal");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
auto it = m_keys.find(m_active_key_id);
if (it == m_keys.end()) {
return std::unexpected{make_security_error(
SecurityErrorCode::key_not_found,
"Security::SecretKeyRing::seal: active key missing")};
}
static_assert(kEnvelopeNonceBytes ==
crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
static_assert(kEnvelopeTagBytes ==
crypto_aead_xchacha20poly1305_ietf_ABYTES);
const std::size_t header_size =
kFixedPrefixBytes + m_active_key_id.size() + kEnvelopeNonceBytes;
std::vector<unsigned char> out;
out.reserve(header_size + plaintext.size() + kEnvelopeTagBytes);
out.insert(out.end(), kMagic.begin(), kMagic.end());
out.push_back(kEnvelopeVersionV1);
out.push_back(kEnvelopeAlgXChaCha20Poly1305Ietf);
append_u16_be(out, static_cast<std::uint16_t>(m_active_key_id.size()));
append_u32_be(out, static_cast<std::uint32_t>(plaintext.size()));
for (const char ch : m_active_key_id) {
out.push_back(static_cast<unsigned char>(ch));
}
const std::size_t nonce_offset = out.size();
out.resize(nonce_offset + kEnvelopeNonceBytes);
randombytes_buf(out.data() + nonce_offset, kEnvelopeNonceBytes);
const auto combined_aad =
build_aead_aad(std::span<const unsigned char>{out}, aad);
const std::size_t ct_offset = out.size();
out.resize(ct_offset + plaintext.size() + kEnvelopeTagBytes);
unsigned long long ct_len = 0;
static constexpr unsigned char kEmptyByte = 0;
const unsigned char* pt_ptr =
plaintext.empty() ? &kEmptyByte : plaintext.data();
if (crypto_aead_xchacha20poly1305_ietf_encrypt(
out.data() + ct_offset, &ct_len, pt_ptr,
static_cast<unsigned long long>(plaintext.size()),
combined_aad.data(),
static_cast<unsigned long long>(combined_aad.size()), nullptr,
out.data() + nonce_offset, it->second.view().data()) != 0 ||
ct_len != plaintext.size() + kEnvelopeTagBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::SecretKeyRing::seal: AEAD encryption failed")};
}
return out;
}
Void::Result::Result<SecureBuffer>
SecretKeyRing::open(std::span<const unsigned char> envelope,
std::span<const unsigned char> aad,
LockPolicy out_policy) const
{
if (auto init = ensure_sodium_env(); !init.has_value()) {
return std::unexpected{std::move(init.error())};
}
if (aad.size() > SecurityLimits::kMaxAadBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::SecretKeyRing::open: AAD exceeds 64 KiB cap")};
}
auto header = inspect_envelope(envelope);
if (!header.has_value()) {
return std::unexpected{std::move(header.error())};
}
auto it = m_keys.find(header->key_id);
if (it == m_keys.end()) {
return std::unexpected{make_security_error(
SecurityErrorCode::key_not_found,
"Security::SecretKeyRing::open: unknown key_id in envelope")};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::secret_open, "Security::SecretKeyRing::open");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
const std::size_t nonce_offset =
kFixedPrefixBytes + header->key_id.size();
const std::size_t header_and_nonce_len =
nonce_offset + kEnvelopeNonceBytes;
const auto combined_aad =
build_aead_aad(envelope.subspan(0, header_and_nonce_len), aad);
auto plaintext =
SecureBuffer::allocate(header->plaintext_size, out_policy);
if (!plaintext.has_value()) {
return std::unexpected{std::move(plaintext.error())};
}
unsigned char dummy_out = 0;
unsigned char* out_ptr =
plaintext->empty() ? &dummy_out : plaintext->writable().data();
unsigned long long pt_len = 0;
const std::size_t ct_size = envelope.size() - header_and_nonce_len;
if (crypto_aead_xchacha20poly1305_ietf_decrypt(
out_ptr, &pt_len, nullptr,
envelope.data() + header_and_nonce_len,
static_cast<unsigned long long>(ct_size), combined_aad.data(),
static_cast<unsigned long long>(combined_aad.size()),
envelope.data() + nonce_offset,
it->second.view().data()) != 0 ||
pt_len != header->plaintext_size) {
plaintext->clear();
return std::unexpected{make_security_error(
SecurityErrorCode::authentication_failed,
"Security::SecretKeyRing::open: AEAD authentication failed")};
}
return plaintext;
}
} // namespace Void::Security
+152
View File
@@ -0,0 +1,152 @@
#include <Void/Security/SecureBuffer.hpp>
#include <sodium.h>
#include <atomic>
#include <cstring>
#include <new>
#include <utility>
namespace Void::Security
{
namespace
{
std::atomic<std::uint64_t> g_total_wiped_bytes{0};
[[nodiscard]] Void::Result::Result<void> ensure_sodium_buf()
{
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::sodium_init, "Security::SecureBuffer");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
static const bool ok = sodium_init() >= 0;
if (!ok) {
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::SecureBuffer: libsodium initialization failed")};
}
return {};
}
} // namespace
SecureBuffer::~SecureBuffer() noexcept { clear(); }
SecureBuffer::SecureBuffer(SecureBuffer&& other) noexcept
: m_data(std::exchange(other.m_data, nullptr)),
m_size(std::exchange(other.m_size, 0)),
m_locked(std::exchange(other.m_locked, false))
{
}
SecureBuffer& SecureBuffer::operator=(SecureBuffer&& other) noexcept
{
if (this != &other) {
clear();
m_data = std::exchange(other.m_data, nullptr);
m_size = std::exchange(other.m_size, 0);
m_locked = std::exchange(other.m_locked, false);
}
return *this;
}
void SecureBuffer::clear() noexcept
{
if (m_data != nullptr) {
if (m_size > 0) {
sodium_memzero(m_data, m_size);
g_total_wiped_bytes.fetch_add(m_size,
std::memory_order_relaxed);
}
if (m_locked) {
sodium_free(m_data);
} else {
delete[] m_data;
}
m_data = nullptr;
m_size = 0;
m_locked = false;
}
}
std::uint64_t SecureBuffer::total_wiped_bytes() noexcept
{
return g_total_wiped_bytes.load(std::memory_order_relaxed);
}
Void::Result::Result<SecureBuffer>
SecureBuffer::allocate(std::size_t size, LockPolicy policy)
{
if (size > SecurityLimits::kMaxSecretPlaintextBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::SecureBuffer: allocation exceeds 16 MiB cap")};
}
if (auto init = ensure_sodium_buf(); !init.has_value()) {
return std::unexpected{std::move(init.error())};
}
if (size == 0) {
return SecureBuffer{};
}
if (policy == LockPolicy::LockedRequired ||
policy == LockPolicy::LockedOptional) {
auto fault = Detail::maybe_inject_fault(
FaultOperation::locked_alloc,
"Security::SecureBuffer::allocate");
void* raw = fault.has_value() ? nullptr : sodium_malloc(size);
if (raw != nullptr) {
sodium_memzero(raw, size);
SecureBuffer buf;
buf.m_data = static_cast<unsigned char*>(raw);
buf.m_size = size;
buf.m_locked = true;
return buf;
}
if (policy == LockPolicy::LockedRequired) {
return std::unexpected{make_security_error(
SecurityErrorCode::locked_memory_unavailable,
"Security::SecureBuffer: required locked allocation "
"failed")};
}
}
unsigned char* raw = new (std::nothrow) unsigned char[size];
if (raw == nullptr) {
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::SecureBuffer: allocation failed")};
}
sodium_memzero(raw, size);
SecureBuffer buf;
buf.m_data = raw;
buf.m_size = size;
buf.m_locked = false;
return buf;
}
Void::Result::Result<SecureBuffer>
SecureBuffer::from_bytes(std::span<const unsigned char> data,
LockPolicy policy)
{
auto buf = allocate(data.size(), policy);
if (!buf.has_value()) {
return std::unexpected{std::move(buf.error())};
}
if (!data.empty()) {
std::memcpy(buf->m_data, data.data(), data.size());
}
return buf;
}
Void::Result::Result<SecureBuffer>
SecureBuffer::from_string(std::string_view text, LockPolicy policy)
{
return from_bytes(
std::span<const unsigned char>{
reinterpret_cast<const unsigned char*>(text.data()),
text.size()},
policy);
}
} // namespace Void::Security
+338 -40
View File
@@ -3,7 +3,9 @@
#include <sodium.h>
#include <array>
#include <charconv>
#include <cstring>
#include <format>
#include <limits>
#include <optional>
#include <vector>
@@ -12,6 +14,9 @@ namespace Void::Security
{
namespace
{
thread_local FaultConfig g_fault_config{};
thread_local std::size_t g_fault_hits{0};
struct PasswordLimits {
unsigned long long operations;
std::size_t memory;
@@ -19,10 +24,16 @@ namespace Void::Security
[[nodiscard]] Void::Result::Result<void> ensure_sodium()
{
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::sodium_init, "Security::ensure_sodium");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
static const bool initialized = sodium_init() >= 0;
if (!initialized) {
return Void::Result::fail(
"Security: libsodium initialization failed");
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security: libsodium initialization failed")};
}
return {};
}
@@ -54,21 +65,106 @@ namespace Void::Security
token.size(), nullptr, 0);
return digest;
}
[[nodiscard]] std::optional<std::uint64_t>
parse_u64_strict(std::string_view text) noexcept
{
if (text.empty()) {
return std::nullopt;
}
for (const char ch : text) {
if (ch < '0' || ch > '9') {
return std::nullopt;
}
}
std::uint64_t value = 0;
const auto res = std::from_chars(
text.data(), text.data() + text.size(), value);
if (res.ec != std::errc{} ||
res.ptr != text.data() + text.size()) {
return std::nullopt;
}
return value;
}
} // namespace
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
: m_previous(g_fault_config), m_previous_hits(g_fault_hits)
{
g_fault_config = config;
g_fault_hits = 0;
}
ScopedFaultGuard::~ScopedFaultGuard() noexcept
{
g_fault_config = m_previous;
g_fault_hits = m_previous_hits;
}
namespace Detail
{
std::optional<Void::Result::Error>
maybe_inject_fault(FaultOperation op, std::string_view operation)
{
if (g_fault_config.op == FaultOperation::none) {
return std::nullopt;
}
if (g_fault_config.op != FaultOperation::any &&
g_fault_config.op != op) {
return std::nullopt;
}
if (g_fault_hits < g_fault_config.fail_after) {
++g_fault_hits;
return std::nullopt;
}
++g_fault_hits;
return make_security_error(
g_fault_config.code,
std::format("{}: injected security backend fault", operation));
}
} // namespace Detail
void wipe_bytes(std::span<unsigned char> buffer) noexcept
{
if (!buffer.empty()) {
sodium_memzero(buffer.data(), buffer.size());
}
}
bool constant_time_equal(std::span<const unsigned char> lhs,
std::span<const unsigned char> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
if (lhs.empty()) {
return true;
}
return sodium_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
}
Void::Result::Result<std::string> random_token(std::size_t entropy_bytes)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
if (entropy_bytes == 0) {
return Void::Result::fail(
"Security::random_token: entropy must be greater than zero");
return std::unexpected{make_security_error(
SecurityErrorCode::invalid_argument,
"Security::random_token: entropy must be greater than zero")};
}
if (entropy_bytes >
(std::numeric_limits<std::size_t>::max() - 2) / 4 * 3) {
return Void::Result::fail(
"Security::random_token: entropy size is too large");
// 384 bytes base64url encodes to 512 chars (SecurityLimits::kMaxTokenBytes).
constexpr std::size_t kMaxEntropyBytes =
(SecurityLimits::kMaxTokenBytes / 4U) * 3U;
if (entropy_bytes > kMaxEntropyBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::random_token: entropy exceeds 512-byte token cap")};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::random_bytes, "Security::random_token");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
std::vector<unsigned char> random(entropy_bytes);
@@ -82,8 +178,9 @@ namespace Void::Security
sodium_base64_VARIANT_URLSAFE_NO_PADDING);
sodium_memzero(random.data(), random.size());
if (result == nullptr) {
return Void::Result::fail(
"Security::random_token: base64 encoding failed");
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::random_token: base64 encoding failed")};
}
encoded.resize(std::strlen(encoded.c_str()));
return encoded;
@@ -92,7 +189,12 @@ namespace Void::Security
Void::Result::Result<std::string> hash_token(std::string_view token)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
if (token.size() > SecurityLimits::kMaxTokenBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::hash_token: token exceeds 512-byte cap")};
}
const auto digest = token_digest(token);
@@ -106,7 +208,12 @@ namespace Void::Security
std::string_view encoded_hash)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
if (token.size() > SecurityLimits::kMaxTokenBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::verify_token: token exceeds 512-byte cap")};
}
constexpr auto encoded_length = crypto_generichash_BYTES * 2;
@@ -132,17 +239,24 @@ namespace Void::Security
hash_password(std::string_view password, PasswordHashStrength strength)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
if (password.size() > crypto_pwhash_PASSWD_MAX) {
return Void::Result::fail(
"Security::hash_password: password is too long");
if (password.size() > SecurityLimits::kMaxPasswordBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::hash_password: password exceeds 1 KiB cap")};
}
const auto limits = password_limits(strength);
if (!limits) {
return Void::Result::fail(
"Security::hash_password: invalid strength");
return std::unexpected{make_security_error(
SecurityErrorCode::invalid_argument,
"Security::hash_password: invalid strength")};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::password_hash, "Security::hash_password");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
std::array<char, crypto_pwhash_STRBYTES> encoded{};
@@ -151,23 +265,183 @@ namespace Void::Security
static_cast<unsigned long long>(password.size()),
limits->operations, limits->memory,
crypto_pwhash_ALG_ARGON2ID13) != 0) {
return Void::Result::fail(
"Security::hash_password: Argon2id hashing failed");
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::hash_password: Argon2id hashing failed")};
}
return std::string{encoded.data()};
}
Void::Result::Result<Argon2idCost>
parse_argon2id_cost(std::string_view encoded_hash)
{
if (encoded_hash.empty() ||
encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes ||
encoded_hash.find('\0') != std::string_view::npos) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: invalid hash length or NUL")};
}
// Format: $argon2id$v=19$m=<kib>,t=<ops>,p=<par>$<salt>$<digest>
constexpr std::string_view kPrefix = "$argon2id$";
if (!encoded_hash.starts_with(kPrefix)) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: unsupported algorithm prefix")};
}
std::string_view rest = encoded_hash.substr(kPrefix.size());
const auto next_field = [&](std::string_view& field) -> bool {
const auto sep = rest.find('$');
if (sep == std::string_view::npos) {
return false;
}
field = rest.substr(0, sep);
rest = rest.substr(sep + 1);
return true;
};
std::string_view ver_field;
std::string_view params_field;
std::string_view salt_field;
if (!next_field(ver_field) || !next_field(params_field) ||
!next_field(salt_field) || salt_field.empty() || rest.empty() ||
rest.find('$') != std::string_view::npos) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: malformed PHC structure")};
}
if (!ver_field.starts_with("v=")) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: missing version field")};
}
const auto ver = parse_u64_strict(ver_field.substr(2));
if (!ver.has_value() || *ver != 19ULL) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: unsupported Argon2 version")};
}
const auto c1 = params_field.find(',');
if (c1 == std::string_view::npos) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: missing parameter separators")};
}
const auto c2 = params_field.find(',', c1 + 1);
if (c2 == std::string_view::npos ||
params_field.find(',', c2 + 1) != std::string_view::npos) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: invalid parameter list")};
}
const std::string_view m_part = params_field.substr(0, c1);
const std::string_view t_part = params_field.substr(c1 + 1, c2 - c1 - 1);
const std::string_view p_part = params_field.substr(c2 + 1);
if (!m_part.starts_with("m=") || !t_part.starts_with("t=") ||
!p_part.starts_with("p=")) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: expected m=,t=,p= fields")};
}
const auto m_val = parse_u64_strict(m_part.substr(2));
const auto t_val = parse_u64_strict(t_part.substr(2));
const auto p_val = parse_u64_strict(p_part.substr(2));
if (!m_val.has_value() || !t_val.has_value() || !p_val.has_value() ||
*m_val == 0 || *t_val == 0 || *p_val == 0 ||
*p_val > std::numeric_limits<std::uint32_t>::max()) {
return std::unexpected{make_security_error(
SecurityErrorCode::malformed_hash,
"Security::parse_argon2id_cost: invalid m/t/p values")};
}
Argon2idCost cost{
.version = static_cast<std::uint32_t>(*ver),
.memory_kib = *m_val,
.iterations = *t_val,
.parallelism = static_cast<std::uint32_t>(*p_val),
};
if (!cost.memory_bytes().has_value()) {
return std::unexpected{make_security_error(
SecurityErrorCode::cost_budget_exceeded,
"Security::parse_argon2id_cost: memory cost overflows")};
}
return cost;
}
Void::Result::Result<bool>
verify_password_budgeted(std::string_view password,
std::string_view encoded_hash,
const PasswordVerifyBudget& budget)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return std::unexpected{initialized.error()};
}
if (password.size() > SecurityLimits::kMaxPasswordBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::verify_password_budgeted: password exceeds 1 KiB "
"cap")};
}
if (encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::verify_password_budgeted: encoded hash exceeds 1 "
"KiB cap")};
}
auto cost = parse_argon2id_cost(encoded_hash);
if (!cost.has_value()) {
return std::unexpected{std::move(cost.error())};
}
const auto mem_bytes = cost->memory_bytes();
if (!mem_bytes.has_value() || *mem_bytes > budget.max_memory_bytes ||
cost->iterations > budget.max_iterations ||
cost->parallelism > budget.max_parallelism) {
return std::unexpected{make_security_error(
SecurityErrorCode::cost_budget_exceeded,
"Security::verify_password_budgeted: encoded Argon2id cost "
"exceeds approved verification budget")};
}
const std::string terminated_hash{encoded_hash};
return crypto_pwhash_str_verify(
terminated_hash.c_str(), password.data(),
static_cast<unsigned long long>(password.size())) == 0;
}
Void::Result::Result<bool> verify_password(std::string_view password,
std::string_view encoded_hash)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
if (password.size() > crypto_pwhash_PASSWD_MAX ||
if (password.size() > SecurityLimits::kMaxPasswordBytes ||
encoded_hash.empty() ||
encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes ||
encoded_hash.find('\0') != std::string_view::npos) {
return false;
}
auto cost = parse_argon2id_cost(encoded_hash);
if (!cost.has_value()) {
return false;
}
// Prevent DoS from malicious encoded costs even through the legacy
// helper while allowing all built-in libsodium presets up to Sensitive.
const auto mem_bytes = cost->memory_bytes();
if (!mem_bytes.has_value() ||
*mem_bytes > crypto_pwhash_MEMLIMIT_SENSITIVE ||
cost->iterations > 32ULL || cost->parallelism > 8U) {
return std::unexpected{make_security_error(
SecurityErrorCode::cost_budget_exceeded,
"Security::verify_password: encoded Argon2id cost exceeds "
"safety ceiling")};
}
const std::string terminated_hash{encoded_hash};
return crypto_pwhash_str_verify(
@@ -178,7 +452,12 @@ namespace Void::Security
Void::Result::Result<SecretKey> random_secret_key()
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::random_bytes, "Security::random_secret_key");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
static_assert(secret_key_bytes == crypto_secretbox_KEYBYTES);
@@ -192,15 +471,19 @@ namespace Void::Security
const SecretKey& key)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
static_assert(secret_nonce_bytes == crypto_secretbox_NONCEBYTES);
static_assert(secret_authentication_bytes == crypto_secretbox_MACBYTES);
if (plaintext.size() > std::numeric_limits<std::size_t>::max() -
secret_nonce_bytes -
secret_authentication_bytes) {
return Void::Result::fail(
"Security::seal_secret: plaintext is too large");
if (plaintext.size() > SecurityLimits::kMaxSecretPlaintextBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::seal_secret: plaintext exceeds 16 MiB cap")};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::secret_seal, "Security::seal_secret");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
std::vector<unsigned char> envelope(secret_nonce_bytes +
@@ -213,8 +496,9 @@ namespace Void::Security
ciphertext, plaintext.data(),
static_cast<unsigned long long>(plaintext.size()), nonce,
key.data()) != 0) {
return Void::Result::fail(
"Security::seal_secret: encryption failed");
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::seal_secret: encryption failed")};
}
return envelope;
}
@@ -224,25 +508,39 @@ namespace Void::Security
const SecretKey& key)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return Void::Result::fail(std::move(initialized).error());
return std::unexpected{initialized.error()};
}
if (envelope.size() <
secret_nonce_bytes + secret_authentication_bytes) {
return Void::Result::fail(
"Security::open_secret: envelope is truncated");
return std::unexpected{make_security_error(
SecurityErrorCode::authentication_failed,
"Security::open_secret: envelope is truncated")};
}
const auto ciphertext_size = envelope.size() - secret_nonce_bytes;
const auto plaintext_size =
ciphertext_size - secret_authentication_bytes;
if (plaintext_size > SecurityLimits::kMaxSecretPlaintextBytes) {
return std::unexpected{make_security_error(
SecurityErrorCode::input_too_large,
"Security::open_secret: envelope exceeds 16 MiB cap")};
}
if (auto fault = Detail::maybe_inject_fault(
FaultOperation::secret_open, "Security::open_secret");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
const auto* nonce = envelope.data();
const auto* ciphertext = nonce + secret_nonce_bytes;
const auto ciphertext_size = envelope.size() - secret_nonce_bytes;
std::vector<unsigned char> plaintext(ciphertext_size -
secret_authentication_bytes);
std::vector<unsigned char> plaintext(plaintext_size);
if (crypto_secretbox_open_easy(
plaintext.data(), ciphertext,
static_cast<unsigned long long>(ciphertext_size), nonce,
key.data()) != 0) {
return Void::Result::fail(
"Security::open_secret: authentication failed");
wipe_bytes(plaintext);
return std::unexpected{make_security_error(
SecurityErrorCode::authentication_failed,
"Security::open_secret: authentication failed")};
}
return plaintext;
}
+3 -1
View File
@@ -1,4 +1,6 @@
void_add_module(Security
INTERNAL_DEPS Functional
INTERNAL_DEPS Functional Time
EXTERNAL_DEPS Sodium::Sodium
EXCLUDE_HEADERS
Void/Security/Authenticator.hpp
)
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
void_add_module(SecurityAsync
INTERNAL_DEPS Security Async Time Resilience Functional
EXTERNAL_DEPS Threads::Threads
EXTRA_HEADERS
Void/Security/Authenticator.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
)
+1593 -296
View File
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -1,4 +1,7 @@
void_add_module(System
INTERNAL_DEPS Functional LogState
INTERNAL_DEPS Functional Time LogState
EXTERNAL_DEPS Threads::Threads
EXCLUDE_HEADERS
Void/System/AsyncProcess.hpp
Void/System/AsyncWatcher.hpp
)
+781
View File
@@ -0,0 +1,781 @@
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/System/AsyncProcess.hpp>
#include <signal.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstring>
#include <expected>
#include <format>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace Void::SystemAsync
{
namespace
{
struct PipeCommState {
std::mutex mu{};
Void::Process::CaptureLimits limits{};
std::stop_source stop_src{};
std::string out{};
std::string err{};
std::size_t out_cur_line{0};
std::size_t err_cur_line{0};
bool stdout_truncated{false};
bool stderr_truncated{false};
bool timed_out{false};
bool cancelled{false};
bool overflowed{false};
std::optional<Void::Result::Error> fatal_error{};
};
void record_fatal(PipeCommState& st, Void::Result::Error err)
{
std::lock_guard lk{st.mu};
if (!st.fatal_error.has_value()) {
st.fatal_error = std::move(err);
}
st.stop_src.request_stop();
}
void process_pipe_chunk(PipeCommState& st,
const std::byte* data,
std::size_t len,
bool is_stdout)
{
std::lock_guard lk{st.mu};
std::string& dst = is_stdout ? st.out : st.err;
const std::size_t max_bytes =
is_stdout ? st.limits.max_stdout_bytes : st.limits.max_stderr_bytes;
bool& truncated = is_stdout ? st.stdout_truncated : st.stderr_truncated;
std::size_t& cur_line = is_stdout ? st.out_cur_line : st.err_cur_line;
const auto* chars = reinterpret_cast<const char*>(data);
if (st.limits.max_line_bytes > 0) {
for (std::size_t i = 0; i < len; ++i) {
if (chars[i] == '\n') {
cur_line = 0;
} else {
++cur_line;
if (cur_line > st.limits.max_line_bytes) {
truncated = true;
st.overflowed = true;
if (st.limits.overflow_policy ==
Void::Process::OverflowPolicy::fail_and_terminate) {
if (!st.fatal_error.has_value()) {
st.fatal_error = Void::System::make_system_error(
Void::System::SystemErrorCode::line_limit,
std::format(
"Async process {} line exceeded max_line_bytes ({})",
is_stdout ? "stdout" : "stderr",
st.limits.max_line_bytes));
}
st.stop_src.request_stop();
return;
}
}
}
}
}
const std::size_t rem_cap =
(dst.size() < max_bytes) ? (max_bytes - dst.size()) : 0;
const std::size_t to_store = std::min(len, rem_cap);
if (to_store > 0) {
dst.append(chars, to_store);
}
if (to_store < len) {
truncated = true;
st.overflowed = true;
if (st.limits.overflow_policy ==
Void::Process::OverflowPolicy::fail_and_terminate) {
if (!st.fatal_error.has_value()) {
st.fatal_error = Void::System::make_system_error(
Void::System::SystemErrorCode::output_limit,
std::format(
"Async process {} output exceeded limit ({} bytes)",
is_stdout ? "stdout" : "stderr",
max_bytes));
}
st.stop_src.request_stop();
}
}
}
[[nodiscard]] Void::Coro::Task<void> pump_stdin_task(
Void::IO::Driver* driver,
Void::IO::ByteStream stream,
std::shared_ptr<PipeCommState> st,
std::string stdin_data,
std::stop_token ext_stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline)
{
constexpr std::size_t kChunk = 16ULL * 1024ULL;
std::size_t offset = 0;
while (offset < stdin_data.size() && !st->stop_src.stop_requested()) {
const std::size_t n = std::min(kChunk, stdin_data.size() - offset);
auto lease_res = driver->allocate_buffer(n);
if (!lease_res.has_value()) {
record_fatal(*st, std::move(lease_res.error()));
break;
}
auto lease = std::move(*lease_res);
std::memcpy(lease.writable().data(), stdin_data.data() + offset, n);
lease.set_valid_bytes(n);
Void::Async::OperationOptions pipe_opts{
.stop = st->stop_src.get_token(), .deadline = deadline};
auto wr = co_await stream.write_some_owned(lease, pipe_opts);
if (!wr.has_value()) {
const auto& err = wr.error();
if (err.kind() == Void::Result::ErrorKind::timeout) {
std::lock_guard lk{st->mu};
st->timed_out = true;
st->stop_src.request_stop();
} else if (err.kind() == Void::Result::ErrorKind::cancelled &&
ext_stop.stop_requested()) {
std::lock_guard lk{st->mu};
st->cancelled = true;
st->stop_src.request_stop();
}
break;
}
offset += wr->bytes;
}
(void)co_await stream.close_and_join();
}
[[nodiscard]] Void::Coro::Task<void> pump_read_task(
Void::IO::Driver* driver,
Void::IO::ByteStream stream,
std::shared_ptr<PipeCommState> st,
bool is_stdout,
std::stop_token ext_stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline)
{
constexpr std::size_t kChunk = 16ULL * 1024ULL;
auto lease_res = driver->allocate_buffer(kChunk);
if (!lease_res.has_value()) {
record_fatal(*st, std::move(lease_res.error()));
(void)co_await stream.close_and_join();
co_return;
}
auto lease = std::move(*lease_res);
while (!st->stop_src.stop_requested()) {
Void::Async::OperationOptions pipe_opts{
.stop = st->stop_src.get_token(), .deadline = deadline};
auto rd = co_await stream.read_some_owned(lease, pipe_opts);
if (!rd.has_value()) {
const auto& err = rd.error();
if (err.kind() == Void::Result::ErrorKind::timeout) {
std::lock_guard lk{st->mu};
st->timed_out = true;
st->stop_src.request_stop();
} else if (err.kind() == Void::Result::ErrorKind::cancelled) {
if (ext_stop.stop_requested()) {
std::lock_guard lk{st->mu};
st->cancelled = true;
}
} else {
record_fatal(*st, err);
}
break;
}
if (rd->bytes > 0) {
process_pipe_chunk(
*st, lease.readable().data(), rd->bytes, is_stdout);
if (st->stop_src.stop_requested()) {
break;
}
}
if (rd->eof) {
break;
}
}
(void)co_await stream.close_and_join();
}
struct WaitOutcome {
Void::Process::ExitStatus status{};
bool timed_out{false};
bool cancelled{false};
};
struct ReaperEntry {
Void::Process::Child* child{nullptr};
std::shared_ptr<Void::Async::OperationState<WaitOutcome>> op{};
bool escalate_immediately{false};
int phase{0}; // 0 = waiting/running, 1 = SIGTERM sent
std::chrono::milliseconds grace{std::chrono::milliseconds{2000}};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
Void::Time::MonotonicClock::time_point kill_deadline{};
bool done{false};
};
} // namespace
struct ProcessManager::Impl : public std::enable_shared_from_this<ProcessManager::Impl> {
Void::IO::Driver& driver;
Void::Async::Executor& executor;
ProcessManagerOptions options;
const Void::Time::MonotonicClock& clock;
mutable std::mutex mu{};
std::condition_variable cv{};
std::size_t active_slots{0};
bool closing{false};
bool stop_worker{false};
std::vector<ReaperEntry> waits{};
std::vector<std::shared_ptr<Void::Async::OperationState<void>>> close_waiters{};
std::thread reaper_thread{};
Impl(Void::IO::Driver& d,
Void::Async::Executor& ex,
ProcessManagerOptions opts,
const Void::Time::MonotonicClock& clk)
: driver(d), executor(ex), options(opts), clock(clk)
{
reaper_thread = std::thread([this] { run_reaper(); });
}
~Impl() noexcept
{
{
std::lock_guard lk{mu};
closing = true;
stop_worker = true;
cv.notify_all();
}
if (reaper_thread.joinable()) {
reaper_thread.join();
}
}
void release_slot() noexcept
{
std::lock_guard lk{mu};
if (active_slots > 0) {
--active_slots;
}
cv.notify_all();
}
void run_reaper()
{
for (;;) {
std::vector<Void::Async::ResumeTicket> tickets;
std::vector<std::shared_ptr<Void::Async::OperationState<void>>>
completed_closes;
{
std::unique_lock lk{mu};
if (waits.empty() && !stop_worker) {
cv.wait(lk, [this] {
return !waits.empty() || stop_worker;
});
}
if (stop_worker && waits.empty()) {
for (auto& cw : close_waiters) {
if (auto t = cw->try_commit_value(); t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = cw->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
}
close_waiters.clear();
lk.unlock();
for (auto& t : tickets) {
t.dispatch();
}
return;
}
const auto now = clock.now();
for (auto& w : waits) {
if (w.done) {
continue;
}
auto polled = w.child->try_wait();
if (!polled.has_value()) {
if (auto t = w.op->try_commit_error(
std::move(polled.error()));
t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = w.op->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
w.done = true;
continue;
}
if (polled->has_value()) {
WaitOutcome wo;
wo.status = **polled;
wo.timed_out =
(w.phase > 0 && w.deadline.has_value() &&
now >= *w.deadline) ||
w.escalate_immediately;
wo.cancelled = w.op->stop_requested() || stop_worker;
if (auto t = w.op->try_commit_value(wo); t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = w.op->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
w.done = true;
continue;
}
const bool expired =
w.deadline.has_value() && now >= *w.deadline;
const bool stopped = w.op->stop_requested() || stop_worker;
if (w.phase == 0 &&
(w.escalate_immediately || expired || stopped)) {
(void)w.child->send_signal(SIGTERM);
w.phase = 1;
w.kill_deadline = now + w.grace;
} else if (w.phase == 1 && now >= w.kill_deadline) {
(void)w.child->send_signal(SIGKILL);
auto term_res = w.child->wait_blocking(
std::chrono::milliseconds{1000});
if (term_res.has_value()) {
WaitOutcome wo;
wo.status = *term_res;
wo.timed_out = expired;
wo.cancelled = stopped;
if (auto t = w.op->try_commit_value(wo);
t.has_value()) {
tickets.push_back(std::move(*t));
}
} else {
if (auto t = w.op->try_commit_error(
std::move(term_res.error()));
t.has_value()) {
tickets.push_back(std::move(*t));
}
}
if (auto r = w.op->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
w.done = true;
}
}
std::erase_if(
waits, [](const ReaperEntry& e) { return e.done; });
if (closing && waits.empty() && !close_waiters.empty()) {
completed_closes = std::move(close_waiters);
close_waiters.clear();
}
}
for (auto& cw : completed_closes) {
if (auto t = cw->try_commit_value(); t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = cw->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
}
for (auto& t : tickets) {
t.dispatch();
}
std::unique_lock lk{mu};
if (!waits.empty()) {
cv.wait_for(lk, std::chrono::milliseconds{5}, [this] {
return stop_worker;
});
}
}
}
};
struct ManagedChild::SlotGuard {
std::weak_ptr<ProcessManager::Impl> mgr;
~SlotGuard() noexcept
{
if (auto p = mgr.lock()) {
p->release_slot();
}
}
};
ManagedChild::~ManagedChild() noexcept = default;
ManagedChild::ManagedChild(ManagedChild&&) noexcept = default;
ManagedChild& ManagedChild::operator=(ManagedChild&&) noexcept = default;
bool ManagedChild::valid() const noexcept { return child_.valid(); }
void ManagedChild::release_slot() noexcept
{
child_ = Void::Process::Child{};
slot_token_.reset();
}
ProcessManager::ProcessManager(Void::IO::Driver& driver,
Void::Async::Executor& executor,
ProcessManagerOptions options,
const Void::Time::MonotonicClock& clock)
: impl_(std::make_shared<Impl>(driver, executor, options, clock))
{
}
ProcessManager::~ProcessManager() noexcept = default;
Void::Result::Result<ManagedChild, Void::Result::Error>
ProcessManager::spawn(const Void::Process::SpawnOptions& options)
{
{
std::lock_guard lk{impl_->mu};
if (impl_->closing) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"ProcessManager::spawn: manager is closing")};
}
if (impl_->active_slots >= impl_->options.max_active_children) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format(
"ProcessManager::spawn: active child limit ({}) reached",
impl_->options.max_active_children))};
}
++impl_->active_slots;
}
auto guard =
std::make_shared<ManagedChild::SlotGuard>(impl_);
auto child = Void::Process::spawn(options);
if (!child.has_value()) {
return std::unexpected{std::move(child.error())};
}
ManagedChild out;
out.child_ = std::move(*child);
out.slot_token_ = std::move(guard);
return out;
}
namespace
{
[[nodiscard]] Void::Coro::Task<Void::Result::Result<WaitOutcome, Void::Result::Error>>
wait_for_reap_async(
std::shared_ptr<ProcessManager::Impl> impl,
Void::Process::Child& child,
bool escalate_immediately,
std::chrono::milliseconds grace,
Void::Async::OperationOptions options)
{
if (!child.valid()) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"ProcessManager::wait: invalid child")};
}
if (auto polled = child.try_wait(); !polled.has_value()) {
co_return std::unexpected{std::move(polled.error())};
} else if (polled->has_value()) {
WaitOutcome wo;
wo.status = **polled;
co_return wo;
}
auto op = Void::Async::OperationState<WaitOutcome>::create(
options,
&impl->executor,
Void::Async::StopBehavior::notify_only);
op->acquire_backend_ref();
{
std::lock_guard lk{impl->mu};
if (impl->closing && !escalate_immediately) {
if (auto r = op->release_backend_ref(); r.has_value()) {
r->dispatch();
}
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"ProcessManager::wait: manager is closing")};
}
ReaperEntry entry;
entry.child = &child;
entry.op = op;
entry.escalate_immediately = escalate_immediately;
entry.grace = grace;
entry.deadline = options.deadline;
impl->waits.push_back(std::move(entry));
impl->cv.notify_all();
}
co_return co_await op->awaitable(&impl->executor);
}
} // namespace
Void::Coro::Task<Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
ProcessManager::communicate(Void::Process::Child& child,
std::string stdin_data,
Void::Process::CaptureLimits limits,
Void::Async::OperationOptions options)
{
if (!child.valid()) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"ProcessManager::communicate: invalid child")};
}
if (stdin_data.size() > limits.max_stdin_bytes) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
"ProcessManager::communicate: stdin exceeds max_stdin_bytes")};
}
if (Void::Async::is_deadline_expired(options, impl_->clock)) {
(void)child.terminate(impl_->options.default_kill_grace);
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"ProcessManager::communicate: deadline already expired")};
}
if (stdin_data.empty()) {
child.close_stdin();
}
Void::IO::ByteStream in_stream;
Void::IO::ByteStream out_stream;
Void::IO::ByteStream err_stream;
auto adopt_pipe =
[&](Void::System::OwnedFd owned,
Void::IO::ByteStream& target) -> Void::Result::Result<void, Void::Result::Error> {
if (!owned.valid()) {
return {};
}
auto adopted = impl_->driver.adopt_fd(owned.get());
if (!adopted.has_value()) {
return std::unexpected{std::move(adopted.error())};
}
(void)owned.release();
target = std::move(*adopted);
return {};
};
if (auto r = adopt_pipe(child.take_stdin_fd(), in_stream); !r.has_value()) {
co_return std::unexpected{std::move(r.error())};
}
if (auto r = adopt_pipe(child.take_stdout_fd(), out_stream); !r.has_value()) {
if (in_stream.valid()) {
(void)co_await in_stream.close_and_join();
}
co_return std::unexpected{std::move(r.error())};
}
if (auto r = adopt_pipe(child.take_stderr_fd(), err_stream); !r.has_value()) {
if (in_stream.valid()) {
(void)co_await in_stream.close_and_join();
}
if (out_stream.valid()) {
(void)co_await out_stream.close_and_join();
}
co_return std::unexpected{std::move(r.error())};
}
auto st = std::make_shared<PipeCommState>();
st->limits = limits;
struct ForwardStop {
std::shared_ptr<PipeCommState> state;
void operator()() const noexcept { state->stop_src.request_stop(); }
};
std::optional<std::stop_callback<ForwardStop>> ext_cb;
if (options.stop.stop_possible()) {
ext_cb.emplace(options.stop, ForwardStop{st});
}
Void::Async::TaskScope scope{
impl_->executor,
Void::Async::TaskScopeOptions::unlimited(st->stop_src.get_token(), false),
impl_->clock};
if (in_stream.valid()) {
auto sp = scope.spawn(pump_stdin_task(&impl_->driver,
std::move(in_stream),
st,
std::move(stdin_data),
options.stop,
options.deadline));
if (!sp.has_value()) {
record_fatal(*st,
Void::Async::make_async_error(
sp.error(), "Failed to spawn async stdin pump"));
}
}
if (out_stream.valid()) {
auto sp = scope.spawn(pump_read_task(&impl_->driver,
std::move(out_stream),
st,
true,
options.stop,
options.deadline));
if (!sp.has_value()) {
record_fatal(*st,
Void::Async::make_async_error(
sp.error(), "Failed to spawn async stdout pump"));
}
}
if (err_stream.valid()) {
auto sp = scope.spawn(pump_read_task(&impl_->driver,
std::move(err_stream),
st,
false,
options.stop,
options.deadline));
if (!sp.has_value()) {
record_fatal(*st,
Void::Async::make_async_error(
sp.error(), "Failed to spawn async stderr pump"));
}
}
(void)co_await scope.join();
bool need_terminate = false;
bool timed_out_flag = false;
bool cancelled_flag = options.stop.stop_requested();
std::optional<Void::Result::Error> fatal_err;
{
std::lock_guard lk{st->mu};
timed_out_flag = st->timed_out ||
Void::Async::is_deadline_expired(options, impl_->clock);
cancelled_flag = cancelled_flag || st->cancelled;
fatal_err = st->fatal_error;
need_terminate = timed_out_flag || cancelled_flag || fatal_err.has_value();
}
auto wait_res = co_await wait_for_reap_async(
impl_,
child,
need_terminate,
impl_->options.default_kill_grace,
need_terminate ? Void::Async::OperationOptions{} : options);
if (fatal_err.has_value()) {
co_return std::unexpected{std::move(*fatal_err)};
}
if (!wait_res.has_value()) {
co_return std::unexpected{std::move(wait_res.error())};
}
Void::Process::CommunicateResult out;
{
std::lock_guard lk{st->mu};
out.out = std::move(st->out);
out.err = std::move(st->err);
out.stdout_truncated = st->stdout_truncated;
out.stderr_truncated = st->stderr_truncated;
out.overflowed = st->overflowed;
}
out.status = wait_res->status;
out.timed_out = timed_out_flag || wait_res->timed_out;
out.cancelled = cancelled_flag || wait_res->cancelled;
co_return out;
}
Void::Coro::Task<Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
ProcessManager::communicate(ManagedChild& managed,
std::string stdin_data,
Void::Process::CaptureLimits limits,
Void::Async::OperationOptions options)
{
co_return co_await communicate(
managed.child(), std::move(stdin_data), limits, std::move(options));
}
Void::Coro::Task<Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
ProcessManager::wait(Void::Process::Child& child,
Void::Async::OperationOptions options)
{
auto wo = co_await wait_for_reap_async(
impl_,
child,
false,
impl_->options.default_kill_grace,
std::move(options));
if (!wo.has_value()) {
co_return std::unexpected{std::move(wo.error())};
}
if (wo->cancelled) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"ProcessManager::wait cancelled; child terminated")};
}
if (wo->timed_out) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"ProcessManager::wait timed out; child terminated")};
}
co_return wo->status;
}
Void::Coro::Task<Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
ProcessManager::wait(ManagedChild& managed,
Void::Async::OperationOptions options)
{
co_return co_await wait(managed.child(), std::move(options));
}
Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
ProcessManager::close_and_join(Void::Async::OperationOptions options)
{
std::shared_ptr<Void::Async::OperationState<void>> op;
{
std::lock_guard lk{impl_->mu};
impl_->closing = true;
if (impl_->waits.empty()) {
impl_->stop_worker = true;
impl_->cv.notify_all();
co_return {};
}
op = Void::Async::OperationState<void>::create(
options,
&impl_->executor,
Void::Async::StopBehavior::settle_cancelled);
op->acquire_backend_ref();
impl_->close_waiters.push_back(op);
impl_->cv.notify_all();
}
auto res = co_await op->awaitable(&impl_->executor);
std::lock_guard lk{impl_->mu};
impl_->stop_worker = true;
impl_->cv.notify_all();
co_return res;
}
std::size_t ProcessManager::active_children() const noexcept
{
std::lock_guard lk{impl_->mu};
return impl_->active_slots;
}
bool ProcessManager::closed() const noexcept
{
std::lock_guard lk{impl_->mu};
return impl_->closing;
}
} // namespace Void::SystemAsync
+648
View File
@@ -0,0 +1,648 @@
#include <Void/Async/TaskScope.hpp>
#include <Void/System/AsyncWatcher.hpp>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <cerrno>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <expected>
#include <filesystem>
#include <format>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::SystemAsync
{
namespace
{
thread_local const void* t_active_subscription_token = nullptr;
struct DispatchGuard {
const void* prev{nullptr};
explicit DispatchGuard(const void* cur) noexcept
: prev(t_active_subscription_token)
{
t_active_subscription_token = cur;
}
~DispatchGuard() noexcept { t_active_subscription_token = prev; }
};
struct PathSnapshot {
bool exists{false};
bool is_symlink{false};
bool permission_denied{false};
int sys_errno{0};
std::uint64_t dev{0};
std::uint64_t ino{0};
std::uint32_t mode{0};
std::uint64_t size{0};
std::int64_t mtime_ns{0};
std::string symlink_target{};
[[nodiscard]] bool operator==(const PathSnapshot&) const = default;
};
[[nodiscard]] PathSnapshot probe_path(const std::filesystem::path& path)
{
PathSnapshot snap;
#ifndef _WIN32
struct stat st {};
if (::lstat(path.c_str(), &st) != 0) {
const int err = errno;
snap.sys_errno = err;
if (err == EACCES || err == EPERM) {
snap.permission_denied = true;
}
return snap;
}
snap.exists = true;
snap.is_symlink = S_ISLNK(st.st_mode);
snap.dev = static_cast<std::uint64_t>(st.st_dev);
snap.ino = static_cast<std::uint64_t>(st.st_ino);
snap.mode = static_cast<std::uint32_t>(st.st_mode);
snap.size = static_cast<std::uint64_t>(st.st_size);
snap.mtime_ns =
static_cast<std::int64_t>(st.st_mtim.tv_sec) * 1000000000LL +
static_cast<std::int64_t>(st.st_mtim.tv_nsec);
if (snap.is_symlink) {
std::array<char, 4096> link_buf{};
const ssize_t len =
::readlink(path.c_str(), link_buf.data(), link_buf.size());
if (len > 0) {
snap.symlink_target.assign(
link_buf.data(), static_cast<std::size_t>(len));
}
}
#else
(void)path;
#endif
return snap;
}
[[nodiscard]] bool path_within_root(const std::filesystem::path& candidate,
const std::filesystem::path& root,
std::filesystem::path& out_normalized)
{
std::error_code ec;
const auto canon_root = std::filesystem::weakly_canonical(root, ec);
if (ec) {
return false;
}
const auto lex_cand = candidate.lexically_normal();
for (const auto& comp : lex_cand) {
if (comp == "..") {
return false;
}
}
const auto parent = lex_cand.parent_path();
std::filesystem::path norm_cand;
if (!parent.empty()) {
const auto canon_parent = std::filesystem::weakly_canonical(parent, ec);
if (ec) {
return false;
}
norm_cand = canon_parent / lex_cand.filename();
} else {
norm_cand = std::filesystem::weakly_canonical(lex_cand, ec);
if (ec) {
return false;
}
}
auto rel = norm_cand.lexically_relative(canon_root);
if (rel.empty()) {
return false;
}
for (const auto& comp : rel) {
if (comp == "..") {
return false;
}
break;
}
out_normalized = std::move(norm_cand);
return true;
}
[[nodiscard]] WatchEvent classify_transition(const std::filesystem::path& path,
const PathSnapshot& prev,
const PathSnapshot& cur,
bool allow_symlink)
{
WatchEvent ev;
ev.path = path;
ev.exists = cur.exists;
ev.dev = cur.dev;
ev.ino = cur.ino;
ev.size = cur.size;
ev.sys_errno = cur.sys_errno;
if (cur.permission_denied) {
ev.kind = WatchEventKind::permission_denied;
return ev;
}
if (cur.is_symlink && !allow_symlink) {
ev.kind = WatchEventKind::permission_denied;
return ev;
}
if (!prev.exists && cur.exists) {
ev.kind = WatchEventKind::created;
return ev;
}
if (prev.exists && !cur.exists) {
ev.kind = WatchEventKind::deleted;
return ev;
}
if (prev.is_symlink || cur.is_symlink) {
ev.kind = WatchEventKind::symlink_changed;
return ev;
}
if (prev.dev != cur.dev || prev.ino != cur.ino) {
ev.kind = WatchEventKind::replaced_inode;
return ev;
}
ev.kind = WatchEventKind::modified;
return ev;
}
} // namespace
struct WatchSubscription::Token {
std::uint64_t id{0};
std::filesystem::path path{};
WatchCallback callback{};
WatchPathOptions options{};
std::weak_ptr<WatcherService::Impl> service{};
PathSnapshot accepted{};
PathSnapshot pending{};
int stable_polls{0};
bool dirty{false};
bool active{true};
bool delivery_scheduled{false};
bool dispatching{false};
std::deque<WatchEvent> queue{};
std::mutex mu{};
std::condition_variable cv{};
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
close_and_join();
};
struct WatcherService::Impl
: public std::enable_shared_from_this<WatcherService::Impl> {
using Token = WatchSubscription::Token;
Void::Async::Executor& executor;
WatcherLimits limits;
const Void::Time::MonotonicClock& clock;
ErrorSink error_sink{};
Void::Async::TaskScope scope;
std::mutex poll_mu{};
mutable std::mutex state_mu{};
std::condition_variable stop_cv{};
std::uint64_t next_id{1};
bool closed{false};
std::size_t total_queued{0};
std::unordered_map<std::uint64_t, std::shared_ptr<Token>> subs{};
std::thread bg_thread{};
Impl(Void::Async::Executor& ex,
WatcherLimits lim,
const Void::Time::MonotonicClock& clk,
ErrorSink sink)
: executor(ex),
limits(lim),
clock(clk),
error_sink(std::move(sink)),
scope(ex, Void::Async::TaskScopeOptions::unlimited(), clk)
{
}
static void enqueue_event_locked(Impl& impl, Token& tok, WatchEvent ev)
{
std::lock_guard tlk{tok.mu};
if (!tok.active) {
return;
}
for (auto& existing : tok.queue) {
if (existing.path == ev.path) {
if (existing.kind != WatchEventKind::rescan_required) {
existing = std::move(ev);
}
return;
}
}
if (impl.total_queued >= impl.limits.max_queued_events) {
if (!tok.queue.empty()) {
tok.queue.back().kind = WatchEventKind::rescan_required;
return;
}
ev.kind = WatchEventKind::rescan_required;
}
tok.queue.push_back(std::move(ev));
++impl.total_queued;
}
[[nodiscard]] static Void::Coro::Task<void> deliver_subscription_events(
std::shared_ptr<Impl> impl,
std::shared_ptr<Token> tok)
{
for (;;) {
WatchEvent ev;
{
std::lock_guard lk{impl->state_mu};
std::lock_guard tlk{tok->mu};
if (!tok->active || tok->queue.empty()) {
tok->delivery_scheduled = false;
tok->dispatching = false;
tok->cv.notify_all();
co_return;
}
ev = std::move(tok->queue.front());
tok->queue.pop_front();
if (impl->total_queued > 0) {
--impl->total_queued;
}
tok->dispatching = true;
}
try {
DispatchGuard dg{tok.get()};
tok->callback(ev);
} catch (const std::exception& ex) {
if (impl->error_sink) {
impl->error_sink(Void::System::make_system_error(
Void::System::SystemErrorCode::internal,
std::format(
"Watcher callback exception: {}", ex.what())));
}
} catch (...) {
if (impl->error_sink) {
impl->error_sink(Void::System::make_system_error(
Void::System::SystemErrorCode::internal,
"Watcher callback threw non-std exception"));
}
}
{
std::lock_guard tlk{tok->mu};
tok->dispatching = false;
tok->cv.notify_all();
if (!tok->active) {
tok->delivery_scheduled = false;
co_return;
}
}
}
}
void poll_once()
{
std::lock_guard poll_lk{poll_mu};
std::vector<std::shared_ptr<Token>> active_subs;
{
std::lock_guard lk{state_mu};
if (closed) {
return;
}
active_subs.reserve(subs.size());
for (const auto& [id, tok] : subs) {
(void)id;
active_subs.push_back(tok);
}
}
std::vector<std::shared_ptr<Token>> to_schedule;
const int required_debounce = std::max(1, limits.debounce_polls);
for (const auto& tok : active_subs) {
std::filesystem::path p;
bool allow_sym = false;
{
std::lock_guard tlk{tok->mu};
if (!tok->active) {
continue;
}
p = tok->path;
allow_sym = tok->options.allow_symlink;
}
const PathSnapshot cur = probe_path(p);
std::lock_guard lk{state_mu};
if (closed) {
break;
}
std::optional<WatchEvent> ready_event;
{
std::lock_guard tlk{tok->mu};
if (!tok->active) {
continue;
}
if (!tok->dirty) {
if (!(cur == tok->accepted)) {
tok->pending = cur;
tok->stable_polls = 1;
tok->dirty = true;
}
} else {
if (cur == tok->pending) {
++tok->stable_polls;
} else if (cur == tok->accepted) {
tok->dirty = false;
tok->stable_polls = 0;
} else {
tok->pending = cur;
tok->stable_polls = 1;
}
}
if (tok->dirty && tok->stable_polls >= required_debounce) {
WatchEvent ev = classify_transition(
tok->path, tok->accepted, tok->pending, allow_sym);
tok->accepted = tok->pending;
tok->dirty = false;
tok->stable_polls = 0;
ready_event = std::move(ev);
}
}
if (ready_event.has_value()) {
enqueue_event_locked(*this, *tok, std::move(*ready_event));
std::lock_guard tlk{tok->mu};
if (tok->active && !tok->delivery_scheduled &&
!tok->queue.empty()) {
tok->delivery_scheduled = true;
to_schedule.push_back(tok);
}
}
}
auto self = this->shared_from_this();
for (const auto& tok : to_schedule) {
(void)scope.spawn(deliver_subscription_events(self, tok));
}
}
};
Void::Result::Result<void, Void::Result::Error>
WatchSubscription::Token::close_and_join()
{
auto svc = service.lock();
if (t_active_subscription_token == this) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::self_join,
"WatchSubscription::close_and_join cannot be called from its own callback")};
}
if (svc != nullptr && svc->executor.is_executor_thread()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::self_join,
"WatchSubscription::close_and_join cannot block on executor thread")};
}
if (svc != nullptr) {
std::lock_guard lk{svc->state_mu};
std::lock_guard tlk{mu};
if (svc->total_queued >= queue.size()) {
svc->total_queued -= queue.size();
} else {
svc->total_queued = 0;
}
queue.clear();
active = false;
svc->subs.erase(id);
} else {
std::lock_guard tlk{mu};
queue.clear();
active = false;
}
std::unique_lock tlk{mu};
cv.wait(tlk, [this] { return !dispatching; });
return {};
}
WatchSubscription::~WatchSubscription() noexcept
{
if (token_) {
(void)token_->close_and_join();
}
}
WatchSubscription::WatchSubscription(WatchSubscription&&) noexcept = default;
WatchSubscription&
WatchSubscription::operator=(WatchSubscription&& other) noexcept
{
if (this != &other) {
if (token_) {
(void)token_->close_and_join();
}
token_ = std::move(other.token_);
}
return *this;
}
bool WatchSubscription::active() const noexcept
{
if (!token_) {
return false;
}
std::lock_guard lk{token_->mu};
return token_->active;
}
Void::Result::Result<void, Void::Result::Error>
WatchSubscription::close_and_join()
{
if (!token_) {
return {};
}
auto res = token_->close_and_join();
if (res.has_value()) {
token_.reset();
}
return res;
}
WatcherService::WatcherService(Void::Async::Executor& executor,
WatcherLimits limits,
const Void::Time::MonotonicClock& clock,
ErrorSink error_sink,
bool start_background_thread)
: impl_(std::make_shared<Impl>(
executor, limits, clock, std::move(error_sink)))
{
if (start_background_thread) {
std::weak_ptr<Impl> weak_impl = impl_;
impl_->bg_thread = std::thread([weak_impl] {
for (;;) {
auto p = weak_impl.lock();
if (!p) {
return;
}
std::chrono::milliseconds interval{250};
{
std::unique_lock lk{p->state_mu};
if (p->closed) {
return;
}
interval = std::max(std::chrono::milliseconds{10},
p->limits.poll_interval);
p->stop_cv.wait_for(lk, interval, [&p] {
return p->closed;
});
if (p->closed) {
return;
}
}
p->poll_once();
}
});
}
}
WatcherService::~WatcherService() noexcept { (void)shutdown(); }
Void::Result::Result<WatchSubscription, Void::Result::Error>
WatcherService::watch(const std::filesystem::path& path,
WatchCallback callback,
WatchPathOptions options)
{
if (path.empty() || !callback) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"WatcherService::watch requires non-empty path and callback")};
}
std::filesystem::path target_path = path;
if (options.allowed_root.has_value()) {
std::filesystem::path normalized;
if (!path_within_root(path, *options.allowed_root, normalized)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::permission_denied,
std::format(
"WatcherService::watch: '{}' escapes allowed_root",
path.string()))};
}
target_path = std::move(normalized);
}
const PathSnapshot initial = probe_path(target_path);
if (initial.is_symlink && !options.allow_symlink) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::permission_denied,
std::format(
"WatcherService::watch: '{}' is a symlink and allow_symlink is false",
target_path.string()))};
}
auto tok = std::make_shared<WatchSubscription::Token>();
tok->path = std::move(target_path);
tok->callback = std::move(callback);
tok->options = std::move(options);
tok->service = impl_;
tok->accepted = initial;
tok->pending = initial;
{
std::lock_guard lk{impl_->state_mu};
if (impl_->closed) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"WatcherService::watch: service is shut down")};
}
if (impl_->subs.size() >= impl_->limits.max_watched_paths) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format(
"WatcherService::watch: max_watched_paths ({}) reached",
impl_->limits.max_watched_paths))};
}
tok->id = impl_->next_id++;
impl_->subs.emplace(tok->id, tok);
}
WatchSubscription sub;
sub.token_ = std::move(tok);
return sub;
}
void WatcherService::poll_once() { impl_->poll_once(); }
std::size_t WatcherService::watch_count() const noexcept
{
std::lock_guard lk{impl_->state_mu};
return impl_->subs.size();
}
std::size_t WatcherService::queued_event_count() const noexcept
{
std::lock_guard lk{impl_->state_mu};
return impl_->total_queued;
}
Void::Result::Result<void, Void::Result::Error> WatcherService::shutdown()
{
if (impl_->executor.is_executor_thread()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::self_join,
"WatcherService::shutdown cannot be called on executor thread")};
}
std::thread bg;
{
std::lock_guard lk{impl_->state_mu};
if (impl_->closed) {
return {};
}
impl_->closed = true;
impl_->total_queued = 0;
for (const auto& [id, tok] : impl_->subs) {
(void)id;
std::lock_guard tlk{tok->mu};
tok->active = false;
tok->queue.clear();
}
impl_->subs.clear();
impl_->stop_cv.notify_all();
bg = std::move(impl_->bg_thread);
}
if (bg.joinable()) {
bg.join();
}
impl_->scope.request_stop();
if (impl_->executor.has_background_workers()) {
(void)impl_->scope.join_blocking();
} else if (auto* manual =
dynamic_cast<Void::Async::ManualExecutor*>(&impl_->executor)) {
(void)impl_->scope.join_pumping(*manual);
}
return {};
}
} // namespace Void::SystemAsync
+7
View File
@@ -0,0 +1,7 @@
void_add_module(SystemAsync
INTERNAL_DEPS System Async IO Time Functional LogState
EXTERNAL_DEPS Threads::Threads
EXTRA_HEADERS
Void/System/AsyncProcess.hpp
Void/System/AsyncWatcher.hpp
)
+193 -22
View File
@@ -1,6 +1,7 @@
#include <Void/Update/Feed.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Text/Base64.hpp>
#include <algorithm>
@@ -592,6 +593,26 @@ namespace Void::Update
}
return true;
}
[[nodiscard]] Void::Result::Result<void>
enforce_parse_policy(std::string_view payload,
const VerificationPolicy& policy)
{
if (policy.parsePolicy == SchemaParsePolicy::StrictJsonProfile) {
auto strict = Json::Strict::parse(
payload, Json::Strict::ParseOptions{
.maximumDepth = policy.maxJsonDepth,
.allowDecimals = false,
});
if (!strict.has_value()) {
return std::unexpected{make_update_error(
UpdateErrorCode::schema_error,
std::format("Update feed: StrictJsonProfile rejected "
"payload: {}",
strict.error().message))};
}
}
return {};
}
} // namespace
Void::Result::Result<Feed>
@@ -599,8 +620,13 @@ namespace Void::Update
const VerificationPolicy& policy)
{
if (payload.size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Update feed: payload exceeds policy size");
return std::unexpected{make_update_error(
UpdateErrorCode::limit_exceeded,
"Update feed: payload exceeds policy size")};
}
if (auto strict = enforce_parse_policy(payload, policy);
!strict.has_value()) {
return std::unexpected{std::move(strict.error())};
}
return parse_feed(payload, policy);
}
@@ -665,25 +691,21 @@ namespace Void::Update
}
const auto key = keys.find(*keyId);
if (key == keys.end()) {
return Void::Result::fail(
"Update feed: envelope key is not trusted");
return std::unexpected{make_update_error(
UpdateErrorCode::untrusted_key,
"Update feed: envelope key is not trusted")};
}
auto payload = Encoding::Base64::decode_url(*payloadText);
auto signature = Encoding::Base64::decode_url(*signatureText);
if (!payload || !signature ||
payload->size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Update feed: invalid or oversized envelope encoding");
}
if (*schema == 3) {
auto signedDocument = Json::parse(*payload);
if (!signedDocument || !signedDocument->is_object() ||
displayedDocument == nullptr ||
*displayedDocument != *signedDocument) {
return Void::Result::fail("Update feed: readable document "
"differs from signed payload");
}
return std::unexpected{make_update_error(
UpdateErrorCode::schema_error,
"Update feed: invalid or oversized envelope encoding")};
}
// Verify exact signed payload bytes BEFORE any payload JSON parsing or
// schema-3 readable-document mirror comparison.
const auto signatureBytes =
std::as_bytes(std::span{signature->data(), signature->size()});
const auto payloadBytes =
@@ -691,11 +713,30 @@ namespace Void::Update
auto valid =
Crypto::verifyEd25519(payloadBytes, signatureBytes, key->second);
if (!valid) {
return std::unexpected{valid.error()};
return std::unexpected{make_update_error(
UpdateErrorCode::signature_failed, valid.error().message())};
}
if (!*valid) {
return Void::Result::fail(
"Update feed: signature verification failed");
return std::unexpected{make_update_error(
UpdateErrorCode::signature_failed,
"Update feed: signature verification failed")};
}
if (auto strict = enforce_parse_policy(*payload, policy);
!strict.has_value()) {
return std::unexpected{std::move(strict.error())};
}
if (*schema == 3) {
auto signedDocument = Json::parse(*payload);
if (!signedDocument || !signedDocument->is_object() ||
displayedDocument == nullptr ||
*displayedDocument != *signedDocument) {
return std::unexpected{make_update_error(
UpdateErrorCode::mirror_mismatch,
"Update feed: readable document differs from signed "
"payload")};
}
}
return VerifiedEnvelope{.schemaVersion = *schema,
.keyId = std::move(*keyId),
@@ -707,8 +748,13 @@ namespace Void::Update
const VerificationPolicy& policy)
{
if (payload.size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Component feed: payload exceeds policy size");
return std::unexpected{make_update_error(
UpdateErrorCode::limit_exceeded,
"Component feed: payload exceeds policy size")};
}
if (auto strict = enforce_parse_policy(payload, policy);
!strict.has_value()) {
return std::unexpected{std::move(strict.error())};
}
auto document = Json::parse(payload);
if (!document || !document->is_object()) {
@@ -754,8 +800,13 @@ namespace Void::Update
const VerificationPolicy& policy)
{
if (payload.size() > policy.maxPayloadBytes) {
return Void::Result::fail(
"Component feed: payload exceeds policy size");
return std::unexpected{make_update_error(
UpdateErrorCode::limit_exceeded,
"Component feed: payload exceeds policy size")};
}
if (auto strict = enforce_parse_policy(payload, policy);
!strict.has_value()) {
return std::unexpected{std::move(strict.error())};
}
auto document = Json::parse(payload);
if (!document || !document->is_object()) {
@@ -919,4 +970,124 @@ namespace Void::Update
}
return *selected;
}
Void::Result::Result<VerifiedSelection>
verify_and_select_release(std::string_view envelopeJson,
const Keyring& keys,
const SelectionRequest& request,
const VerificationPolicy& policy)
{
auto verified = verifyFeedEnvelope(envelopeJson, keys, policy);
if (!verified.has_value()) {
return std::unexpected{std::move(verified.error())};
}
auto selected = selectRelease(verified->feed, request);
if (!selected.has_value()) {
return std::unexpected{make_update_error(
UpdateErrorCode::schema_error,
"Update feed: no compatible release matched selection "
"request")};
}
VerifiedSelection out;
out.m_signed_envelope.assign(envelopeJson);
out.m_signed_payload = std::move(verified->signedPayload);
out.m_signer_key_id = std::move(verified->keyId);
out.m_feed_id = verified->feed.feedId;
out.m_sequence = verified->feed.sequence;
out.m_expires_at = verified->feed.expiresAt;
out.m_parse_policy = policy.parsePolicy;
out.m_release = ReleaseIdentity{
.component = std::move(selected->component),
.artifact_id = std::move(selected->artifactId),
.channel = std::move(selected->channel),
.version = std::move(selected->version),
.sequence = verified->feed.sequence,
.sha256 = std::move(selected->sha256),
.size = selected->size,
.url = std::move(selected->url),
.package_type = std::move(selected->packageType),
};
return out;
}
Void::Result::Result<VerifiedSelection> verify_and_select_component_set(
std::string_view catalogEnvelopeJson,
const std::map<std::string, std::string>& releaseEnvelopeJsons,
const Keyring& keys, std::string_view primaryComponentId,
const VerificationPolicy& policy)
{
auto cat_env = verifyEnvelope(catalogEnvelopeJson, keys, policy);
if (!cat_env.has_value()) {
return std::unexpected{std::move(cat_env.error())};
}
auto catalog =
parseComponentCatalogPayload(cat_env->signedPayload, policy);
if (!catalog.has_value()) {
return std::unexpected{std::move(catalog.error())};
}
if (catalog->components.size() >
UpdateLimits::kDefaultMaxComponentsPerTransaction) {
return std::unexpected{make_update_error(
UpdateErrorCode::limit_exceeded,
"Component set: exceeds 32-component transaction limit")};
}
std::map<std::string, ComponentRelease> releases;
std::size_t edge_count = 0;
for (const auto& [comp_id, env_json] : releaseEnvelopeJsons) {
auto rel_env = verifyEnvelope(env_json, keys, policy);
if (!rel_env.has_value()) {
return std::unexpected{std::move(rel_env.error())};
}
auto rel =
parseComponentReleasePayload(rel_env->signedPayload, policy);
if (!rel.has_value()) {
return std::unexpected{std::move(rel.error())};
}
edge_count += rel->dependencies.size();
if (edge_count > UpdateLimits::kDefaultMaxDependencyEdges) {
return std::unexpected{make_update_error(
UpdateErrorCode::limit_exceeded,
"Component set: exceeds 256 dependency-edge limit")};
}
releases.emplace(comp_id, std::move(*rel));
}
if (auto valid = validateComponentSet(*catalog, releases);
!valid.has_value()) {
return std::unexpected{std::move(valid.error())};
}
auto primary_it = releases.find(std::string{primaryComponentId});
if (primary_it == releases.end()) {
return std::unexpected{make_update_error(
UpdateErrorCode::invalid_argument,
"Component set: primaryComponentId not present in verified "
"set")};
}
const auto& primary = primary_it->second;
VerifiedSelection out;
out.m_signed_envelope.assign(catalogEnvelopeJson);
out.m_signed_payload = std::move(cat_env->signedPayload);
out.m_signer_key_id = std::move(cat_env->keyId);
out.m_feed_id = "component-catalog";
out.m_sequence = catalog->sequence;
out.m_expires_at = catalog->expiresAt;
out.m_parse_policy = policy.parsePolicy;
out.m_release = ReleaseIdentity{
.component = primary.componentId,
.artifact_id = primary.artifactIdentity,
.channel = primary.channel,
.version = primary.componentVersion,
.sequence = primary.sequence,
.sha256 = primary.artifact.sha256,
.size = primary.artifact.size,
.url = primary.artifact.url,
.package_type = primary.artifact.packageType,
};
out.m_components = std::move(releases);
return out;
}
} // namespace Void::Update
File diff suppressed because it is too large. Load diff
+118
View File
@@ -1721,6 +1721,124 @@ namespace Void::Update
return removed;
}
Void::Result::Result<PruneReport>
VersionStore::pruneWithPins(std::size_t retainedPreviousVersions,
std::span<const Semver::Version>
pinnedVersions,
std::size_t batchLimit)
{
if (batchLimit == 0) {
return Void::Result::fail(
"VersionStore::pruneWithPins: batchLimit must be positive");
}
for (const auto& path : {m_root, m_root / "versions"}) {
if (auto checked = require_real_directory(path); !checked) {
return std::unexpected{checked.error()};
}
}
auto lock = FileLock::acquire(m_root / ".update.lock");
if (!lock) {
return std::unexpected{lock.error()};
}
if (auto cleaned = cleanup_pruning_entries(m_root / "versions");
!cleaned) {
return std::unexpected{cleaned.error()};
}
auto current = currentVersion();
if (!current) {
return std::unexpected{current.error()};
}
auto pending = pendingActivation();
if (!pending) {
return std::unexpected{pending.error()};
}
auto history = read_health_history(m_root);
if (!history) {
return std::unexpected{history.error()};
}
auto published = published_versions(m_root / "versions");
if (!published) {
return std::unexpected{published.error()};
}
std::sort(published->begin(), published->end(),
std::greater<Semver::Version>{});
std::set<std::string, std::less<>> publishedNames;
for (const auto& version : *published) {
publishedNames.insert(version.to_string());
}
std::set<std::string, std::less<>> retained;
std::optional<std::string> currentName;
if (*current) {
currentName = (**current).to_string();
retained.insert(*currentName);
}
if (*pending) {
retained.insert((*pending)->candidateVersion.to_string());
if ((*pending)->previousVersion) {
retained.insert((*pending)->previousVersion->to_string());
}
}
std::size_t retainedPrevious = 0;
for (auto iterator = history->committedOrder.rbegin();
iterator != history->committedOrder.rend() &&
retainedPrevious < retainedPreviousVersions;
++iterator) {
const auto state = history->states.find(*iterator);
if (publishedNames.contains(*iterator) &&
state != history->states.end() &&
state->second == HealthState::healthy &&
(!currentName || *iterator != *currentName) &&
!retained.contains(*iterator)) {
retained.insert(*iterator);
++retainedPrevious;
}
}
std::set<std::string, std::less<>> pinnedNames;
for (const auto& v : pinnedVersions) {
pinnedNames.insert(v.to_string());
}
PruneReport report;
for (const auto& version : *published) {
const auto name = version.to_string();
if (retained.contains(name)) {
continue;
}
const auto state = history->states.find(name);
if (state == history->states.end() ||
(state->second != HealthState::healthy &&
state->second != HealthState::failed &&
state->second != HealthState::retired)) {
continue;
}
if (pinnedNames.contains(name)) {
report.skipped_due_to_pins.push_back(version);
continue;
}
if (report.removed.size() >= batchLimit) {
report.batch_limit_reached = true;
break;
}
if (state->second != HealthState::retired) {
if (auto recorded = append_health_event(m_root, 'D', name);
!recorded) {
return std::unexpected{recorded.error()};
}
}
if (auto pruned = quarantine_and_remove(m_root / "versions", name);
!pruned) {
return std::unexpected{pruned.error()};
}
report.removed.push_back(version);
}
return report;
}
Void::Result::Result<std::optional<Semver::Version>>
VersionStore::currentVersion() const
{
+1 -1
View File
@@ -1,3 +1,3 @@
void_add_module(Update
INTERNAL_DEPS Crypto Data Functional System Text
INTERNAL_DEPS Archive Crypto Data Functional System Text Time
)
+18 -1
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)
@@ -157,7 +160,7 @@ endif()
# ── Test-support executables & libraries ──────────────────────────────────────
# These are NOT test files; they are helper executables/libs referenced by tests.
if(TARGET VoidTests AND TARGET Void::System)
if(TARGET VoidTests AND (TARGET Void::System OR TARGET Void::IPC))
add_executable(VoidProcessHelper
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ProcessHelper.cpp")
set_target_properties(VoidProcessHelper PROPERTIES
@@ -170,6 +173,20 @@ if(TARGET VoidTests AND TARGET Void::System)
add_dependencies(VoidTests VoidProcessHelper)
endif()
if(TARGET VoidTests AND TARGET Void::Archive)
add_executable(VoidArchiveWorker
"${CMAKE_CURRENT_SOURCE_DIR}/helpers/ArchiveWorker.cpp")
target_link_libraries(VoidArchiveWorker PRIVATE Void::Archive)
set_target_properties(VoidArchiveWorker PROPERTIES
CXX_STANDARD 26
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
VOID_TESTING_NO_AUTO_SCAN TRUE)
target_compile_definitions(VoidTests PRIVATE
"VOID_ARCHIVE_WORKER_PATH=\"$<TARGET_FILE:VoidArchiveWorker>\"")
add_dependencies(VoidTests VoidArchiveWorker)
endif()
if(TARGET VoidTests AND TARGET Void::Plugin)
set(_test_plugin_src "${CMAKE_CURRENT_SOURCE_DIR}/plugins/TestPlugin.cpp")
if(EXISTS "${_test_plugin_src}")
+6
View File
@@ -0,0 +1,6 @@
#include <Void/Archive/Archive.hpp>
int main(int argc, char** argv)
{
return Void::Archive::run_isolated_worker_main(argc, argv);
}
+354 -1
View File
@@ -1,9 +1,23 @@
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <limits>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
extern char** environ;
namespace
{
@@ -25,6 +39,45 @@ int usage_error(std::string_view msg)
return 2;
}
bool write_all_fd(int fd, const void* data, std::size_t len) noexcept
{
const auto* ptr = static_cast<const std::uint8_t*>(data);
std::size_t written = 0;
while (written < len) {
const ssize_t n = ::write(fd, ptr + written, len - written);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
written += static_cast<std::size_t>(n);
}
return true;
}
bool read_exact_fd(int fd, void* data, std::size_t len, bool& clean_eof) noexcept
{
auto* ptr = static_cast<std::uint8_t*>(data);
std::size_t got = 0;
clean_eof = false;
while (got < len) {
const ssize_t n = ::read(fd, ptr + got, len - got);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
if (n == 0) {
clean_eof = (got == 0);
return false;
}
got += static_cast<std::size_t>(n);
}
return true;
}
int mode_echo(int argc, char** argv)
{
for (int i = 2; i < argc; ++i) {
@@ -126,6 +179,282 @@ int mode_lines(int argc, char** argv)
return 0;
}
int mode_ignore_sigterm(int argc, char** argv)
{
std::int64_t sleep_ms = 5000;
if (argc >= 3 && !parse_i64(argv[2], sleep_ms)) {
return usage_error("ignore-sigterm duration must be an integer");
}
if (sleep_ms < 0) {
sleep_ms = 0;
}
std::signal(SIGTERM, SIG_IGN);
std::cout << "ready\n" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds{sleep_ms});
return 0;
}
int mode_simultaneous_io(int argc, char** argv)
{
if (argc != 3) {
return usage_error("simultaneous-io requires <bytes>");
}
std::int64_t total_i64 = 0;
if (!parse_i64(argv[2], total_i64) || total_i64 < 0) {
return usage_error("simultaneous-io <bytes> must be non-negative");
}
const auto total = static_cast<std::size_t>(total_i64);
for (int fd : {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO}) {
const int fl = ::fcntl(fd, F_GETFL, 0);
if (fl >= 0) {
(void)::fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
}
std::string chunk_out(std::min<std::size_t>(4096, std::max<std::size_t>(1, total)), 'o');
std::string chunk_err(std::min<std::size_t>(4096, std::max<std::size_t>(1, total)), 'e');
std::size_t out_sent = 0;
std::size_t err_sent = 0;
std::size_t in_read = 0;
bool in_eof = false;
std::array<char, 4096> in_buf{};
while (!in_eof || out_sent < total || err_sent < total) {
std::array<struct pollfd, 3> pfds{};
nfds_t nfds = 0;
if (!in_eof) {
pfds[nfds++] = {STDIN_FILENO, POLLIN, 0};
}
if (out_sent < total) {
pfds[nfds++] = {STDOUT_FILENO, POLLOUT, 0};
}
if (err_sent < total) {
pfds[nfds++] = {STDERR_FILENO, POLLOUT, 0};
}
const int rc = ::poll(pfds.data(), nfds, -1);
if (rc < 0) {
if (errno == EINTR) {
continue;
}
return 1;
}
for (nfds_t i = 0; i < nfds; ++i) {
if (pfds[i].fd == STDIN_FILENO &&
(pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) != 0) {
for (;;) {
const ssize_t n = ::read(STDIN_FILENO, in_buf.data(), in_buf.size());
if (n > 0) {
in_read += static_cast<std::size_t>(n);
continue;
}
if (n == 0) {
in_eof = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
in_eof = true;
break;
}
} else if (pfds[i].fd == STDOUT_FILENO && (pfds[i].revents & POLLOUT) != 0) {
const std::size_t rem = std::min(chunk_out.size(), total - out_sent);
const ssize_t n = ::write(STDOUT_FILENO, chunk_out.data(), rem);
if (n > 0) {
out_sent += static_cast<std::size_t>(n);
} else if (n < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
return 1;
}
} else if (pfds[i].fd == STDERR_FILENO && (pfds[i].revents & POLLOUT) != 0) {
const std::size_t rem = std::min(chunk_err.size(), total - err_sent);
const ssize_t n = ::write(STDERR_FILENO, chunk_err.data(), rem);
if (n > 0) {
err_sent += static_cast<std::size_t>(n);
} else if (n < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
return 1;
}
}
}
}
return (in_read > 0 || total == 0) ? 0 : 0;
}
int mode_flood(int argc, char** argv)
{
if (argc != 4) {
return usage_error("flood requires <stdout_bytes> <stderr_bytes>");
}
std::int64_t out_n = 0;
std::int64_t err_n = 0;
if (!parse_i64(argv[2], out_n) || !parse_i64(argv[3], err_n) || out_n < 0 || err_n < 0) {
return usage_error("flood byte counts must be non-negative");
}
std::array<char, 4096> buf{};
buf.fill('O');
for (std::int64_t rem = out_n; rem > 0;) {
const auto chunk = static_cast<std::size_t>(std::min<std::int64_t>(rem, buf.size()));
if (!write_all_fd(STDOUT_FILENO, buf.data(), chunk)) {
return 1;
}
rem -= static_cast<std::int64_t>(chunk);
}
buf.fill('E');
for (std::int64_t rem = err_n; rem > 0;) {
const auto chunk = static_cast<std::size_t>(std::min<std::int64_t>(rem, buf.size()));
if (!write_all_fd(STDERR_FILENO, buf.data(), chunk)) {
return 1;
}
rem -= static_cast<std::int64_t>(chunk);
}
return 0;
}
int mode_long_line(int argc, char** argv)
{
if (argc != 3) {
return usage_error("long-line requires <bytes>");
}
std::int64_t len = 0;
if (!parse_i64(argv[2], len) || len < 0) {
return usage_error("long-line <bytes> must be non-negative");
}
std::array<char, 4096> buf{};
buf.fill('a');
for (std::int64_t rem = len; rem > 0;) {
const auto chunk = static_cast<std::size_t>(std::min<std::int64_t>(rem, buf.size()));
if (!write_all_fd(STDOUT_FILENO, buf.data(), chunk)) {
return 1;
}
rem -= static_cast<std::int64_t>(chunk);
}
const char nl = '\n';
return write_all_fd(STDOUT_FILENO, &nl, 1) ? 0 : 1;
}
int mode_check_fds()
{
std::vector<int> open_fds;
for (int fd = 3; fd <= 64; ++fd) {
if (::fcntl(fd, F_GETFD) != -1 || errno != EBADF) {
open_fds.push_back(fd);
}
}
if (open_fds.empty()) {
std::cout << "clean\n";
} else {
for (std::size_t i = 0; i < open_fds.size(); ++i) {
if (i > 0) {
std::cout << ' ';
}
std::cout << open_fds[i];
}
std::cout << '\n';
}
std::cout.flush();
return 0;
}
int mode_env_dump()
{
std::vector<std::string> vars;
if (environ != nullptr) {
for (char** p = environ; *p != nullptr; ++p) {
vars.emplace_back(*p);
}
}
std::sort(vars.begin(), vars.end());
for (const auto& entry : vars) {
std::cout << entry << '\n';
}
std::cout.flush();
return 0;
}
int mode_cwd()
{
std::array<char, 4096> buf{};
if (::getcwd(buf.data(), buf.size()) == nullptr) {
return 1;
}
std::cout << buf.data() << '\n' << std::flush;
return 0;
}
std::uint16_t read_u16_be(const std::uint8_t* p) noexcept
{
return static_cast<std::uint16_t>((static_cast<std::uint16_t>(p[0]) << 8) | p[1]);
}
std::uint32_t read_u32_be(const std::uint8_t* p) noexcept
{
return (static_cast<std::uint32_t>(p[0]) << 24) |
(static_cast<std::uint32_t>(p[1]) << 16) |
(static_cast<std::uint32_t>(p[2]) << 8) |
static_cast<std::uint32_t>(p[3]);
}
void write_u16_be(std::uint8_t* p, std::uint16_t v) noexcept
{
p[0] = static_cast<std::uint8_t>((v >> 8) & 0xffu);
p[1] = static_cast<std::uint8_t>(v & 0xffu);
}
void write_u32_be(std::uint8_t* p, std::uint32_t v) noexcept
{
p[0] = static_cast<std::uint8_t>((v >> 24) & 0xffu);
p[1] = static_cast<std::uint8_t>((v >> 16) & 0xffu);
p[2] = static_cast<std::uint8_t>((v >> 8) & 0xffu);
p[3] = static_cast<std::uint8_t>(v & 0xffu);
}
int mode_ipc_pipe_echo()
{
for (;;) {
std::array<std::uint8_t, 24> hdr{};
bool clean_eof = false;
if (!read_exact_fd(STDIN_FILENO, hdr.data(), hdr.size(), clean_eof)) {
return clean_eof ? 0 : 1;
}
if (hdr[0] != 'V' || hdr[1] != 'D' || hdr[2] != 'I' || hdr[3] != 'P') {
return 3;
}
const std::uint16_t version = read_u16_be(hdr.data() + 4);
const std::uint16_t flags_type = read_u16_be(hdr.data() + 6);
const std::uint32_t payload_len = read_u32_be(hdr.data() + 8);
const std::uint32_t stream_id = read_u32_be(hdr.data() + 12);
if (version != 1 || stream_id != 0 || payload_len > 2u * 1024u * 1024u) {
return 4;
}
std::vector<std::uint8_t> payload(payload_len);
if (payload_len > 0) {
bool eof2 = false;
if (!read_exact_fd(STDIN_FILENO, payload.data(), payload_len, eof2)) {
return 5;
}
}
const std::uint8_t frame_type = static_cast<std::uint8_t>(flags_type & 0xffu);
if (frame_type == 7) { // goaway
return 0;
}
if (frame_type == 1 || frame_type == 2) { // hello -> hello, request -> response
std::array<std::uint8_t, 24> out_hdr = hdr;
const std::uint8_t reply_type = (frame_type == 1) ? 1u : 3u;
write_u16_be(out_hdr.data() + 6, reply_type);
write_u32_be(out_hdr.data() + 8, payload_len);
if (!write_all_fd(STDOUT_FILENO, out_hdr.data(), out_hdr.size())) {
return 6;
}
if (payload_len > 0 && !write_all_fd(STDOUT_FILENO, payload.data(), payload.size())) {
return 7;
}
}
}
}
} // namespace
int main(int argc, char** argv)
@@ -153,5 +482,29 @@ int main(int argc, char** argv)
if (mode == "lines") {
return mode_lines(argc, argv);
}
if (mode == "ignore-sigterm") {
return mode_ignore_sigterm(argc, argv);
}
if (mode == "simultaneous-io") {
return mode_simultaneous_io(argc, argv);
}
if (mode == "flood") {
return mode_flood(argc, argv);
}
if (mode == "long-line") {
return mode_long_line(argc, argv);
}
if (mode == "check-fds") {
return mode_check_fds();
}
if (mode == "env-dump") {
return mode_env_dump();
}
if (mode == "cwd") {
return mode_cwd();
}
if (mode == "ipc-pipe-echo") {
return mode_ipc_pipe_echo();
}
return usage_error("unknown mode");
}
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidArchiveOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Archive)
add_executable(void_archive_only_consumer main.cpp)
target_link_libraries(void_archive_only_consumer PRIVATE Void::Archive)
target_compile_features(void_archive_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME ArchiveOnlyConsumer COMMAND void_archive_only_consumer)
+26
View File
@@ -0,0 +1,26 @@
#include <Void/Archive/Archive.hpp>
#include <array>
#include <cstddef>
int main()
{
const std::array<Void::Archive::CreateEntry, 1> entries{{
Void::Archive::CreateEntry{
.path = "hello.txt",
.type = Void::Archive::EntryType::RegularFile,
.content = {std::byte{'h'}, std::byte{'i'}},
},
}};
Void::Archive::VectorByteSink sink;
if (!Void::Archive::create_archive(sink, entries).has_value()) {
return 1;
}
Void::Archive::SpanByteSource src{sink.bytes()};
auto listed = Void::Archive::list_entries(src);
if (!listed.has_value() || listed->size() != 1U ||
(*listed)[0].path != "hello.txt") {
return 2;
}
return 0;
}
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidCryptoAsyncOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS CryptoAsync)
add_executable(void_crypto_async_only_consumer main.cpp)
target_link_libraries(void_crypto_async_only_consumer PRIVATE Void::CryptoAsync)
target_compile_features(void_crypto_async_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME CryptoAsyncOnlyConsumer COMMAND void_crypto_async_only_consumer)
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more